forked from denodrivers/postgres
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpacket_reader.ts
47 lines (39 loc) · 1.1 KB
/
packet_reader.ts
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
import { readInt16BE, readInt32BE } from "./utils.ts";
export class PacketReader {
private offset: number = 0;
private decoder: TextDecoder = new TextDecoder();
constructor(private buffer: Uint8Array) {}
readInt16(): number {
const value = readInt16BE(this.buffer, this.offset);
this.offset += 2;
return value;
}
readInt32(): number {
const value = readInt32BE(this.buffer, this.offset);
this.offset += 4;
return value;
}
readByte(): number {
return this.readBytes(1)[0];
}
readBytes(length: number): Uint8Array {
const start = this.offset;
const end = start + length;
const slice = this.buffer.slice(start, end);
this.offset = end;
return slice;
}
readString(length: number): string {
const bytes = this.readBytes(length);
return this.decoder.decode(bytes);
}
readCString(): string {
const start = this.offset;
// find next null byte
const end = this.buffer.indexOf(0, start);
const slice = this.buffer.slice(start, end);
// add +1 for null byte
this.offset = end + 1;
return this.decoder.decode(slice);
}
}