blob: b25be618f45ca24e2b993789e5696d76fc0a57ef [file] [log] [blame]
Randolf Jungbcb3bc82023-06-26 16:30:141module.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 Rudenko1552f2b2023-07-11 11:18:3211 clear () {
12 this.top = this.btm = 0
13 this.next = null
14 this.buffer.fill(undefined)
15 }
16
Randolf Jungbcb3bc82023-06-26 16:30:1417 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}