-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTransferableDataStructure.ts
More file actions
40 lines (35 loc) · 1.67 KB
/
TransferableDataStructure.ts
File metadata and controls
40 lines (35 loc) · 1.67 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
export default abstract class TransferableDataStructure {
// Default size of the decoder buffer that's always reused (in bytes)
private static readonly DECODER_BUFFER_SIZE = 16384;
// This buffer can be reused to decode the keys of each pair in the map (and avoids us having to reallocate a new
// block of memory for each `get` or `set` operation).
private decoderBuffer: ArrayBuffer = new ArrayBuffer(TransferableDataStructure.DECODER_BUFFER_SIZE);
private currentDecoderBufferSize: number = TransferableDataStructure.DECODER_BUFFER_SIZE;
// Check if the current environment supports decoding directly from a SharedArrayBuffer view.
protected static readonly SUPPORTS_SAB_VIEW = (() => {
try {
if (typeof SharedArrayBuffer === "undefined") return false;
const sab = new SharedArrayBuffer(0);
const view = new Uint8Array(sab);
new TextDecoder().decode(view);
return true;
} catch {
return false;
}
})();
protected allocateMemory(byteSize: number): SharedArrayBuffer | ArrayBuffer {
try {
return new SharedArrayBuffer(byteSize);
} catch (err) {
throw new Error(`Could not allocate memory. Tried to allocate ${byteSize} bytes.`);
}
}
protected getFittingDecoderBuffer(minimumSize: number): ArrayBuffer {
if (this.currentDecoderBufferSize < minimumSize) {
const nextPowerOfTwo = 2 ** Math.ceil(Math.log2(minimumSize));
this.decoderBuffer = new ArrayBuffer(nextPowerOfTwo);
this.currentDecoderBufferSize = nextPowerOfTwo;
}
return this.decoderBuffer;
}
}