| 1 | /** |
| 2 | * Default buffer size. |
| 3 | */ |
| 4 | export const defaultBufferSize = 2048 |
| 5 | |
| 6 | /** |
| 7 | * Circular buffer designed for positive numbers. |
| 8 | * |
| 9 | * @internal |
| 10 | */ |
| 11 | export class CircularBuffer { |
| 12 | private readIdx: number |
| 13 | private writeIdx: number |
| 14 | private readonly items: Float32Array |
| 15 | private readonly maxArrayIdx: number |
| 16 | public size: number |
| 17 | |
| 18 | /** |
| 19 | * @param size - Buffer size. @defaultValue defaultBufferSize |
| 20 | * @returns CircularBuffer. |
| 21 | */ |
| 22 | constructor (size: number = defaultBufferSize) { |
| 23 | this.checkSize(size) |
| 24 | this.readIdx = 0 |
| 25 | this.writeIdx = 0 |
| 26 | this.maxArrayIdx = size - 1 |
| 27 | this.size = 0 |
| 28 | this.items = new Float32Array(size).fill(-1) |
| 29 | } |
| 30 | |
| 31 | /** |
| 32 | * Checks whether the buffer is empty. |
| 33 | * |
| 34 | * @returns Whether the buffer is empty. |
| 35 | */ |
| 36 | public empty (): boolean { |
| 37 | return this.size === 0 |
| 38 | } |
| 39 | |
| 40 | /** |
| 41 | * Checks whether the buffer is full. |
| 42 | * |
| 43 | * @returns Whether the buffer is full. |
| 44 | */ |
| 45 | public full (): boolean { |
| 46 | return this.size === this.items.length |
| 47 | } |
| 48 | |
| 49 | /** |
| 50 | * Puts number into buffer. |
| 51 | * |
| 52 | * @param number - Number to put into buffer. |
| 53 | */ |
| 54 | public put (number: number): void { |
| 55 | this.items[this.writeIdx] = number |
| 56 | this.writeIdx = this.writeIdx === this.maxArrayIdx ? 0 : this.writeIdx + 1 |
| 57 | if (this.size < this.items.length) { |
| 58 | ++this.size |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | /** |
| 63 | * Gets number from buffer. |
| 64 | * |
| 65 | * @returns Number from buffer. |
| 66 | */ |
| 67 | public get (): number | undefined { |
| 68 | const number = this.items[this.readIdx] |
| 69 | if (number === -1) { |
| 70 | return |
| 71 | } |
| 72 | this.items[this.readIdx] = -1 |
| 73 | this.readIdx = this.readIdx === this.maxArrayIdx ? 0 : this.readIdx + 1 |
| 74 | --this.size |
| 75 | return number |
| 76 | } |
| 77 | |
| 78 | /** |
| 79 | * Returns buffer as numbers' array. |
| 80 | * |
| 81 | * @returns Numbers' array. |
| 82 | */ |
| 83 | public toArray (): number[] { |
| 84 | return Array.from(this.items.filter(item => item !== -1)) |
| 85 | } |
| 86 | |
| 87 | /** |
| 88 | * Checks the buffer size. |
| 89 | * |
| 90 | * @param size - Buffer size. |
| 91 | */ |
| 92 | private checkSize (size: number): void { |
| 93 | if (!Number.isSafeInteger(size)) { |
| 94 | throw new TypeError( |
| 95 | `Invalid circular buffer size: '${size}' is not an integer` |
| 96 | ) |
| 97 | } |
| 98 | if (size < 0) { |
| 99 | throw new RangeError(`Invalid circular buffer size: ${size} < 0`) |
| 100 | } |
| 101 | } |
| 102 | } |