UNPKG

@thi.ng/buffers

Version:

General purpose and generic read/write buffer implementations with different behaviors/orderings

56 lines (55 loc) 1.04 kB
import { assert } from "@thi.ng/errors/assert"; const fifo = (cap) => new FIFOBuffer(cap); class FIFOBuffer { buf; rpos = 0; wpos = 0; len = 0; constructor(cap = 1) { assert(cap >= 1, `capacity must be >= 1`); this.buf = new Array(cap); } get length() { return this.len; } clear() { this.buf.fill(void 0); } copy() { const buf = new FIFOBuffer(1); buf.buf = this.buf.slice(); buf.rpos = this.rpos; buf.wpos = this.wpos; buf.len = this.len; return buf; } readable() { return this.len > 0; } read() { const { buf, rpos } = this; const val = buf[rpos]; buf[rpos] = void 0; this.rpos = (rpos + 1) % buf.length; this.len--; return val; } peek() { const { buf, rpos } = this; return buf[rpos]; } writable() { return this.len < this.buf.length; } write(x) { const { buf, wpos } = this; buf[wpos] = x; this.wpos = (wpos + 1) % buf.length; this.len++; return true; } } export { FIFOBuffer, fifo };