| 1 | /** |
| 2 | * Default buffer size. |
| 3 | */ |
| 4 | export const defaultBufferSize = 2048 |
| 5 | |
| 6 | /** |
| 7 | * Circular buffer |
| 8 | * |
| 9 | * @typeParam T - Type of buffer data. |
| 10 | * @internal |
| 11 | */ |
| 12 | export class CircularBuffer<T> { |
| 13 | private readonly readIdx: number |
| 14 | private writeIdx: number |
| 15 | private items: Array<T | undefined> |
| 16 | private readonly maxArrayIdx: 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.items = new Array<T | undefined>(size) |
| 28 | } |
| 29 | |
| 30 | /** |
| 31 | * Puts data into buffer. |
| 32 | * |
| 33 | * @param data - Data to put into buffer. |
| 34 | */ |
| 35 | public put (data: T): void { |
| 36 | this.items[this.writeIdx] = data |
| 37 | this.writeIdx = this.writeIdx === this.maxArrayIdx ? 0 : this.writeIdx + 1 |
| 38 | } |
| 39 | |
| 40 | /** |
| 41 | * Returns buffer as array. |
| 42 | * |
| 43 | * @returns Array of buffer data. |
| 44 | */ |
| 45 | public toArray (): T[] { |
| 46 | return this.items.filter(item => item != null) as T[] |
| 47 | } |
| 48 | |
| 49 | private checkSize (size: number): void { |
| 50 | if (!Number.isSafeInteger(size)) { |
| 51 | throw new TypeError( |
| 52 | `Invalid circular buffer size: ${size} is not an integer` |
| 53 | ) |
| 54 | } |
| 55 | if (size < 0) { |
| 56 | throw new RangeError(`Invalid circular buffer size: ${size} < 0`) |
| 57 | } |
| 58 | } |
| 59 | } |