| 362 | } |
| 363 | |
| 364 | export class AsyncMutex { |
| 365 | private locked = false; |
| 366 | private resolverQueue: (() => void)[] = []; |
| 367 | |
| 368 | lock() { |
| 369 | if (!this.locked) { |
| 370 | // Fast path |
| 371 | this.locked = true; |
| 372 | return this.createLock(false, null); |
| 373 | } |
| 374 | |
| 375 | const { promise, resolve } = promiseWithResolvers(); |
| 376 | this.resolverQueue.push(resolve); |
| 377 | |
| 378 | return this.createLock(true, promise); |
| 379 | } |
| 380 | |
| 381 | private createLock(pending: boolean, ready: Promise<void> | null): AsyncMutexLock { |
| 382 | let released = false; |
| 383 | |
| 384 | return { |
| 385 | pending, |
| 386 | ready, |
| 387 | release: () => { |
| 388 | if (released) return; |
| 389 | released = true; |
| 390 | this.dispatch(); |
| 391 | }, |
| 392 | [Symbol.dispose]() { |
| 393 | this.release(); |
| 394 | }, |
| 395 | }; |
| 396 | } |
| 397 | |
| 398 | private dispatch() { |
| 399 | if (this.resolverQueue.length > 0) { |
| 400 | const resolve = this.resolverQueue.shift()!; |
| 401 | resolve(); |
| 402 | } else { |
| 403 | this.locked = false; |
| 404 | } |
| 405 | } |
| 406 | } |
| 407 | |
| 408 | export class Bitstream { |
| 409 | /** Current offset in bits. */ |
nothing calls this directly
no outgoing calls
no test coverage detected