This repository was archived by the owner on Apr 5, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
46 lines (31 loc) · 1.24 KB
/
index.ts
File metadata and controls
46 lines (31 loc) · 1.24 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
import { ArrayList } from "../../structures/array-list";
/**
* A utility to help with consuming buffer data.
*/
export class BufferReader {
private readHeadPosition = 0;
constructor(private readonly buffer: Buffer) { }
public bytesLeft = () => this.buffer.length - this.readHeadPosition;
/**
* Reads the sequentially longer slices of the buffer and queries the predicate function with them.
* When the predicate returns true for a slice, that slice is returned.
*
* Should the slice to be tested reach the end of the buffer,
* that slice will be returned regardless of the predicate
*
* **Resumes from where it left off the next time it's called.**
* @param predicate A function to test slices
*/
public readBytesUntil = (predicate: (slice: ArrayList<number>) => boolean) => {
const output = new ArrayList<number>();
let offset = 0;
do {
const readIndex = this.readHeadPosition + offset;
if (readIndex >= this.buffer.length) break;
output.add(this.buffer.readUInt8(readIndex));
offset++;
} while (!predicate(output));
this.readHeadPosition += offset;
return output;
}
}