Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
add jsdoc
  • Loading branch information
Uzlopak committed Sep 10, 2024
commit 530f0610607578f9338e2c89495067c91efeb709
44 changes: 44 additions & 0 deletions lib/dispatcher/fixed-queue.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,27 +54,56 @@ const kMask = kSize - 1
// `top + 1 === bottom` it's full. This wastes a single space of storage
// but allows much quicker checks.

/**
* @type {FixedCircularBuffer}
* @template T
*/
class FixedCircularBuffer {
constructor () {
/**
* @type {number}
*/
this.bottom = 0
/**
* @type {number}
*/
this.top = 0
/**
* @type {Array<T|undefined>}
*/
this.list = new Array(kSize).fill(undefined)
/**
* @type {T|null}
*/
this.next = null
}

/**
* @returns {boolean}
*/
isEmpty () {
return this.top === this.bottom
}

/**
* @returns {boolean}
*/
isFull () {
return ((this.top + 1) & kMask) === this.bottom
}

/**
* @param {T} data
* @returns {void}
*/
push (data) {
this.list[this.top] = data
this.top = (this.top + 1) & kMask
}

/**
* @returns {T|null}
*/
shift () {
const nextItem = this.list[this.bottom]
if (nextItem === undefined) { return null }
Expand All @@ -84,15 +113,27 @@ class FixedCircularBuffer {
}
}

/**
* @template T
*/
module.exports = class FixedQueue {
constructor () {
/**
* @type {FixedCircularBuffer<T>}
*/
this.head = this.tail = new FixedCircularBuffer()
}

/**
* @returns {boolean}
*/
isEmpty () {
return this.head.isEmpty()
}

/**
* @param {T} data
*/
push (data) {
if (this.head.isFull()) {
// Head is full: Creates a new queue, sets the old queue's `.next` to it,
Expand All @@ -102,6 +143,9 @@ module.exports = class FixedQueue {
this.head.push(data)
}

/**
* @returns {T|null}
*/
shift () {
const tail = this.tail
const next = tail.shift()
Expand Down