X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fcircular-buffer.ts;h=7d12069fe369b48c72bf592d9b46a8eae0294031;hb=fcfc3353eb4053c02f64c80a14ae142d44388a71;hp=9f9678d18dbf439690d3ddd3f8787a6e2ca6fb74;hpb=db89e3bcb546d7302179437c4fa88d6fd03bccf0;p=poolifier.git diff --git a/src/circular-buffer.ts b/src/circular-buffer.ts index 9f9678d1..7d12069f 100644 --- a/src/circular-buffer.ts +++ b/src/circular-buffer.ts @@ -4,16 +4,16 @@ export const defaultBufferSize = 2048 /** - * Circular buffer + * Circular buffer designed for positive numbers. * - * @typeParam T - Type of buffer data. * @internal */ -export class CircularBuffer { - private readonly readIdx: number +export class CircularBuffer { + private readIdx: number private writeIdx: number - private items: Array + private readonly items: Float32Array private readonly maxArrayIdx: number + public size: number /** * @param size - Buffer size. @defaultValue defaultBufferSize @@ -24,32 +24,75 @@ export class CircularBuffer { this.readIdx = 0 this.writeIdx = 0 this.maxArrayIdx = size - 1 - this.items = new Array(size) + this.size = 0 + this.items = new Float32Array(size).fill(-1) } /** - * Puts data into buffer. + * Checks whether the buffer is empty. * - * @param data - Data to put into buffer. + * @returns Whether the buffer is empty. */ - public put (data: T): void { - this.items[this.writeIdx] = data + public empty (): boolean { + return this.size === 0 + } + + /** + * Checks whether the buffer is full. + * + * @returns Whether the buffer is full. + */ + public full (): boolean { + return this.size === this.items.length + } + + /** + * Puts number into buffer. + * + * @param number - Number to put into buffer. + */ + public put (number: number): void { + this.items[this.writeIdx] = number this.writeIdx = this.writeIdx === this.maxArrayIdx ? 0 : this.writeIdx + 1 + if (this.size < this.items.length) { + ++this.size + } + } + + /** + * Gets number from buffer. + * + * @returns Number from buffer. + */ + public get (): number | undefined { + const number = this.items[this.readIdx] + if (number === -1) { + return + } + this.items[this.readIdx] = -1 + this.readIdx = this.readIdx === this.maxArrayIdx ? 0 : this.readIdx + 1 + --this.size + return number } /** - * Returns buffer as array. + * Returns buffer as numbers' array. * - * @returns Array of buffer data. + * @returns Numbers' array. */ - public toArray (): T[] { - return this.items.filter(item => item != null) as T[] + public toArray (): number[] { + return Array.from(this.items.filter(item => item !== -1)) } + /** + * Checks the buffer size. + * + * @param size - Buffer size. + */ private checkSize (size: number): void { if (!Number.isSafeInteger(size)) { throw new TypeError( - `Invalid circular buffer size: ${size} is not an integer` + `Invalid circular buffer size: '${size}' is not an integer` ) } if (size < 0) {