Randolf Jung | bcb3bc8 | 2023-06-26 16:30:14 | [diff] [blame] | 1 | module.exports = class FixedFIFO { |
| 2 | constructor (hwm) { |
| 3 | if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two') |
| 4 | this.buffer = new Array(hwm) |
| 5 | this.mask = hwm - 1 |
| 6 | this.top = 0 |
| 7 | this.btm = 0 |
| 8 | this.next = null |
| 9 | } |
| 10 | |
Alex Rudenko | 1552f2b | 2023-07-11 11:18:32 | [diff] [blame] | 11 | clear () { |
| 12 | this.top = this.btm = 0 |
| 13 | this.next = null |
| 14 | this.buffer.fill(undefined) |
| 15 | } |
| 16 | |
Randolf Jung | bcb3bc8 | 2023-06-26 16:30:14 | [diff] [blame] | 17 | push (data) { |
| 18 | if (this.buffer[this.top] !== undefined) return false |
| 19 | this.buffer[this.top] = data |
| 20 | this.top = (this.top + 1) & this.mask |
| 21 | return true |
| 22 | } |
| 23 | |
| 24 | shift () { |
| 25 | const last = this.buffer[this.btm] |
| 26 | if (last === undefined) return undefined |
| 27 | this.buffer[this.btm] = undefined |
| 28 | this.btm = (this.btm + 1) & this.mask |
| 29 | return last |
| 30 | } |
| 31 | |
| 32 | peek () { |
| 33 | return this.buffer[this.btm] |
| 34 | } |
| 35 | |
| 36 | isEmpty () { |
| 37 | return this.buffer[this.btm] === undefined |
| 38 | } |
| 39 | } |