X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fcircular-buffer.ts;h=55f5f9bfc22e48f6f6e42da61c252ec124ac0bca;hb=eadb37e247acfa716cad2a1e211c947513c251bf;hp=baa921920f26e3e8b82ebad79f8642577acfc892;hpb=b84939fe9d58fad558fe33eb08ab99ce0b9bb5c7;p=poolifier.git diff --git a/src/circular-buffer.ts b/src/circular-buffer.ts index baa92192..55f5f9bf 100644 --- a/src/circular-buffer.ts +++ b/src/circular-buffer.ts @@ -1,46 +1,87 @@ /** - * Default buffer size + * Default buffer size. */ export const defaultBufferSize = 2048 /** - * Circular buffer + * Circular buffer designed for positive numbers. + * + * @internal */ -export class CircularBuffer { - private readonly readIdx: number +export class CircularBuffer { + private readIdx: number private writeIdx: number - private items: Array + private items: Float32Array private readonly maxArrayIdx: number + public size: number /** - * @param size - Buffer size - * @returns CircularBuffer + * @param size - Buffer size. @defaultValue defaultBufferSize + * @returns CircularBuffer. */ constructor (size: number = defaultBufferSize) { this.checkSize(size) 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 T[] + * @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)) } private checkSize (size: number): void {