Tanoda
CircularObjectBuffer.cs
Go to the documentation of this file.
1/******************************************************************************
2 * Copyright (C) Ultraleap, Inc. 2011-2020. *
3 * *
4 * Use subject to the terms of the Apache License 2.0 available at *
5 * http://www.apache.org/licenses/LICENSE-2.0, or another agreement *
6 * between Ultraleap and you, your company or other organization. *
7 ******************************************************************************/
8
9namespace LeapInternal {
10 //TODO add test for thread safety
11
22 public class CircularObjectBuffer<T> where T : new() {
23 private T[] array;
24 private int current = 0;
25 private object locker = new object();
26 public int Count { get; private set; }
27 public int Capacity { get; private set; }
28 public bool IsEmpty { get; private set; }
29
30 public CircularObjectBuffer(int capacity) {
31 Capacity = capacity;
32 array = new T[this.Capacity];
33 current = 0;
34 Count = 0;
35 IsEmpty = true;
36 }
37
39 public virtual void Put(ref T item) {
40 lock (locker) {
41 if (!IsEmpty) {
42 current++;
43 if (current >= Capacity) {
44 current = 0;
45 }
46 }
47 if (Count < Capacity)
48 Count++;
49
50 lock (array) {
51 array[current] = item;
52 }
53 IsEmpty = false;
54 }
55 }
56
58 public void Get(out T t, int index = 0) {
59 lock (locker) {
60 if (IsEmpty || (index > Count - 1) || index < 0) {
61 t = new T(); //default(T);
62 } else {
63 int effectiveIndex = current - index;
64 if (effectiveIndex < 0) {
65 effectiveIndex += Capacity;
66 }
67
68 t = array[effectiveIndex];
69 }
70 }
71 }
72
74 public void Resize(int newCapacity) {
75 lock (locker) {
76 if (newCapacity <= Capacity) {
77 return;
78 }
79
80 T[] newArray = new T[newCapacity];
81 int j = 0;
82 for (int i = Count - 1; i >= 0; i--) {
83 T t;
84 Get(out t, i);
85 newArray[j++] = t;
86 }
87 this.array = newArray;
88 this.Capacity = newCapacity;
89 }
90 }
91 }
92}
93
void Get(out T t, int index=0)