From a4b96c68a4ad515e98d17e0d6022fd6be94d560f Mon Sep 17 00:00:00 2001 From: Karsten Schmidt Date: Tue, 24 Dec 2024 13:58:50 +0100 Subject: [PATCH] feat(buffers): add `IReadBuffer.peek()` - update `FIFOBuffer` & `LIFOBuffer` impls - add tests --- packages/buffers/src/api.ts | 8 +++++++- packages/buffers/src/fifo.ts | 5 +++++ packages/buffers/src/lifo.ts | 4 ++++ packages/buffers/test/main.test.ts | 2 ++ 4 files changed, 18 insertions(+), 1 deletion(-) diff --git a/packages/buffers/src/api.ts b/packages/buffers/src/api.ts index b7e2605d0e..cb42e966cd 100644 --- a/packages/buffers/src/api.ts +++ b/packages/buffers/src/api.ts @@ -17,9 +17,15 @@ export interface IReadBuffer { /** * Unguarded read operation. Assumes the caller checked * {@link IReadBuffer.readable} immediately before. Returns next value from - * buffer. + * buffer and removes it (from buffer). */ read(): T; + /** + * Unguarded & immutable read operation. Assumes the caller checked + * {@link IReadBuffer.readable} immediately before. Returns what would be + * the next value read from buffer (without removing it). + */ + peek(): T; } /** diff --git a/packages/buffers/src/fifo.ts b/packages/buffers/src/fifo.ts index 10e65d969c..9d432f6fbb 100644 --- a/packages/buffers/src/fifo.ts +++ b/packages/buffers/src/fifo.ts @@ -59,6 +59,11 @@ export class FIFOBuffer implements IReadWriteBuffer { return val; } + peek() { + const { buf, rpos } = this; + return buf[rpos]!; + } + writable() { return (this.wpos + 1) % this.buf.length !== this.rpos; } diff --git a/packages/buffers/src/lifo.ts b/packages/buffers/src/lifo.ts index 1eb984cb5b..ce62e18700 100644 --- a/packages/buffers/src/lifo.ts +++ b/packages/buffers/src/lifo.ts @@ -42,6 +42,10 @@ export class LIFOBuffer implements IReadWriteBuffer { return this.buf.pop()!; } + peek() { + return this.buf[this.buf.length - 1]; + } + writable() { return this.buf.length < this.cap; } diff --git a/packages/buffers/test/main.test.ts b/packages/buffers/test/main.test.ts index bb1b363bd8..a1cb7889f9 100644 --- a/packages/buffers/test/main.test.ts +++ b/packages/buffers/test/main.test.ts @@ -6,6 +6,7 @@ test("fifo", () => { expect(b.readable()).toBeFalse(); expect(b.writable()).toBeTrue(); expect(b.write(1)).toBeTrue(); + expect(b.peek()).toBe(1); expect(b.readable()).toBeTrue(); expect(b.writable()).toBeTrue(); expect(b.write(2)).toBeTrue(); @@ -28,6 +29,7 @@ test("lifo", () => { expect(b.readable()).toBeFalse(); expect(b.writable()).toBeTrue(); expect(b.write(1)).toBeTrue(); + expect(b.peek()).toBe(1); expect(b.readable()).toBeTrue(); expect(b.writable()).toBeTrue(); expect(b.write(2)).toBeTrue();