| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
package com.android.internal.util; |
| 18 |
|
| 19 |
import static com.android.internal.util.Preconditions.checkArgumentPositive; |
| 20 |
|
| 21 |
import java.lang.reflect.Array; |
| 22 |
import java.util.Arrays; |
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
public class RingBuffer<T> { |
| 31 |
|
| 32 |
|
| 33 |
private final T[] mBuffer; |
| 34 |
|
| 35 |
|
| 36 |
private long mCursor = 0; |
| 37 |
|
| 38 |
public RingBuffer(Class<T> c, int capacity) { |
| 39 |
checkArgumentPositive(capacity, "A RingBuffer cannot have 0 capacity"); |
| 40 |
|
| 41 |
mBuffer = (T[]) Array.newInstance(c, capacity); |
| 42 |
} |
| 43 |
|
| 44 |
public int size() { |
| 45 |
return (int) Math.min(mBuffer.length, (long) mCursor); |
| 46 |
} |
| 47 |
|
| 48 |
public boolean isEmpty() { |
| 49 |
return size() == 0; |
| 50 |
} |
| 51 |
|
| 52 |
public void clear() { |
| 53 |
for (int i = 0; i < size(); ++i) { |
| 54 |
mBuffer[i] = null; |
| 55 |
} |
| 56 |
mCursor = 0; |
| 57 |
} |
| 58 |
|
| 59 |
public void append(T t) { |
| 60 |
mBuffer[indexOf(mCursor++)] = t; |
| 61 |
} |
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
public T getNextSlot() { |
| 69 |
final int nextSlotIdx = indexOf(mCursor++); |
| 70 |
if (mBuffer[nextSlotIdx] == null) { |
| 71 |
mBuffer[nextSlotIdx] = createNewItem(); |
| 72 |
} |
| 73 |
return mBuffer[nextSlotIdx]; |
| 74 |
} |
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
protected T createNewItem() { |
| 80 |
try { |
| 81 |
return (T) mBuffer.getClass().getComponentType().newInstance(); |
| 82 |
} catch (IllegalAccessException | InstantiationException e) { |
| 83 |
return null; |
| 84 |
} |
| 85 |
} |
| 86 |
|
| 87 |
public T[] toArray() { |
| 88 |
|
| 89 |
T[] out = Arrays.copyOf(mBuffer, size(), (Class<T[]>) mBuffer.getClass()); |
| 90 |
|
| 91 |
long inCursor = mCursor - 1; |
| 92 |
int outIdx = out.length - 1; |
| 93 |
while (outIdx >= 0) { |
| 94 |
out[outIdx--] = (T) mBuffer[indexOf(inCursor--)]; |
| 95 |
} |
| 96 |
return out; |
| 97 |
} |
| 98 |
|
| 99 |
private int indexOf(long cursor) { |
| 100 |
return (int) Math.abs(cursor % mBuffer.length); |
| 101 |
} |
| 102 |
} |