Add 'buffer.manager.ts'

This commit is contained in:
Matthew Bessette 2022-02-14 06:23:54 +00:00
parent 7ef25e55e4
commit 96178f028c
1 changed files with 33 additions and 0 deletions

33
buffer.manager.ts Normal file
View File

@ -0,0 +1,33 @@
export class BufferManager {
private buffer: Buffer;
constructor(
private readonly maxBufferSize: number,
) {
this.buffer = Buffer.alloc(0);
}
hasRoom(chunk: Buffer): boolean {
return chunk.length + this.buffer.length <= this.maxBufferSize;
}
append(chunk: Buffer) {
if (!this.hasRoom(chunk)) {
throw new Error('Buffer overflow - data will be lost. Check hasRoom before calling');
}
this.buffer = Buffer.concat([this.buffer, chunk]);
}
appendAndGetCompletedBuffer(chunk: Buffer): Buffer {
const fillSize = this.maxBufferSize - this.buffer.length;
const completedBuffer = Buffer.concat([this.buffer, chunk.slice(0, fillSize)]);
this.buffer = Buffer.from(chunk.slice(fillSize, chunk.length)); // ??? could be an issue
return completedBuffer;
}
}