/** * @description 表示可挂入等待队列的节点最小结构。 * * 队列本身不关心节点承载的业务数据,只要求节点能记录自己是否在队列中,以及前后相邻节点。 */ export interface InternalWaitQueueEntry> { isQueued: boolean previous: Entry | undefined next: Entry | undefined } /** * @description 表示面向等待者节点的双向链表队列。 */ export class InternalWaitQueue> { private head: Entry | undefined private tail: Entry | undefined private count: number constructor() { this.head = undefined this.tail = undefined this.count = 0 } /** * @description 查看当前队头节点但不移除。 */ peek(): Entry | undefined { return this.head } /** * @description 读取队列中的节点数量。 */ getCount(): number { return this.count } /** * @description 判断队列是否为空。 */ isEmpty(): boolean { return this.head === undefined } /** * @description 把节点追加到队尾。 */ enqueue(entry: Entry): void { entry.previous = this.tail entry.next = undefined entry.isQueued = true if (this.tail === undefined) { this.head = entry } else { this.tail.next = entry } this.tail = entry this.count = this.count + 1 } /** * @description 从队列中移除指定节点。 * * 该操作不要求节点位于队头,因此适合被 timeout 或 abort 的等待者直接自移除。 */ remove(entry: Entry): void { if (entry.isQueued === false) { return } if (entry.previous === undefined) { this.head = entry.next } else { entry.previous.next = entry.next } if (entry.next === undefined) { this.tail = entry.previous } else { entry.next.previous = entry.previous } entry.previous = undefined entry.next = undefined entry.isQueued = false this.count = this.count - 1 } /** * @description 取出并返回队头节点。 */ shift(): Entry | undefined { const head = this.head if (head === undefined) { return undefined } this.remove(head) return head } }