fixed-size.js 875 B

123456789101112131415161718192021222324252627282930313233343536373839
  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. clear () {
  11. this.top = this.btm = 0
  12. this.next = null
  13. this.buffer.fill(undefined)
  14. }
  15. push (data) {
  16. if (this.buffer[this.top] !== undefined) return false
  17. this.buffer[this.top] = data
  18. this.top = (this.top + 1) & this.mask
  19. return true
  20. }
  21. shift () {
  22. const last = this.buffer[this.btm]
  23. if (last === undefined) return undefined
  24. this.buffer[this.btm] = undefined
  25. this.btm = (this.btm + 1) & this.mask
  26. return last
  27. }
  28. peek () {
  29. return this.buffer[this.btm]
  30. }
  31. isEmpty () {
  32. return this.buffer[this.btm] === undefined
  33. }
  34. }