-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathbufferReader.ts
More file actions
61 lines (53 loc) · 1.55 KB
/
bufferReader.ts
File metadata and controls
61 lines (53 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { Type, TypedValue } from "./typesystem";
/**
* Interface for codec operations.
*/
export interface ICodec {
decodeTopLevel(buffer: Buffer, type: Type): TypedValue;
encodeTopLevel(typedValue: TypedValue): Buffer;
}
/**
* Helper class for reading typed values from buffers sequentially.
* Maintains an internal pointer to track position in the buffer array.
*/
export class BufferReader {
private readonly buffers: Buffer[];
private readonly codec: ICodec;
private bufferIndex: number = 0;
constructor(buffers: Buffer[], codec: ICodec) {
this.buffers = buffers || [];
this.codec = codec;
}
/**
* Returns true if all buffers have been consumed.
*/
hasReachedEnd(): boolean {
return this.bufferIndex >= this.buffers.length;
}
/**
* Reads and decodes the next buffer using the provided type.
* Advances the internal pointer after reading.
*
* @param type - The type to use for decoding
* @returns The decoded typed value, or null if no more buffers available
*/
decodeNext(type: Type): TypedValue | null {
if (this.hasReachedEnd()) {
return null;
}
const buffer = this.buffers[this.bufferIndex++];
return this.codec.decodeTopLevel(buffer, type);
}
/**
* Gets the current position in the buffer array.
*/
getPosition(): number {
return this.bufferIndex;
}
/**
* Gets the total number of buffers.
*/
getLength(): number {
return this.buffers.length;
}
}