refactor RingBuffer
This commit is contained in:
+25
-16
@@ -1,25 +1,34 @@
|
||||
export default class RingBuffer<T> {
|
||||
export type Pooled<T> = {
|
||||
size: number;
|
||||
mask: number;
|
||||
cursor: number;
|
||||
buffer: Array<T>;
|
||||
};
|
||||
|
||||
constructor(size: number, blueprint: T) {
|
||||
if ((size & (size - 1)) !== 0) {
|
||||
throw new Error("size must be a power of two");
|
||||
}
|
||||
|
||||
this.size = size;
|
||||
this.mask = size - 1;
|
||||
this.cursor = 0;
|
||||
this.buffer = [];
|
||||
|
||||
for (let i = 0; i < size; i++) {
|
||||
this.buffer.push(structuredClone(blueprint));
|
||||
}
|
||||
export function createRingBuffer<T extends object>(
|
||||
size: number,
|
||||
create: () => T,
|
||||
): Pooled<T> {
|
||||
if ((size & (size - 1)) !== 0) {
|
||||
throw new Error("size must be a power of two");
|
||||
}
|
||||
|
||||
next(): T {
|
||||
return this.buffer[this.cursor++ & this.mask];
|
||||
const buffer = new Array<T>(size);
|
||||
for (let i = 0; i < size; i++) {
|
||||
buffer[i] = create();
|
||||
}
|
||||
|
||||
return {
|
||||
size,
|
||||
mask: size - 1,
|
||||
cursor: 0,
|
||||
buffer,
|
||||
};
|
||||
}
|
||||
|
||||
export function claim<T>(pooled: Pooled<T>): T {
|
||||
const slot = pooled.buffer[pooled.cursor];
|
||||
pooled.cursor = (pooled.cursor + 1) & pooled.mask;
|
||||
|
||||
return slot;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user