Skip to content

Commit

Permalink
feat(buffers): add IReadBuffer.peek()
Browse files Browse the repository at this point in the history
- update `FIFOBuffer` & `LIFOBuffer` impls
- add tests
  • Loading branch information
postspectacular committed Dec 24, 2024
1 parent 5f8f8df commit a4b96c6
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 1 deletion.
8 changes: 7 additions & 1 deletion packages/buffers/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,15 @@ export interface IReadBuffer<T> {
/**
* 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;
}

/**
Expand Down
5 changes: 5 additions & 0 deletions packages/buffers/src/fifo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,11 @@ export class FIFOBuffer<T> implements IReadWriteBuffer<T> {
return val;
}

peek() {
const { buf, rpos } = this;
return buf[rpos]!;
}

writable() {
return (this.wpos + 1) % this.buf.length !== this.rpos;
}
Expand Down
4 changes: 4 additions & 0 deletions packages/buffers/src/lifo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ export class LIFOBuffer<T> implements IReadWriteBuffer<T> {
return this.buf.pop()!;
}

peek() {
return this.buf[this.buf.length - 1];
}

writable() {
return this.buf.length < this.cap;
}
Expand Down
2 changes: 2 additions & 0 deletions packages/buffers/test/main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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();
Expand Down

0 comments on commit a4b96c6

Please sign in to comment.