-
Notifications
You must be signed in to change notification settings - Fork 77
/
TempBuffer.ts
71 lines (61 loc) · 2.18 KB
/
TempBuffer.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { ISeekableWriter } from "./ISeekableWriter";
import { IWritable } from "./IWritable";
import { IReadable } from "./types";
/**
* In-memory buffer used for reading and writing MCAP files in tests. Can be used as both an IReadable and an IWritable.
*/
export class TempBuffer implements IReadable, IWritable, ISeekableWriter {
#buffer = new ArrayBuffer(0);
#position = 0;
constructor(source?: ArrayBufferView | ArrayBuffer) {
if (source instanceof ArrayBuffer) {
this.#buffer = source;
} else if (source) {
this.#buffer = new Uint8Array(source.buffer, source.byteOffset, source.byteLength).buffer;
}
}
#setCapacity(capacity: number) {
if (this.#buffer.byteLength !== capacity) {
const newBuffer = new ArrayBuffer(capacity);
new Uint8Array(newBuffer).set(
new Uint8Array(this.#buffer, 0, Math.min(this.#buffer.byteLength, capacity)),
);
this.#buffer = newBuffer;
}
}
position(): bigint {
return BigInt(this.#position);
}
async seek(position: bigint): Promise<void> {
if (position < 0n) {
throw new Error(`Attempted to seek to negative position ${position}`);
} else if (position > this.#buffer.byteLength) {
this.#setCapacity(Number(position));
}
this.#position = Number(position);
}
async truncate(): Promise<void> {
const newBuffer = new ArrayBuffer(this.#position);
new Uint8Array(newBuffer).set(new Uint8Array(this.#buffer, 0, this.#position));
this.#buffer = newBuffer;
}
async write(data: Uint8Array): Promise<void> {
if (this.#position + data.byteLength > this.#buffer.byteLength) {
this.#setCapacity(this.#position + data.byteLength);
}
new Uint8Array(this.#buffer, this.#position).set(data);
this.#position += data.byteLength;
}
async size(): Promise<bigint> {
return BigInt(this.#buffer.byteLength);
}
async read(offset: bigint, size: bigint): Promise<Uint8Array> {
if (offset < 0n || offset + size > BigInt(this.#buffer.byteLength)) {
throw new Error("read out of range");
}
return new Uint8Array(this.#buffer, Number(offset), Number(size));
}
get(): Uint8Array {
return new Uint8Array(this.#buffer);
}
}