-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathapi.ts
More file actions
238 lines (205 loc) · 6.96 KB
/
Copy pathapi.ts
File metadata and controls
238 lines (205 loc) · 6.96 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import { initializeArrayBuffer, incrementRefCount } from "./store";
import { createObjectWrapper } from "./objectWrapper";
import type {
ObjectBufferSettings,
GlobalCarrier,
MemoryStats,
} from "./interfaces";
import {
arrayBufferCopyTo,
externalArgsApiToExternalArgsApi,
getInternalAPI,
isSupportedTopLevelValue,
getEndiannessOfSystem,
} from "./utils";
import {
INITIAL_ENTRY_POINTER_TO_POINTER,
MEM_POOL_START,
ENDIANNESS_FLAG_POINTER,
} from "./consts";
import { OutOfMemoryError, UnsupportedOperationError } from "./exceptions";
import { saveValueIterative } from "./saveValue";
import { TransactionalAllocator } from "./TransactionalAllocator";
import { freeNoLongerUsedAddresses } from "./freeNoLongerUsedAddresses";
/**
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer#Browser_compatibility
*
* Future holds additional types https://github.com/tc39/proposal-resizablearraybuffer
*/
export type ArrayBufferKind = "vanilla" | "shared";
/**
* Create a new objectBuffer, with the given initial value
* @param size The size of the ArrayBuffer to create (heap size)
* @param initialValue
* @param settings
* @param arrayBufferConstructor
*/
export function createObjectBuffer<T = any>(
size: number,
initialValue: T,
settings: ObjectBufferSettings = {},
arrayBufferKind: ArrayBufferKind = "vanilla"
): T {
if (!isSupportedTopLevelValue(initialValue)) {
throw new UnsupportedOperationError();
}
const allocator = new TransactionalAllocator(
{ start: MEM_POOL_START, size },
arrayBufferKind === "shared"
);
const arrayBuffer = allocator.getArrayBuffer();
initializeArrayBuffer(arrayBuffer);
const carrier: GlobalCarrier = { allocator, heap: allocator.getHeap() };
const referencedPointers: number[] = [];
allocator.transaction(() => {
saveValueIterative(
externalArgsApiToExternalArgsApi(settings),
carrier,
referencedPointers,
INITIAL_ENTRY_POINTER_TO_POINTER,
initialValue
);
});
for (const pointer of referencedPointers) {
incrementRefCount(carrier.heap, pointer);
}
const dv = new DataView(arrayBuffer);
// endianness flag is always saved in little endian so we can read in every system endianness
dv.setUint32(ENDIANNESS_FLAG_POINTER, getEndiannessOfSystem(), true);
return createObjectWrapper(
externalArgsApiToExternalArgsApi(settings),
carrier,
carrier.heap.u32[
INITIAL_ENTRY_POINTER_TO_POINTER / Uint32Array.BYTES_PER_ELEMENT
]
);
}
/**
* Grow or shrink the underlying ArrayBuffer
*
* @unstable
* Due to possible issues with future support of typed arrays,
* and the upcoming proposal, this api function may be removed
* https://github.com/tc39/proposal-resizablearraybuffer
*
* @param objectBuffer
* @param newSize
*
*/
export function unstable_resizeObjectBuffer(
objectBuffer: unknown,
newSize: number
) {
if (newSize < memoryStats(objectBuffer).top) {
throw new OutOfMemoryError();
}
const oldArrayBuffer = getUnderlyingArrayBuffer(objectBuffer);
const newArrayBuffer = new ArrayBuffer(newSize);
arrayBufferCopyTo(
oldArrayBuffer,
0,
Math.min(newSize, oldArrayBuffer.byteLength),
newArrayBuffer,
0
);
unstable_replaceUnderlyingArrayBuffer(objectBuffer, newArrayBuffer);
return newArrayBuffer;
}
export function getUnderlyingArrayBuffer(
objectBuffer: unknown
): ArrayBuffer | SharedArrayBuffer {
return getInternalAPI(objectBuffer).getCarrier().heap.u8.buffer;
}
/**
* Create objectBuffer object from the given ArrayBuffer
*
* The given ArrayBuffer is expected to be one obtained via getUnderlyingArrayBuffer
* This operation doesn't change any value in the ArrayBuffer
*
* @param settings
* @param arrayBuffer
*/
export function loadObjectBuffer<T = any>(
arrayBuffer: ArrayBuffer | SharedArrayBuffer,
settings: ObjectBufferSettings = {}
): T {
const allocator = TransactionalAllocator.load(arrayBuffer);
const carrier: GlobalCarrier = { allocator, heap: allocator.getHeap() };
const dv = new DataView(arrayBuffer);
// endianness flag is always saved in little endian so we can read in every system endianness
const endiannessOfGivenAb = dv.getUint32(ENDIANNESS_FLAG_POINTER, true);
if (endiannessOfGivenAb !== getEndiannessOfSystem()) {
throw new Error("Endianness mismatch");
}
return createObjectWrapper(
externalArgsApiToExternalArgsApi(settings),
carrier,
carrier.heap.u32[
INITIAL_ENTRY_POINTER_TO_POINTER / Uint32Array.BYTES_PER_ELEMENT
]
);
}
/**
* Replace the Underlying array buffer with the given one.
* The given ArrayBuffer is expected to be a copy of the prev ArrayBuffer,
* just bigger or smaller (less free space)
*
* Consider using `resizeObjectBuffer`
*
* @unstable
* Due to possible issues with future support of typed arrays,
* and the upcoming proposal, this api function may be removed
* https://github.com/tc39/proposal-resizablearraybuffer
*
* @param objectBuffer
* @param newArrayBuffer
*/
export function unstable_replaceUnderlyingArrayBuffer(
objectBuffer: unknown,
newArrayBuffer: ArrayBuffer | SharedArrayBuffer
) {
const allocator = TransactionalAllocator.load(newArrayBuffer);
const carrier: GlobalCarrier = { allocator, heap: allocator.getHeap() };
const dv = new DataView(newArrayBuffer);
// endianness flag is always saved in little endian so we can read in every system endianness
const endiannessOfGivenAb = dv.getUint32(ENDIANNESS_FLAG_POINTER, true);
if (endiannessOfGivenAb !== getEndiannessOfSystem()) {
throw new Error("Endianness mismatch");
}
allocator.setNewEnd(newArrayBuffer.byteLength);
getInternalAPI(objectBuffer).replaceCarrierContent(carrier);
}
/**
* Return the number of free & used bytes left in the given objectBuffer
*/
export function memoryStats(objectBuffer: unknown): MemoryStats {
const { available, total, top } = getInternalAPI(objectBuffer)
.getCarrier()
.allocator.stats();
return { available, used: total - available, total, top };
}
export { reclaim, queueReclaim } from "./reclaim";
/**
* Update the settings of the given ObjectBuffer
*/
export function updateObjectBufferSettings(
objectBuffer: unknown,
options: ObjectBufferSettings
) {
Object.assign(getInternalAPI(objectBuffer).getExternalArgs(), options);
}
export function readObjectBufferSettings(objectBuffer: unknown) {
return getInternalAPI(objectBuffer).getExternalArgs();
}
/**
* Free all the addresses collected using FinalizationRegistry
* When no FinalizationRegistry/WeakRef available, use disposeWrapperObject
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry
*
* This is not called automatic by FinalizationRegistry,
* because It's only safe to call it when you have a lock/similar (As any other operation)
* And FinalizationRegistry might run when ever
*/
export function processQueuedReclaims(objectBuffer: unknown) {
freeNoLongerUsedAddresses(getInternalAPI(objectBuffer).getCarrier());
}