balloc 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +7 -0
- package/README.MD +433 -0
- package/README.ar.md +405 -0
- package/README.en.md +433 -0
- package/README.es.md +405 -0
- package/README.jp.md +404 -0
- package/README.pt.md +433 -0
- package/README.zh.md +404 -0
- package/docs/API /342/200/224 balloc.ar.md" +1365 -0
- package/docs/API /342/200/224 balloc.en.md" +1264 -0
- package/docs/API /342/200/224 balloc.es.md" +1180 -0
- package/docs/API /342/200/224 balloc.jp.md" +1087 -0
- package/docs/API /342/200/224 balloc.pt.md" +1214 -0
- package/docs/API /342/200/224 balloc.zh.md" +1168 -0
- package/img/pix.png +0 -0
- package/package.json +109 -6
- package/src/ar/balloc.cjs +1079 -0
- package/src/ar/balloc.js +2 -0
- package/src/ar/balloc.mjs +1327 -0
- package/src/en/balloc.cjs +1091 -0
- package/src/en/balloc.js +2 -0
- package/src/en/balloc.mjs +1339 -0
- package/src/es/balloc.cjs +1111 -0
- package/src/es/balloc.js +2 -0
- package/src/es/balloc.mjs +1360 -0
- package/src/jp/balloc.cjs +1067 -0
- package/src/jp/balloc.js +2 -0
- package/src/jp/balloc.mjs +1315 -0
- package/src/pt/balloc.cjs +1114 -0
- package/src/pt/balloc.js +2 -0
- package/src/pt/balloc.mjs +1362 -0
- package/src/zh/balloc.cjs +1013 -0
- package/src/zh/balloc.js +2 -0
- package/src/zh/balloc.mjs +1262 -0
- package/types/ar/balloc.d.mts +647 -0
- package/types/en/balloc.d.mts +659 -0
- package/types/es/balloc.d.mts +679 -0
- package/types/jp/balloc.d.mts +635 -0
- package/types/pt/balloc.d.mts +682 -0
- package/types/zh/balloc.d.mts +581 -0
- package/README.md +0 -3
|
@@ -0,0 +1,1362 @@
|
|
|
1
|
+
import { encode, decode } from 'cbor-x';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Flag indicando valor inválido ou desconhecido.
|
|
5
|
+
*/
|
|
6
|
+
const UNKNOWN = 0xFFFFFFFF >>> 0;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Tamanhos e tipos de bucket válidos.
|
|
10
|
+
* Somente tamanhos 8, 16, 32 e 64 bits são suportados para tipos inteiros e
|
|
11
|
+
* Somente tamanhos 16, 32 e 64 bits são suportados para floats.
|
|
12
|
+
* Somente tipos de dados são suportados:
|
|
13
|
+
* u = usigned integer
|
|
14
|
+
* i = signed integer
|
|
15
|
+
* f = float
|
|
16
|
+
*
|
|
17
|
+
* Sintaxe do identificador de bucket:
|
|
18
|
+
*
|
|
19
|
+
* [Tamanho em bits][tipo de dados]
|
|
20
|
+
*
|
|
21
|
+
* Exemplos:
|
|
22
|
+
* Um bucket inteiro não sinalizado de 32-bits: 32u
|
|
23
|
+
* Um bucket inteiro sinalizado de 64-bits: 64i
|
|
24
|
+
*
|
|
25
|
+
*/
|
|
26
|
+
const BUCKET_MAPPING = Object.freeze({
|
|
27
|
+
"8u": { type: "Uint8", bits: 8 },
|
|
28
|
+
"16u": { type: "Uint16", bits: 16 },
|
|
29
|
+
"32u": { type: "Uint32", bits: 32 },
|
|
30
|
+
"64u": { type: "BigUint64", bits: 64 },
|
|
31
|
+
"8i": { type: "Int8", bits: 8 },
|
|
32
|
+
"16i": { type: "Int16", bits: 16 },
|
|
33
|
+
"32i": { type: "Int32", bits: 32 },
|
|
34
|
+
"64i": { type: "BigInt64", bits: 64 },
|
|
35
|
+
"16f": { type: "Float16", bits: 16 },
|
|
36
|
+
"32f": { type: "Float32", bits: 32 },
|
|
37
|
+
"64f": { type: "Float64", bits: 64 }
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Tipos de bucket suportados pelo alocador:
|
|
42
|
+
* - Inteiros não sinalizados: '8u', '16u', '32u', '64u'
|
|
43
|
+
* - Inteiros sinalizados: '8i', '16i', '32i', '64i'
|
|
44
|
+
* - Ponto flutuante: '16f', '32f', '64f'
|
|
45
|
+
*
|
|
46
|
+
* @typedef {'8u'|'16u'|'32u'|'64u'|'8i'|'16i'|'32i'|'64i'|'16f'|'32f'|'64f'} BucketType
|
|
47
|
+
*/
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Flag de endianness do sistema.
|
|
51
|
+
*
|
|
52
|
+
* Detecta se o sistema é Little Endian, o que afeta
|
|
53
|
+
* a ordem de bytes em operações DataView.
|
|
54
|
+
*/
|
|
55
|
+
const IS_LITTLE_ENDIAN = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Formato dos metadados.
|
|
60
|
+
* 0 4 8 9 10
|
|
61
|
+
* [32bits address][32bits occupied][8bits capacity][8bits cookie][48bits reserved]
|
|
62
|
+
*
|
|
63
|
+
* Total: 4 + 4 + 1 + 1 + 6 = 16 bytes
|
|
64
|
+
*/
|
|
65
|
+
const HEADER_SIZE = 16 >>> 0;
|
|
66
|
+
|
|
67
|
+
const ADDRESS_OFFSET = 0 >>> 0;
|
|
68
|
+
const OCCUPIED_OFFSET = 4 >>> 0;
|
|
69
|
+
const CAPACITY_OFFSET = 8 >>> 0;
|
|
70
|
+
const COOKIE_OFFSET = 9 >>> 0;
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
const ROTATE_32BITS = 4294967296;
|
|
74
|
+
const CLAMP_11BITS = 0x7FF >>> 0;
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Estrutura contendo os metadado codificados num handler.
|
|
78
|
+
*
|
|
79
|
+
* @typedef {Object} Metadata
|
|
80
|
+
* @property {number} byteCapacity - A capacidade em bytes do bloco de memória.
|
|
81
|
+
* @property {number} capacityExponent - A capacidade do bloco de memória expresso como exponte de base dois.
|
|
82
|
+
* @property {number} dataAddress - Endereço do bloco de memória dentro do dataBus.
|
|
83
|
+
* @property {number} generation - Geração cujo o handler pertence.
|
|
84
|
+
* @property {number} headerAddress - Endereço do header dentro do controlBus.
|
|
85
|
+
* @property {number} occupied - Número de elementos ocupados no bloco.
|
|
86
|
+
*/
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Verifica se um valor é uma instância de TypedArray.
|
|
90
|
+
*
|
|
91
|
+
* @param {any} val - Valor a ser testado.
|
|
92
|
+
* @returns {boolean} `true` se o valor for um TypedArray, caso contrário `false`.
|
|
93
|
+
*/
|
|
94
|
+
const isTypedArray = (val) => ArrayBuffer.isView(val) && !(val instanceof DataView);
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Echo Stack Dual Bus Bump Allocator with ReBump GC.
|
|
98
|
+
*/
|
|
99
|
+
export default class Balloc {
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Cria uma instância do alocador de memória `Balloc`.
|
|
103
|
+
*
|
|
104
|
+
* O alocador mantém dois buffers independentes:
|
|
105
|
+
* - `dataBus`: armazena os dados dos blocos alocados;
|
|
106
|
+
* - `controlBus`: armazena os headers e demais metadados de controle.
|
|
107
|
+
*
|
|
108
|
+
* Cada bloco possui um header de tamanho fixo (`HEADER_SIZE`) e é
|
|
109
|
+
* identificado externamente por um handler de 43 bits lógicos, composto
|
|
110
|
+
* por uma geração de 11 bits e pelo endereço de seu header em 32 bits.
|
|
111
|
+
*
|
|
112
|
+
* A capacidade de cada bloco é arredondada para a próxima potência de
|
|
113
|
+
* dois em elementos, respeitando a largura do bucket configurado.
|
|
114
|
+
*
|
|
115
|
+
* @param {number} [size=65535] - Capacidade inicial do `dataBus`, em bytes.
|
|
116
|
+
* Deve ser um inteiro seguro no intervalo [2, 0x80000000].
|
|
117
|
+
* @param {BucketType} [bucketSize="32u"] - Identificador do tipo e tamanho do bucket
|
|
118
|
+
* (ex: '32u' para Uint32, '64f' para Float64, '8i' para Int8).
|
|
119
|
+
* @param {number} [metadataSize=1024] - Capacidade inicial do `controlBus`,
|
|
120
|
+
* em bytes. Deve ser um inteiro seguro no intervalo
|
|
121
|
+
* [HEADER_SIZE, 0x80000000].
|
|
122
|
+
*
|
|
123
|
+
* @throws {RangeError} Se `size` estiver fora do intervalo permitido.
|
|
124
|
+
* @throws {RangeError} Se `bucketSize` não for um identificador de bucket válido.
|
|
125
|
+
* @throws {RangeError} Se `metadataSize` estiver fora do intervalo permitido.
|
|
126
|
+
*/
|
|
127
|
+
constructor(size = 65535, bucketSize = "32u", metadataSize = 1024) {
|
|
128
|
+
|
|
129
|
+
if (!Number.isSafeInteger(size) || size < 2 || size > 0x80000000) throw new RangeError(`Parameter size must be in range [2, 0x80000000] but size is ${size}`);
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
if (!BUCKET_MAPPING[bucketSize]) {
|
|
133
|
+
throw new RangeError(`bucketSize must be in ([ 8 || 16 || 32 || 64][ u || i ]) || ([ 16 || 32 || 64][ f ]) but I found ${bucketSize}`);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
if (!Number.isSafeInteger(metadataSize) || metadataSize < HEADER_SIZE || metadataSize > 0x80000000) throw new RangeError(`Parameter metadataSize must be in range [HEADER_SIZE, 0x80000000] but metadataSize is ${metadataSize}`);
|
|
137
|
+
|
|
138
|
+
this.wordType = bucketSize;
|
|
139
|
+
this.bucketType = BUCKET_MAPPING[bucketSize].type;
|
|
140
|
+
this.bucketSize = BUCKET_MAPPING[bucketSize].bits >>> 0;
|
|
141
|
+
this.bucketArray = globalThis[`${this.bucketType}Array`];
|
|
142
|
+
this.wordSize = this.bucketSize >>> 3;
|
|
143
|
+
this.wordShift = this.bucketSize >>> 4;
|
|
144
|
+
this.size = Math.max(1 << (32 - Math.clz32(size)) >>> 0, this.wordSize);
|
|
145
|
+
this.headerSize = 1 << (32 - Math.clz32(metadataSize)) >>> 0;
|
|
146
|
+
this.dataPointer = 0 >>> 0;
|
|
147
|
+
this.controlPointer = 0 >>> 0;
|
|
148
|
+
this.echoPointer = 0 >>> 0;
|
|
149
|
+
this.generation = 0 >>> 0;
|
|
150
|
+
this.dataBus = new Uint8Array(this.size);
|
|
151
|
+
this.controlBus = new Uint8Array(this.headerSize);
|
|
152
|
+
this.dataAdapter = new DataView(this.dataBus.buffer);
|
|
153
|
+
this.controlAdapter = new DataView(this.controlBus.buffer);
|
|
154
|
+
this.auxiliary = new globalThis[`${this.bucketType}Array`](this.dataBus.buffer);
|
|
155
|
+
this.writer = this.dataAdapter[`set${this.bucketType}`].bind(this.dataAdapter);
|
|
156
|
+
this.reader = this.dataAdapter[`get${this.bucketType}`].bind(this.dataAdapter);
|
|
157
|
+
this.recycle = new Map();
|
|
158
|
+
|
|
159
|
+
/** @type {Metadata} */
|
|
160
|
+
this.metadata = {
|
|
161
|
+
generation: 0 >>> 0,
|
|
162
|
+
headerAddress: 0 >>> 0,
|
|
163
|
+
dataAddress: 0 >>> 0,
|
|
164
|
+
capacityExponent: 0 >>> 0,
|
|
165
|
+
byteCapacity: 0 >>> 0,
|
|
166
|
+
occupied: 0 >>> 0,
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// ========== ALOCAÇÃO ==========
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Aloca um novo bloco de memória.
|
|
175
|
+
*
|
|
176
|
+
* A capacidade solicitada é convertida para a menor potência de dois que
|
|
177
|
+
* comporte `size` elementos. O bloco é obtido preferencialmente da lista
|
|
178
|
+
* de regiões recicláveis com a capacidade correspondente; caso não exista
|
|
179
|
+
* uma região compatível, o bloco é reservado no topo do `dataBus`.
|
|
180
|
+
*
|
|
181
|
+
* Em seguida, um header é obtido do espaço de controle. Headers previamente
|
|
182
|
+
* liberados podem ser reutilizados por meio da pilha interna de reciclagem;
|
|
183
|
+
* caso contrário, o `controlBus` é expandido quando necessário.
|
|
184
|
+
*
|
|
185
|
+
* O header recebe o endereço, a capacidade, a ocupação inicial (zero) e
|
|
186
|
+
* um cookie de validação. O valor retornado codifica a geração da alocação
|
|
187
|
+
* e o endereço do header:
|
|
188
|
+
*
|
|
189
|
+
* [11 bits de geração][32 bits de endereço do header]
|
|
190
|
+
*
|
|
191
|
+
* @param {number} [size=16] - Número mínimo de elementos que o bloco deve
|
|
192
|
+
* comportar. Deve ser um inteiro seguro no intervalo [2, 0x80000000].
|
|
193
|
+
* @returns {number} Handler que identifica o bloco alocado.
|
|
194
|
+
* @throws {RangeError} Se `size` estiver fora do intervalo permitido.
|
|
195
|
+
*/
|
|
196
|
+
alloc(size = 16) {
|
|
197
|
+
if (!Number.isSafeInteger(size) || size < 2 || size > 0x80000000) throw new RangeError(`Parameter size must be in range [2, 0x80000000] but size is ${size}`);
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
const capacity = (32 - Math.clz32(size - 1));
|
|
201
|
+
const blockSize = (1 << capacity >>> 0) * this.wordSize;
|
|
202
|
+
|
|
203
|
+
let dataAddress = this.recyclePop(blockSize);
|
|
204
|
+
|
|
205
|
+
if (dataAddress === UNKNOWN) {
|
|
206
|
+
while (this.dataPointer + blockSize > this.size) this.grow();
|
|
207
|
+
dataAddress = this.dataPointer;
|
|
208
|
+
this.dataPointer += blockSize;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
let headerAddress = 0 >>> 0;
|
|
212
|
+
|
|
213
|
+
if (this.echoPointer > this.controlPointer) {
|
|
214
|
+
this.echoPointer -= 4;
|
|
215
|
+
headerAddress = this.controlAdapter.getUint32(this.echoPointer, IS_LITTLE_ENDIAN);
|
|
216
|
+
} else {
|
|
217
|
+
if (this.controlPointer + HEADER_SIZE > this.controlAdapter.byteLength) this.headerGrow();
|
|
218
|
+
headerAddress = this.controlPointer;
|
|
219
|
+
this.controlPointer+= HEADER_SIZE;
|
|
220
|
+
this.echoPointer+= HEADER_SIZE;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
this.controlAdapter.setUint32(headerAddress + ADDRESS_OFFSET, dataAddress, IS_LITTLE_ENDIAN);
|
|
224
|
+
this.controlAdapter.setUint32(headerAddress + OCCUPIED_OFFSET, 0, IS_LITTLE_ENDIAN);
|
|
225
|
+
this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, capacity);
|
|
226
|
+
this.controlAdapter.setUint8(headerAddress + COOKIE_OFFSET, this.bakeCookie(headerAddress, ++this.generation));
|
|
227
|
+
|
|
228
|
+
return (this.generation & CLAMP_11BITS) * ROTATE_32BITS + headerAddress;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Expande a capacidade de um bloco para a próxima potência de dois.
|
|
233
|
+
*
|
|
234
|
+
* Quando o bloco está localizado no topo atual do `dataBus`, a expansão
|
|
235
|
+
* ocorre in-place: somente sua capacidade e o `dataPointer` são
|
|
236
|
+
* atualizados.
|
|
237
|
+
*
|
|
238
|
+
* Caso exista outra região após o bloco, uma nova região com o dobro da
|
|
239
|
+
* capacidade é obtida do espaço reciclável ou alocada no topo do `dataBus`.
|
|
240
|
+
* Os elementos atualmente ocupados são então copiados para a nova região,
|
|
241
|
+
* e a região anterior é devolvida à lista de reciclagem.
|
|
242
|
+
*
|
|
243
|
+
* O handler permanece válido, pois seu header é preservado e apenas o
|
|
244
|
+
* endereço e a capacidade registrados nele são atualizados.
|
|
245
|
+
*
|
|
246
|
+
* @param {number} handler - Handler do bloco a ser expandido.
|
|
247
|
+
* @returns {void}
|
|
248
|
+
* @throws {Error} Se o handler for inválido ou estiver corrompido.
|
|
249
|
+
* @throws {AggregateError} Se a capacidade já tiver atingido o limite
|
|
250
|
+
* máximo suportado.
|
|
251
|
+
*/
|
|
252
|
+
realloc(handler) {
|
|
253
|
+
const generation = (handler / ROTATE_32BITS) & CLAMP_11BITS;
|
|
254
|
+
let headerAddress = handler >>> 0;
|
|
255
|
+
|
|
256
|
+
const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
|
|
257
|
+
const occupied = this.controlAdapter.getUint32(headerAddress + OCCUPIED_OFFSET, IS_LITTLE_ENDIAN);
|
|
258
|
+
const capacity = this.controlAdapter.getUint8(headerAddress + CAPACITY_OFFSET);
|
|
259
|
+
const cookie = this.controlAdapter.getUint8(headerAddress + COOKIE_OFFSET);
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
if (cookie !== this.bakeCookie(headerAddress, generation)) {
|
|
263
|
+
throw new Error("Invalid or corrupted handle");
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
if (capacity >= 31) throw new AggregateError([new Error("Can´t reallocate handler.") ,new RangeError("Capacity has reached its limit.")], "Internal Error.");
|
|
267
|
+
|
|
268
|
+
const newCapacity = capacity + 1;
|
|
269
|
+
const newBlockSize = (1 << newCapacity >>> 0) * this.wordSize;
|
|
270
|
+
const oldBlockSize = (1 << capacity >>> 0) * this.wordSize;
|
|
271
|
+
|
|
272
|
+
if (dataAddress + oldBlockSize === this.dataPointer) {
|
|
273
|
+
while (dataAddress + newBlockSize > this.size) this.grow();
|
|
274
|
+
|
|
275
|
+
this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, newCapacity, IS_LITTLE_ENDIAN);
|
|
276
|
+
this.dataPointer = dataAddress + newBlockSize;
|
|
277
|
+
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
this.recyclePush(oldBlockSize, dataAddress);
|
|
282
|
+
|
|
283
|
+
let newAddress = this.recyclePop(newBlockSize);
|
|
284
|
+
|
|
285
|
+
if (newAddress === UNKNOWN) {
|
|
286
|
+
while (this.dataPointer + newBlockSize > this.size) this.grow();
|
|
287
|
+
|
|
288
|
+
newAddress = this.dataPointer;
|
|
289
|
+
this.dataPointer += newBlockSize;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, newCapacity);
|
|
293
|
+
this.dataBus.copyWithin(newAddress, dataAddress, dataAddress + occupied * this.wordSize);
|
|
294
|
+
|
|
295
|
+
this.controlAdapter.setUint32(headerAddress + ADDRESS_OFFSET, newAddress, IS_LITTLE_ENDIAN);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Libera um bloco de memória.
|
|
300
|
+
*
|
|
301
|
+
* O header do bloco é invalidado pelo zeramento de seu cookie e seu
|
|
302
|
+
* endereço é registrado para posterior reutilização. A região de dados
|
|
303
|
+
* também é devolvida ao sistema de reciclagem, exceto quando o bloco está
|
|
304
|
+
* exatamente no topo do `dataBus`; nesse caso, o `dataPointer` é simplesmente
|
|
305
|
+
* retrocedido, eliminando a região sem criar uma entrada na lista de
|
|
306
|
+
* reciclagem.
|
|
307
|
+
*
|
|
308
|
+
* @param {number} handler - Handler do bloco a ser liberado.
|
|
309
|
+
* @returns {void}
|
|
310
|
+
* @throws {Error} Se o handler for inválido ou estiver corrompido.
|
|
311
|
+
*/
|
|
312
|
+
free(handler) {
|
|
313
|
+
const generation = (handler / ROTATE_32BITS) & CLAMP_11BITS;
|
|
314
|
+
let headerAddress = handler >>> 0;
|
|
315
|
+
|
|
316
|
+
const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
|
|
317
|
+
const capacity = this.controlAdapter.getUint8(headerAddress + CAPACITY_OFFSET);
|
|
318
|
+
const cookie = this.controlAdapter.getUint8(headerAddress + COOKIE_OFFSET);
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
if (cookie !== this.bakeCookie(headerAddress, generation)) {
|
|
322
|
+
throw new Error("Invalid or corrupted handle");
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const blockSize = (1 << capacity >>> 0) * this.wordSize;
|
|
326
|
+
|
|
327
|
+
this.controlAdapter.setUint8(headerAddress + COOKIE_OFFSET, 0);
|
|
328
|
+
|
|
329
|
+
if (this.echoPointer + 4 <= this.controlBus.byteLength) {
|
|
330
|
+
this.controlAdapter.setUint32(this.echoPointer, headerAddress, IS_LITTLE_ENDIAN);
|
|
331
|
+
this.echoPointer += 4;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
if (dataAddress + blockSize === this.dataPointer) {
|
|
336
|
+
this.dataPointer = dataAddress;
|
|
337
|
+
} else {
|
|
338
|
+
this.recyclePush(blockSize, dataAddress);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// ========== RECICLAGEM ==========
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* [USO INTERNO]
|
|
347
|
+
* Insere uma região livre na lista de reciclagem.
|
|
348
|
+
*
|
|
349
|
+
* A lista é organizada por capacidade em bytes. Para cada capacidade, o
|
|
350
|
+
* valor armazenado é um `Uint32Array` cuja posição zero contém a quantidade
|
|
351
|
+
* de endereços registrados e as posições seguintes contêm os endereços das
|
|
352
|
+
* regiões livres:
|
|
353
|
+
*
|
|
354
|
+
* [count, address1, address2, ...]
|
|
355
|
+
*
|
|
356
|
+
* Quando a página fica cheia, seu buffer é expandido para o dobro da
|
|
357
|
+
* capacidade atual.
|
|
358
|
+
*
|
|
359
|
+
* @param {number} capacity - Capacidade da região livre, em bytes.
|
|
360
|
+
* @param {number} address - Endereço inicial da região no `dataBus`.
|
|
361
|
+
* @returns {void}
|
|
362
|
+
* @private
|
|
363
|
+
*/
|
|
364
|
+
recyclePush(capacity, address) {
|
|
365
|
+
if (this.recycle.has(capacity)) {
|
|
366
|
+
let page = this.recycle.get(capacity);
|
|
367
|
+
const count = page[0];
|
|
368
|
+
|
|
369
|
+
if (count === page.length - 1) {
|
|
370
|
+
const newBuffer = page.buffer.transfer(page.buffer.byteLength * 2);
|
|
371
|
+
page = new Uint32Array(newBuffer);
|
|
372
|
+
this.recycle.set(capacity, page);
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
page[count + 1] = address;
|
|
376
|
+
page[0] = count + 1;
|
|
377
|
+
} else {
|
|
378
|
+
this.recycle.set(capacity, new Uint32Array([1, address]));
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/**
|
|
383
|
+
* [USO INTERNO]
|
|
384
|
+
* Remove uma região livre da lista de reciclagem.
|
|
385
|
+
*
|
|
386
|
+
* A busca é feita pela capacidade exata solicitada. Quando existe uma
|
|
387
|
+
* página correspondente, o último endereço registrado é removido da
|
|
388
|
+
* página e retornado, implementando a reciclagem como uma pilha LIFO.
|
|
389
|
+
*
|
|
390
|
+
* @param {number} capacity - Capacidade desejada, em bytes.
|
|
391
|
+
* @returns {number} Endereço inicial de uma região reciclável ou `UNKNOWN`
|
|
392
|
+
* quando não existe uma região com a capacidade solicitada.
|
|
393
|
+
* @private
|
|
394
|
+
*/
|
|
395
|
+
recyclePop(capacity) {
|
|
396
|
+
if (!this.recycle.has(capacity)) return UNKNOWN;
|
|
397
|
+
|
|
398
|
+
const page = this.recycle.get(capacity);
|
|
399
|
+
const count = page[0];
|
|
400
|
+
|
|
401
|
+
if (count === 0) return UNKNOWN;
|
|
402
|
+
|
|
403
|
+
const address = page[count];
|
|
404
|
+
page[0] = count - 1;
|
|
405
|
+
|
|
406
|
+
return address;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
// ========== COLETA DE LIXO ==========
|
|
410
|
+
/**
|
|
411
|
+
* Compacta o `dataBus` por meio do algoritmo ReBump.
|
|
412
|
+
*
|
|
413
|
+
* Percorre sequencialmente os headers registrados no `controlBus` e copia
|
|
414
|
+
* as regiões ainda válidas para um novo `dataBus`, eliminando os espaços
|
|
415
|
+
* livres existentes entre elas. O endereço de cada bloco sobrevivente é
|
|
416
|
+
* atualizado no respectivo header.
|
|
417
|
+
*
|
|
418
|
+
* A ordem dos blocos no `controlBus` é preservada. Os dados internos de
|
|
419
|
+
* cada bloco também são preservados integralmente, incluindo sua capacidade
|
|
420
|
+
* reservada e sua ocupação atual.
|
|
421
|
+
*
|
|
422
|
+
* Ao final da compactação:
|
|
423
|
+
* - todas as regiões recicláveis são eliminadas;
|
|
424
|
+
* - `dataPointer` passa a apontar para o primeiro byte após o último bloco
|
|
425
|
+
* vivo;
|
|
426
|
+
* - o `dataBus` passa a representar um heap contíguo para os blocos ativos.
|
|
427
|
+
*
|
|
428
|
+
* A complexidade de controle é O(n), onde `n` é o número de headers
|
|
429
|
+
* percorridos. O custo efetivo de movimentação de memória também depende
|
|
430
|
+
* do volume de bytes pertencente aos blocos vivos.
|
|
431
|
+
*
|
|
432
|
+
* @returns {void}
|
|
433
|
+
*/
|
|
434
|
+
gc() {
|
|
435
|
+
const newDataBus = new Uint8Array(this.dataBus.buffer.byteLength);
|
|
436
|
+
this.recycle.clear();
|
|
437
|
+
this.dataPointer = 0 >>> 0;
|
|
438
|
+
for (let i = 0; i < this.controlPointer; i+= HEADER_SIZE) {
|
|
439
|
+
if (this.controlBus[i + COOKIE_OFFSET] === 0) continue;
|
|
440
|
+
const start = this.controlAdapter.getUint32(i + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
|
|
441
|
+
const size = (1 << this.controlBus[i + CAPACITY_OFFSET] >>> 0) * this.wordSize;
|
|
442
|
+
const end = start + size;
|
|
443
|
+
newDataBus.set(this.dataBus.subarray(start, end), this.dataPointer);
|
|
444
|
+
this.controlAdapter.setUint32(i + ADDRESS_OFFSET, this.dataPointer, IS_LITTLE_ENDIAN);
|
|
445
|
+
this.dataPointer += size;
|
|
446
|
+
}
|
|
447
|
+
this.dataBus = newDataBus;
|
|
448
|
+
this.dataAdapter = new DataView(this.dataBus.buffer);
|
|
449
|
+
this.auxiliary = new globalThis[`${this.bucketType}Array`](this.dataBus.buffer);
|
|
450
|
+
this.writer = this.dataAdapter[`set${this.bucketType}`].bind(this.dataAdapter);
|
|
451
|
+
this.reader = this.dataAdapter[`get${this.bucketType}`].bind(this.dataAdapter);
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// ========== ESCALONAGEM ==========
|
|
455
|
+
/**
|
|
456
|
+
* [!!! USO INTERNO, NÃO USE NO SEU CÓDIGO !!!]
|
|
457
|
+
* Expande o `dataBus` para o dobro de sua capacidade atual.
|
|
458
|
+
*
|
|
459
|
+
* O buffer subjacente é transferido para um `ArrayBuffer` maior, preservando
|
|
460
|
+
* os dados existentes. Todas as views associadas ao buffer são recriadas
|
|
461
|
+
* para referenciar o novo armazenamento.
|
|
462
|
+
*
|
|
463
|
+
* @returns {void}
|
|
464
|
+
* @throws {RangeError} Se a capacidade do `dataBus` já tiver excedido o
|
|
465
|
+
* limite máximo suportado.
|
|
466
|
+
* @private
|
|
467
|
+
*/
|
|
468
|
+
grow() {
|
|
469
|
+
if (this.size > 0x80000000) throw new RangeError("Data bus capacity exceeded");
|
|
470
|
+
|
|
471
|
+
const newSize = (this.size * 2) >>> 0;
|
|
472
|
+
const newBuffer = this.dataBus.buffer.transfer(newSize);
|
|
473
|
+
|
|
474
|
+
this.size = newSize;
|
|
475
|
+
this.dataBus = new Uint8Array(newBuffer);
|
|
476
|
+
this.dataAdapter = new DataView(newBuffer);
|
|
477
|
+
this.writer = this.dataAdapter[`set${this.bucketType}`].bind(this.dataAdapter);
|
|
478
|
+
this.reader = this.dataAdapter[`get${this.bucketType}`].bind(this.dataAdapter);
|
|
479
|
+
this.auxiliary = new this.bucketArray(newBuffer);
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/**
|
|
483
|
+
* [!!! USO INTERNO, NÃO USE NO SEU CÓDIGO !!!]
|
|
484
|
+
* Expande o `controlBus` para o dobro de sua capacidade atual.
|
|
485
|
+
*
|
|
486
|
+
* O buffer subjacente é transferido para um `ArrayBuffer` maior, preservando
|
|
487
|
+
* os headers existentes. O `controlAdapter` é recriado para referenciar
|
|
488
|
+
* o novo armazenamento.
|
|
489
|
+
*
|
|
490
|
+
* @returns {void}
|
|
491
|
+
* @throws {RangeError} Se a capacidade atual do `controlBus` já tiver
|
|
492
|
+
* excedido o limite máximo suportado.
|
|
493
|
+
* @private
|
|
494
|
+
*/
|
|
495
|
+
headerGrow() {
|
|
496
|
+
if (this.controlBus.byteLength > 0x80000000) throw new RangeError("Control bus capacity exceeded");
|
|
497
|
+
const newSize = (this.controlBus.byteLength * 2) >>> 0;
|
|
498
|
+
const newBuffer = this.controlBus.buffer.transfer(newSize);
|
|
499
|
+
|
|
500
|
+
this.controlBus = new Uint8Array(newBuffer);
|
|
501
|
+
this.controlAdapter = new DataView(newBuffer);
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
// ========== OPERAÇÕES DE STACK ==========
|
|
505
|
+
|
|
506
|
+
/**
|
|
507
|
+
* Adiciona um elemento ao final da sequência ocupada pelo bloco.
|
|
508
|
+
*
|
|
509
|
+
* O elemento é gravado na primeira posição livre após o último elemento
|
|
510
|
+
* ocupado. A ocupação do bloco é incrementada somente quando existe espaço
|
|
511
|
+
* disponível em sua capacidade.
|
|
512
|
+
*
|
|
513
|
+
* @param {number} handler - Handler do bloco.
|
|
514
|
+
* @param {number} value - Valor a ser inserido.
|
|
515
|
+
* @returns {boolean} `true` se o valor foi inserido; `false` se o bloco
|
|
516
|
+
* já estiver sem espaço disponível.
|
|
517
|
+
* @throws {Error} Se o handler for inválido ou estiver corrompido.
|
|
518
|
+
*/
|
|
519
|
+
push(handler, value) {
|
|
520
|
+
|
|
521
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
522
|
+
|
|
523
|
+
if ((meta.occupied + 1) * this.wordSize > meta.byteCapacity) return false;
|
|
524
|
+
|
|
525
|
+
this.writer(meta.dataAddress + meta.occupied * this.wordSize , value, IS_LITTLE_ENDIAN);
|
|
526
|
+
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied + 1,IS_LITTLE_ENDIAN);
|
|
527
|
+
|
|
528
|
+
return true;
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
/**
|
|
532
|
+
* Remove o último elemento ocupado do bloco e o retorna.
|
|
533
|
+
*
|
|
534
|
+
* A ocupação é decrementada antes da leitura do elemento removido. Os
|
|
535
|
+
* bytes correspondentes não são limpos e permanecem na região alocada,
|
|
536
|
+
* mas deixam de fazer parte da sequência ocupada.
|
|
537
|
+
*
|
|
538
|
+
* @param {number} handler - Handler do bloco.
|
|
539
|
+
* @returns {number|undefined} Valor removido ou `undefined` se o bloco
|
|
540
|
+
* estiver vazio.
|
|
541
|
+
* @throws {Error} Se o handler for inválido ou estiver corrompido.
|
|
542
|
+
*/
|
|
543
|
+
pop(handler) {
|
|
544
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
545
|
+
|
|
546
|
+
if (meta.occupied === 0) return undefined;
|
|
547
|
+
|
|
548
|
+
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied - 1,IS_LITTLE_ENDIAN);
|
|
549
|
+
return this.reader(meta.dataAddress + (meta.occupied - 1) * this.wordSize, IS_LITTLE_ENDIAN);
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
/**
|
|
553
|
+
* Retorna o último elemento ocupado sem removê-lo.
|
|
554
|
+
*
|
|
555
|
+
* @param {number} handler - Handler do bloco.
|
|
556
|
+
* @returns {number|undefined} Último valor ocupado ou `undefined` se o
|
|
557
|
+
* bloco estiver vazio.
|
|
558
|
+
* @throws {Error} Se o handler for inválido ou estiver corrompido.
|
|
559
|
+
*/
|
|
560
|
+
peek(handler) {
|
|
561
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
562
|
+
|
|
563
|
+
if (meta.occupied === 0) return undefined;
|
|
564
|
+
|
|
565
|
+
return this.reader(meta.dataAddress + (meta.occupied - 1) * this.wordSize, IS_LITTLE_ENDIAN);
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
// ========== OPERAÇÕES DE QUEUE ==========
|
|
569
|
+
|
|
570
|
+
/**
|
|
571
|
+
* Insere um elemento no início da sequência ocupada.
|
|
572
|
+
*
|
|
573
|
+
* Os elementos atualmente ocupados são deslocados uma posição para a
|
|
574
|
+
* frente e `value` é gravado na primeira posição. A operação exige uma
|
|
575
|
+
* posição livre na capacidade do bloco.
|
|
576
|
+
*
|
|
577
|
+
* O custo da operação é proporcional ao número de elementos ocupados,
|
|
578
|
+
* pois os dados precisam ser deslocados.
|
|
579
|
+
*
|
|
580
|
+
* @param {number} handler - Handler do bloco.
|
|
581
|
+
* @param {number} value - Valor a ser inserido.
|
|
582
|
+
* @returns {boolean} `true` se o valor foi inserido; `false` se o bloco
|
|
583
|
+
* estiver cheio.
|
|
584
|
+
* @throws {Error} Se o handler for inválido ou estiver corrompido.
|
|
585
|
+
*/
|
|
586
|
+
nudge(handler, value) {
|
|
587
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
588
|
+
|
|
589
|
+
if ((meta.occupied + 1) * this.wordSize > meta.byteCapacity) return false;
|
|
590
|
+
|
|
591
|
+
this.dataBus.copyWithin(meta.dataAddress + this.wordSize, meta.dataAddress, meta.dataAddress + meta.occupied * this.wordSize);
|
|
592
|
+
this.writer(meta.dataAddress, value, IS_LITTLE_ENDIAN);
|
|
593
|
+
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied + 1,IS_LITTLE_ENDIAN);
|
|
594
|
+
|
|
595
|
+
return true;
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/**
|
|
599
|
+
* Remove o primeiro elemento ocupado do bloco e o retorna.
|
|
600
|
+
*
|
|
601
|
+
* Os elementos restantes são deslocados uma posição em direção ao início
|
|
602
|
+
* da região ocupada. A capacidade física do bloco permanece inalterada.
|
|
603
|
+
*
|
|
604
|
+
* O custo da operação é proporcional ao número de elementos deslocados.
|
|
605
|
+
*
|
|
606
|
+
* @param {number} handler - Handler do bloco.
|
|
607
|
+
* @returns {number|undefined} Primeiro valor removido ou `undefined` se o
|
|
608
|
+
* bloco estiver vazio.
|
|
609
|
+
* @throws {Error} Se o handler for inválido ou estiver corrompido.
|
|
610
|
+
*/
|
|
611
|
+
pull(handler) {
|
|
612
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
613
|
+
|
|
614
|
+
if (meta.occupied === 0) return undefined;
|
|
615
|
+
|
|
616
|
+
const result = this.reader(meta.dataAddress, IS_LITTLE_ENDIAN);
|
|
617
|
+
this.dataBus.copyWithin(meta.dataAddress, meta.dataAddress + this.wordSize, meta.dataAddress + meta.occupied * this.wordSize);
|
|
618
|
+
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied - 1, IS_LITTLE_ENDIAN);
|
|
619
|
+
return result;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
/**
|
|
623
|
+
* Retorna o primeiro elemento ocupado sem removê-lo.
|
|
624
|
+
*
|
|
625
|
+
* @param {number} handler - Handler do bloco.
|
|
626
|
+
* @returns {number|undefined} Primeiro valor ocupado ou `undefined` se o
|
|
627
|
+
* bloco estiver vazio.
|
|
628
|
+
* @throws {Error} Se o handler for inválido ou estiver corrompido.
|
|
629
|
+
*/
|
|
630
|
+
head(handler) {
|
|
631
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
632
|
+
|
|
633
|
+
if (meta.occupied === 0) return undefined;
|
|
634
|
+
|
|
635
|
+
return this.reader(meta.dataAddress, IS_LITTLE_ENDIAN);
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
// ========== ACESSO ALEATÓRIO ==========
|
|
639
|
+
|
|
640
|
+
/**
|
|
641
|
+
* Verifica se um valor está presente entre os elementos ocupados do bloco.
|
|
642
|
+
*
|
|
643
|
+
* A busca é realizada diretamente sobre a `TypedArray` auxiliar e considera
|
|
644
|
+
* somente o intervalo atualmente ocupado, não toda a capacidade física
|
|
645
|
+
* reservada.
|
|
646
|
+
*
|
|
647
|
+
* @param {number} handler - Handler do bloco.
|
|
648
|
+
* @param {number} value - Valor a ser procurado.
|
|
649
|
+
* @returns {boolean} `true` se `value` estiver presente entre os elementos
|
|
650
|
+
* ocupados; caso contrário, `false`.
|
|
651
|
+
* @throws {Error} Se o handler for inválido ou estiver corrompido.
|
|
652
|
+
*/
|
|
653
|
+
has(handler, value) {
|
|
654
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
655
|
+
|
|
656
|
+
if (meta.occupied === 0) return false;
|
|
657
|
+
|
|
658
|
+
const rawAddres = meta.dataAddress >>> this.wordShift;
|
|
659
|
+
|
|
660
|
+
return this.auxiliary.subarray(rawAddres, rawAddres + meta.occupied).includes(value);
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
/**
|
|
664
|
+
* Retorna o elemento ocupado em um índice baseado em zero.
|
|
665
|
+
*
|
|
666
|
+
* Índices fora do intervalo `[0, occupied)` não são considerados erro e
|
|
667
|
+
* resultam em `undefined`.
|
|
668
|
+
*
|
|
669
|
+
* @param {number} handler - Handler do bloco.
|
|
670
|
+
* @param {number} index - Índice baseado em zero do elemento.
|
|
671
|
+
* @returns {number|undefined} Valor armazenado no índice ou `undefined` se
|
|
672
|
+
* o índice estiver fora da região ocupada.
|
|
673
|
+
* @throws {Error} Se o handler for inválido ou estiver corrompido.
|
|
674
|
+
*/
|
|
675
|
+
get(handler, index) {
|
|
676
|
+
|
|
677
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
678
|
+
|
|
679
|
+
if (index < 0 || index >= meta.occupied) return undefined;
|
|
680
|
+
|
|
681
|
+
return this.reader(meta.dataAddress + index * this.wordSize, IS_LITTLE_ENDIAN);
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
/**
|
|
685
|
+
* Substitui o valor armazenado em um índice ocupado.
|
|
686
|
+
*
|
|
687
|
+
* A operação não altera a ocupação do bloco. Índices fora do intervalo
|
|
688
|
+
* `[0, occupied)` são ignorados e resultam em `false`.
|
|
689
|
+
*
|
|
690
|
+
* @param {number} handler - Handler do bloco.
|
|
691
|
+
* @param {number} index - Índice baseado em zero do elemento.
|
|
692
|
+
* @param {number} value - Novo valor.
|
|
693
|
+
* @returns {boolean} `true` se o valor foi gravado; `false` se o índice
|
|
694
|
+
* estiver fora da região ocupada.
|
|
695
|
+
* @throws {Error} Se o handler for inválido ou estiver corrompido.
|
|
696
|
+
*/
|
|
697
|
+
set(handler, index, value) {
|
|
698
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
699
|
+
|
|
700
|
+
if (index < 0 || index >= meta.occupied) return false;
|
|
701
|
+
|
|
702
|
+
this.writer(meta.dataAddress + index * this.wordSize, value, IS_LITTLE_ENDIAN);
|
|
703
|
+
return true;
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
// ============= MISCELÂNEA ===============
|
|
707
|
+
|
|
708
|
+
/**
|
|
709
|
+
* Zera a ocupação do bloco e preenche toda a sua capacidade física com
|
|
710
|
+
* um mesmo valor.
|
|
711
|
+
*
|
|
712
|
+
* O preenchimento abrange todos os slots disponíveis, não apenas os
|
|
713
|
+
* elementos atualmente ocupados. Após a operação, o bloco é considerado
|
|
714
|
+
* vazio independentemente do valor utilizado no preenchimento.
|
|
715
|
+
*
|
|
716
|
+
* @param {number} handler - Handler do bloco.
|
|
717
|
+
* @param {number} [value=0] - Valor utilizado para preencher todos os slots.
|
|
718
|
+
* @returns {void}
|
|
719
|
+
* @throws {Error} Se o handler for inválido ou estiver corrompido.
|
|
720
|
+
*/
|
|
721
|
+
clear(handler, value=0) {
|
|
722
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
723
|
+
|
|
724
|
+
const slots = meta.byteCapacity / this.wordSize;
|
|
725
|
+
const rawAddress = meta.dataAddress >>> this.wordShift;
|
|
726
|
+
|
|
727
|
+
this.auxiliary.fill(value, rawAddress, rawAddress + slots);
|
|
728
|
+
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, 0, IS_LITTLE_ENDIAN);
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
|
|
732
|
+
/**
|
|
733
|
+
* Preenche um intervalo de slots do bloco com um valor.
|
|
734
|
+
*
|
|
735
|
+
* O intervalo utiliza índices baseados em zero e segue a convenção
|
|
736
|
+
* `[start, end)`, portanto `start` é inclusivo e `end` é exclusivo.
|
|
737
|
+
* Quando `end` não é informado, o preenchimento se estende até o fim da
|
|
738
|
+
* capacidade física do bloco.
|
|
739
|
+
*
|
|
740
|
+
* A ocupação do bloco passa a ser `end`, inclusive quando o intervalo
|
|
741
|
+
* preenchido se estende além da ocupação anterior.
|
|
742
|
+
*
|
|
743
|
+
* @param {number} handler - Handler do bloco.
|
|
744
|
+
* @param {number} value - Valor utilizado no preenchimento.
|
|
745
|
+
* @param {number} [start=0] - Índice inicial, inclusivo.
|
|
746
|
+
* @param {number|null} [end=null] - Índice final, exclusivo. Quando
|
|
747
|
+
* omitido ou `null`, utiliza a capacidade total do bloco.
|
|
748
|
+
* @returns {void}
|
|
749
|
+
* @throws {Error} Se o handler for inválido ou estiver corrompido.
|
|
750
|
+
* @throws {RangeError} Se `start` ou `end` estiver fora dos limites da
|
|
751
|
+
* capacidade, ou se `start > end`.
|
|
752
|
+
*/
|
|
753
|
+
fill(handler, value, start = 0, end = null) {
|
|
754
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
755
|
+
|
|
756
|
+
const slots = meta.byteCapacity / this.wordSize;
|
|
757
|
+
const lastIndex = end ?? slots;
|
|
758
|
+
|
|
759
|
+
if (start > lastIndex) {
|
|
760
|
+
throw new RangeError(`start ${start} must be less or equal than end ${lastIndex}.`);
|
|
761
|
+
}
|
|
762
|
+
if (start < 0 || start > slots) {
|
|
763
|
+
throw new RangeError(`start ${start} out of range [0, ${slots}].`);
|
|
764
|
+
}
|
|
765
|
+
if (lastIndex < 0 || lastIndex > slots) {
|
|
766
|
+
throw new RangeError(`end ${lastIndex} out of range [0, ${slots}].`);
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
const rawAddress = meta.dataAddress >>> this.wordShift;
|
|
770
|
+
|
|
771
|
+
this.auxiliary.fill(value, rawAddress + start, rawAddress + lastIndex);
|
|
772
|
+
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, lastIndex, IS_LITTLE_ENDIAN);
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
/**
|
|
776
|
+
* Preenche todos os slots físicos do bloco com um valor e marca toda a
|
|
777
|
+
* capacidade como ocupada.
|
|
778
|
+
*
|
|
779
|
+
* Diferentemente de `clear()`, a operação resulta em um bloco totalmente
|
|
780
|
+
* ocupado.
|
|
781
|
+
*
|
|
782
|
+
* @param {number} handler - Handler do bloco.
|
|
783
|
+
* @param {number} value - Valor utilizado no preenchimento.
|
|
784
|
+
* @returns {void}
|
|
785
|
+
* @throws {Error} Se o handler for inválido ou estiver corrompido.
|
|
786
|
+
*/
|
|
787
|
+
fillAll(handler, value) {
|
|
788
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
789
|
+
|
|
790
|
+
const rawAddress = meta.dataAddress >>> this.wordShift;
|
|
791
|
+
const capacityElements = meta.byteCapacity / this.wordSize;
|
|
792
|
+
|
|
793
|
+
this.auxiliary.fill(value, rawAddress, rawAddress + capacityElements);
|
|
794
|
+
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, capacityElements, IS_LITTLE_ENDIAN);
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
/**
|
|
798
|
+
* Copia os elementos de uma `Array` ou `TypedArray` para o início do bloco.
|
|
799
|
+
*
|
|
800
|
+
* A quantidade copiada é limitada pela capacidade do bloco. A ocupação é
|
|
801
|
+
* atualizada para o maior valor entre a ocupação anterior e a quantidade
|
|
802
|
+
* efetivamente copiada; portanto, uma chamada a `put()` não reduz a
|
|
803
|
+
* ocupação existente quando recebe uma sequência menor.
|
|
804
|
+
*
|
|
805
|
+
* Para `Array`, somente os primeiros elementos que couberem são copiados.
|
|
806
|
+
* Para `TypedArray`, é utilizado um subarray da origem sem cópia
|
|
807
|
+
* intermediária.
|
|
808
|
+
*
|
|
809
|
+
* @param {number} handler - Handler do bloco.
|
|
810
|
+
* @param {Array|TypedArray} data - Sequência de valores a copiar.
|
|
811
|
+
* @returns {void}
|
|
812
|
+
* @throws {Error} Se o handler for inválido ou estiver corrompido.
|
|
813
|
+
* @throws {TypeError} Se `data` não for uma `Array` nem uma `TypedArray`.
|
|
814
|
+
*/
|
|
815
|
+
put(handler, data) {
|
|
816
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
817
|
+
|
|
818
|
+
const rawAddress = meta.dataAddress >>> this.wordShift;
|
|
819
|
+
const length = Math.min(1 << meta.capacityExponent >>> 0, data.length);
|
|
820
|
+
|
|
821
|
+
meta.occupied = Math.max(length, meta.occupied);
|
|
822
|
+
|
|
823
|
+
if (Array.isArray(data)) {
|
|
824
|
+
this.auxiliary.set(data.slice(0, length), rawAddress);
|
|
825
|
+
} else if (isTypedArray(data)) {
|
|
826
|
+
this.auxiliary.set(data.subarray(0, length), rawAddress);
|
|
827
|
+
} else {
|
|
828
|
+
const actual = data?.constructor?.name ?? (data === null ? 'null' : typeof data);
|
|
829
|
+
throw new TypeError(`data must be Array or TypedArray, but ${actual} was given.`);
|
|
830
|
+
}
|
|
831
|
+
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied, IS_LITTLE_ENDIAN);
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
/**
|
|
835
|
+
* Retorna uma cópia dos elementos atualmente ocupados pelo bloco.
|
|
836
|
+
*
|
|
837
|
+
* O resultado é uma `TypedArray` do mesmo tipo configurado por
|
|
838
|
+
* `bucketSize`. A capacidade física não ocupada não é incluída no resultado.
|
|
839
|
+
*
|
|
840
|
+
* A operação não expõe diretamente o armazenamento interno: o método
|
|
841
|
+
* utiliza `TypedArray.prototype.slice()`, produzindo uma nova view com
|
|
842
|
+
* armazenamento independente.
|
|
843
|
+
*
|
|
844
|
+
* @param {number} handler - Handler do bloco.
|
|
845
|
+
* @returns {TypedArray} Cópia dos elementos ocupados pelo bloco. Quando
|
|
846
|
+
* o bloco está vazio, retorna uma `TypedArray` vazia do tipo configurado.
|
|
847
|
+
* @throws {Error} Se o handler for inválido ou estiver corrompido.
|
|
848
|
+
*/
|
|
849
|
+
pick(handler) {
|
|
850
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
851
|
+
|
|
852
|
+
const rawAddress = meta.dataAddress >>> this.wordShift;
|
|
853
|
+
|
|
854
|
+
if (meta.occupied === 0) {
|
|
855
|
+
return this.auxiliary.slice(rawAddress, rawAddress);
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
return this.auxiliary.slice(rawAddress, rawAddress + meta.occupied);
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
// ======== CAPACIDADE EM SLOTS ==========
|
|
862
|
+
|
|
863
|
+
/**
|
|
864
|
+
* Retorna a capacidade física do bloco em bytes.
|
|
865
|
+
*
|
|
866
|
+
* A capacidade corresponde ao espaço reservado para todos os slots do
|
|
867
|
+
* bloco, independentemente de quantos elementos estejam atualmente
|
|
868
|
+
* ocupados.
|
|
869
|
+
*
|
|
870
|
+
* @param {number} handler - Handler do bloco.
|
|
871
|
+
* @returns {number} Capacidade física do bloco, em bytes.
|
|
872
|
+
* @throws {Error} Se o handler for inválido ou estiver corrompido.
|
|
873
|
+
*/
|
|
874
|
+
byteSize(handler) {
|
|
875
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
876
|
+
return meta.byteCapacity;
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
/**
|
|
880
|
+
* Retorna a quantidade de elementos atualmente ocupados no bloco.
|
|
881
|
+
*
|
|
882
|
+
* @param {number} handler - Handler do bloco.
|
|
883
|
+
* @returns {number} Número de elementos ocupados.
|
|
884
|
+
* @throws {Error} Se o handler for inválido ou estiver corrompido.
|
|
885
|
+
*/
|
|
886
|
+
occupied(handler){
|
|
887
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
888
|
+
return meta.occupied;
|
|
889
|
+
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
/**
|
|
893
|
+
* Retorna a capacidade do bloco em número de elementos.
|
|
894
|
+
*
|
|
895
|
+
* O valor corresponde à quantidade total de slots fisicamente reservados,
|
|
896
|
+
* e não à quantidade atualmente ocupada.
|
|
897
|
+
*
|
|
898
|
+
* @param {number} handler - Handler do bloco.
|
|
899
|
+
* @returns {number} Número total de slots disponíveis no bloco.
|
|
900
|
+
* @throws {Error} Se o handler for inválido ou estiver corrompido.
|
|
901
|
+
*/
|
|
902
|
+
length(handler) {
|
|
903
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
904
|
+
return 1 << meta.capacityExponent >>> 0;
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
// ==========Operações entre blocos=============
|
|
908
|
+
|
|
909
|
+
/**
|
|
910
|
+
* Copia elementos ocupados de um bloco para outro.
|
|
911
|
+
*
|
|
912
|
+
* A cópia começa no primeiro elemento de `source` e no primeiro slot de
|
|
913
|
+
* `destiny`. A quantidade efetivamente copiada é limitada pelo número de
|
|
914
|
+
* elementos ocupados na origem, pela capacidade física do destino e pelo
|
|
915
|
+
* limite especificado em `slots`.
|
|
916
|
+
*
|
|
917
|
+
* A ocupação do destino é elevada, quando necessário, para abranger os
|
|
918
|
+
* elementos copiados. A capacidade do destino não é alterada.
|
|
919
|
+
*
|
|
920
|
+
* A operação utiliza `Uint8Array.prototype.copyWithin()` sobre o `dataBus`,
|
|
921
|
+
* portanto o retorno é o próprio `Uint8Array` que representa o barramento
|
|
922
|
+
* de dados.
|
|
923
|
+
*
|
|
924
|
+
* @param {number} source - Handler do bloco de origem.
|
|
925
|
+
* @param {number} destiny - Handler do bloco de destino.
|
|
926
|
+
* @param {number} [slots=UNKNOWN] - Número máximo de elementos a copiar.
|
|
927
|
+
* `UNKNOWN` representa o valor sentinela utilizado para não impor um
|
|
928
|
+
* limite adicional.
|
|
929
|
+
* @returns {Uint8Array} O `dataBus` após a operação.
|
|
930
|
+
* @throws {Error} Se `source` ou `destiny` for inválido ou estiver corrompido.
|
|
931
|
+
*/
|
|
932
|
+
copy(source, destiny, slots = UNKNOWN){
|
|
933
|
+
/** @type {Metadata} */
|
|
934
|
+
const metaA = {};
|
|
935
|
+
/** @type {Metadata} */
|
|
936
|
+
const metaB = {};
|
|
937
|
+
|
|
938
|
+
this.extractMetadata(source, metaA);
|
|
939
|
+
this.extractMetadata(destiny, metaB);
|
|
940
|
+
|
|
941
|
+
const maxSlotsDest = Math.floor(metaB.byteCapacity / this.wordSize);
|
|
942
|
+
const slotsToCopy = Math.min(metaA.occupied, maxSlotsDest, slots);
|
|
943
|
+
const newOccupied = Math.max(metaB.occupied, slotsToCopy);
|
|
944
|
+
|
|
945
|
+
this.controlAdapter.setUint32(metaB.headerAddress + OCCUPIED_OFFSET, newOccupied, IS_LITTLE_ENDIAN);
|
|
946
|
+
|
|
947
|
+
return this.dataBus.copyWithin(metaB.dataAddress, metaA.dataAddress, metaA.dataAddress + slotsToCopy * this.wordSize);
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
/**
|
|
951
|
+
* Copia uma região de elementos dentro do próprio bloco.
|
|
952
|
+
*
|
|
953
|
+
* Os índices são baseados em zero e seguem a semântica de
|
|
954
|
+
* `Array.prototype.copyWithin()`: `target` identifica a posição de destino,
|
|
955
|
+
* `start` a posição inicial da origem e `length` a quantidade máxima de
|
|
956
|
+
* elementos a copiar.
|
|
957
|
+
*
|
|
958
|
+
* Índices negativos são interpretados a partir do fim da capacidade do
|
|
959
|
+
* bloco. Após essa normalização, os índices são limitados à capacidade
|
|
960
|
+
* física. A quantidade copiada também é limitada pelos elementos
|
|
961
|
+
* efetivamente ocupados e pelo espaço disponível a partir de `target`.
|
|
962
|
+
*
|
|
963
|
+
* A operação suporta regiões sobrepostas e pode aumentar a ocupação do
|
|
964
|
+
* bloco quando o intervalo de destino ultrapassar a ocupação atual.
|
|
965
|
+
*
|
|
966
|
+
* @param {number} handler - Handler do bloco.
|
|
967
|
+
* @param {number} target - Índice inicial do destino.
|
|
968
|
+
* @param {number} start - Índice inicial da origem.
|
|
969
|
+
* @param {number} length - Número máximo de elementos a copiar.
|
|
970
|
+
* @returns {Uint8Array} O `dataBus` após a operação.
|
|
971
|
+
* @throws {Error} Se o handler for inválido ou estiver corrompido.
|
|
972
|
+
*/
|
|
973
|
+
copyWithin(handler, target, start, length) {
|
|
974
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
975
|
+
const slots = Math.floor(meta.byteCapacity / this.wordSize);
|
|
976
|
+
|
|
977
|
+
target = Math.trunc(target);
|
|
978
|
+
start = Math.trunc(start);
|
|
979
|
+
length = Math.trunc(length);
|
|
980
|
+
|
|
981
|
+
if (target < 0) target += slots;
|
|
982
|
+
if (start < 0) start += slots;
|
|
983
|
+
|
|
984
|
+
// Clampa índices dentro dos limites da capacidade
|
|
985
|
+
target = Math.max(0, Math.min(target, slots));
|
|
986
|
+
start = Math.max(0, Math.min(start, slots));
|
|
987
|
+
|
|
988
|
+
// Limita a cópia à capacidade disponível a partir do target
|
|
989
|
+
// e aos elementos efetivamente ocupados a partir de start
|
|
990
|
+
const maxRead = Math.max(0, meta.occupied - start);
|
|
991
|
+
const maxWrite = slots - target;
|
|
992
|
+
length = Math.max(0, Math.min(length, maxRead, maxWrite));
|
|
993
|
+
|
|
994
|
+
if (length === 0) return this.dataBus;
|
|
995
|
+
|
|
996
|
+
const targetAddress = meta.dataAddress + target * this.wordSize;
|
|
997
|
+
const sourceAddress = meta.dataAddress + start * this.wordSize;
|
|
998
|
+
|
|
999
|
+
// Atualiza a ocupação caso a cópia expanda o topo ocupado do bloco
|
|
1000
|
+
const newOccupied = Math.max(meta.occupied, target + length);
|
|
1001
|
+
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, newOccupied, IS_LITTLE_ENDIAN);
|
|
1002
|
+
|
|
1003
|
+
return this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + length * this.wordSize);
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
/**
|
|
1007
|
+
* Acrescenta os elementos ocupados de `source` ao final de `target`.
|
|
1008
|
+
*
|
|
1009
|
+
* A quantidade copiada é limitada pelo número de elementos ocupados na
|
|
1010
|
+
* origem e pelo espaço livre restante na capacidade do destino.
|
|
1011
|
+
*
|
|
1012
|
+
* A operação suporta `target` e `source` referenciando o mesmo bloco.
|
|
1013
|
+
* Nesse caso, a cópia é realizada sobre a própria região do bloco e
|
|
1014
|
+
* preserva a semântica de sobreposição de `copyWithin()`.
|
|
1015
|
+
*
|
|
1016
|
+
* @param {number} target - Handler do bloco que receberá os elementos.
|
|
1017
|
+
* @param {number} source - Handler do bloco cujos elementos serão
|
|
1018
|
+
* acrescentados.
|
|
1019
|
+
* @returns {number} Número de elementos efetivamente acrescentados.
|
|
1020
|
+
* @throws {Error} Se `target` ou `source` for inválido ou estiver corrompido.
|
|
1021
|
+
*/
|
|
1022
|
+
append(target, source) {
|
|
1023
|
+
const metaTarget = {};
|
|
1024
|
+
const metaSource = {};
|
|
1025
|
+
|
|
1026
|
+
this.extractMetadata(target, metaTarget);
|
|
1027
|
+
this.extractMetadata(source, metaSource);
|
|
1028
|
+
|
|
1029
|
+
const available = metaTarget.byteCapacity / this.wordSize - metaTarget.occupied;
|
|
1030
|
+
const count = Math.min(available, metaSource.occupied);
|
|
1031
|
+
|
|
1032
|
+
if (count === 0) return 0;
|
|
1033
|
+
|
|
1034
|
+
const targetAddress = metaTarget.dataAddress + metaTarget.occupied * this.wordSize;
|
|
1035
|
+
const sourceAddress = metaSource.dataAddress;
|
|
1036
|
+
|
|
1037
|
+
if (target === source) {
|
|
1038
|
+
this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + count * this.wordSize);
|
|
1039
|
+
} else {
|
|
1040
|
+
this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + count * this.wordSize);
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
this.controlAdapter.setUint32(metaTarget.headerAddress + OCCUPIED_OFFSET, metaTarget.occupied + count, IS_LITTLE_ENDIAN);
|
|
1044
|
+
|
|
1045
|
+
return count;
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
/**
|
|
1049
|
+
* Cria uma cópia independente de um bloco.
|
|
1050
|
+
*
|
|
1051
|
+
* O novo bloco possui a mesma capacidade física e a mesma ocupação do
|
|
1052
|
+
* bloco original. Todos os bytes da região reservada, incluindo posições
|
|
1053
|
+
* atualmente não ocupadas, são copiados.
|
|
1054
|
+
*
|
|
1055
|
+
* O novo bloco recebe um novo handler e permanece sujeito às regras
|
|
1056
|
+
* normais de alocação e reciclagem.
|
|
1057
|
+
*
|
|
1058
|
+
* @param {number} handler - Handler do bloco a ser clonado.
|
|
1059
|
+
* @returns {number} Handler do novo bloco.
|
|
1060
|
+
* @throws {Error} Se o handler for inválido ou estiver corrompido.
|
|
1061
|
+
*/
|
|
1062
|
+
clone(handler) {
|
|
1063
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
1064
|
+
const cloned = this.alloc(meta.byteCapacity / this.wordSize);
|
|
1065
|
+
|
|
1066
|
+
const cloneMeta = {};
|
|
1067
|
+
this.extractMetadata(cloned, cloneMeta);
|
|
1068
|
+
|
|
1069
|
+
this.dataBus.copyWithin(cloneMeta.dataAddress, meta.dataAddress, meta.dataAddress + meta.byteCapacity);
|
|
1070
|
+
this.controlAdapter.setUint32(cloneMeta.headerAddress + OCCUPIED_OFFSET, meta.occupied, IS_LITTLE_ENDIAN);
|
|
1071
|
+
|
|
1072
|
+
return cloned;
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
/**
|
|
1076
|
+
* Troca as regiões de dados associadas a dois blocos.
|
|
1077
|
+
*
|
|
1078
|
+
* A operação troca entre os headers os endereços das regiões, suas
|
|
1079
|
+
* capacidades e suas ocupações. Os handlers permanecem inalterados:
|
|
1080
|
+
* depois da operação, cada handler continua identificando seu próprio
|
|
1081
|
+
* header, mas esse header passa a descrever a região que anteriormente
|
|
1082
|
+
* pertencia ao outro bloco.
|
|
1083
|
+
*
|
|
1084
|
+
* Nenhum dado é copiado no `dataBus`; somente os metadados dos dois
|
|
1085
|
+
* headers são modificados.
|
|
1086
|
+
*
|
|
1087
|
+
* @param {number} source - Handler do primeiro bloco.
|
|
1088
|
+
* @param {number} target - Handler do segundo bloco.
|
|
1089
|
+
* @returns {void}
|
|
1090
|
+
* @throws {Error} Se `source` ou `target` for inválido ou estiver corrompido.
|
|
1091
|
+
*/
|
|
1092
|
+
swap(source, target) {
|
|
1093
|
+
/** @type {Metadata} */
|
|
1094
|
+
const metaA = {};
|
|
1095
|
+
/** @type {Metadata} */
|
|
1096
|
+
const metaB = {};
|
|
1097
|
+
|
|
1098
|
+
this.extractMetadata(source, metaA);
|
|
1099
|
+
this.extractMetadata(target, metaB);
|
|
1100
|
+
|
|
1101
|
+
this.controlAdapter.setUint32(metaA.headerAddress + ADDRESS_OFFSET, metaB.dataAddress, IS_LITTLE_ENDIAN);
|
|
1102
|
+
this.controlAdapter.setUint32(metaB.headerAddress + ADDRESS_OFFSET, metaA.dataAddress, IS_LITTLE_ENDIAN);
|
|
1103
|
+
|
|
1104
|
+
this.controlAdapter.setUint8(metaA.headerAddress + CAPACITY_OFFSET, metaB.capacityExponent);
|
|
1105
|
+
this.controlAdapter.setUint8(metaB.headerAddress + CAPACITY_OFFSET, metaA.capacityExponent);
|
|
1106
|
+
|
|
1107
|
+
this.controlAdapter.setUint32(metaA.headerAddress + OCCUPIED_OFFSET, metaB.occupied, IS_LITTLE_ENDIAN);
|
|
1108
|
+
this.controlAdapter.setUint32(metaB.headerAddress + OCCUPIED_OFFSET, metaA.occupied, IS_LITTLE_ENDIAN);
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
|
|
1112
|
+
// ============= SERIALIZAÇÃO ==============
|
|
1113
|
+
|
|
1114
|
+
/**
|
|
1115
|
+
* Serializa o conteúdo e os metadados de um bloco de memória.
|
|
1116
|
+
*
|
|
1117
|
+
* O método extrai os dados ocupados do bloco por meio de `pick()`,
|
|
1118
|
+
* agrupa-os junto com informações de capacidade e tipo de palavra
|
|
1119
|
+
* em um envelope de dados e os codifica utilizando o formato CBOR.
|
|
1120
|
+
*
|
|
1121
|
+
* @param {number} handler - Handler do bloco a ser serializado.
|
|
1122
|
+
* @returns {Uint8Array} Um buffer contendo os dados serializados do bloco.
|
|
1123
|
+
* @throws {Error} Se o handler for inválido ou estiver corrompido.
|
|
1124
|
+
*/
|
|
1125
|
+
dump(handler) {
|
|
1126
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
1127
|
+
const capacity = meta.capacityExponent;
|
|
1128
|
+
const capacityElements = 2 ** capacity;
|
|
1129
|
+
|
|
1130
|
+
if (!Number.isInteger(capacity) || capacity < 1 || capacity > 31 || meta.occupied > capacityElements) {
|
|
1131
|
+
throw new Error("Cannot serialize a block with invalid metadata");
|
|
1132
|
+
}
|
|
1133
|
+
|
|
1134
|
+
const payload = this.pick(handler);
|
|
1135
|
+
|
|
1136
|
+
if (payload.length !== meta.occupied || payload.constructor !== this.bucketArray) {
|
|
1137
|
+
throw new Error("Cannot serialize a block with an invalid payload");
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
return encode({
|
|
1141
|
+
v: 1,
|
|
1142
|
+
wordType: this.wordType,
|
|
1143
|
+
capacity,
|
|
1144
|
+
occupied: meta.occupied,
|
|
1145
|
+
le: IS_LITTLE_ENDIAN,
|
|
1146
|
+
payload
|
|
1147
|
+
});
|
|
1148
|
+
}
|
|
1149
|
+
|
|
1150
|
+
/**
|
|
1151
|
+
* Restaura um bloco de memória a partir de dados serializados.
|
|
1152
|
+
*
|
|
1153
|
+
* Decodifica o envelope CBOR, valida se o tipo de palavra do dado
|
|
1154
|
+
* serializado é compatível com a instância atual do alocador e aloca
|
|
1155
|
+
* um novo bloco com a capacidade necessária para acomodar o conteúdo.
|
|
1156
|
+
* Em seguida, os dados e a ocupação original são restaurados no novo bloco.
|
|
1157
|
+
*
|
|
1158
|
+
* @param {Uint8Array|ArrayBuffer} serialized - Buffer contendo os dados serializados.
|
|
1159
|
+
* @returns {number} Handler do novo bloco recriado.
|
|
1160
|
+
* @throws {Error} Se o tipo de palavra do dado decodificado divergir do configurado no alocador.
|
|
1161
|
+
*/
|
|
1162
|
+
load(serialized) {
|
|
1163
|
+
if (!(serialized instanceof ArrayBuffer) && !(serialized instanceof Uint8Array)) {
|
|
1164
|
+
throw new TypeError("serialized must be an ArrayBuffer or Uint8Array");
|
|
1165
|
+
}
|
|
1166
|
+
|
|
1167
|
+
const envelope = decode(serialized);
|
|
1168
|
+
|
|
1169
|
+
if (!envelope || typeof envelope !== "object" || Array.isArray(envelope)) {
|
|
1170
|
+
throw new TypeError("Invalid serialized block envelope");
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
if (envelope.v !== 1) {
|
|
1174
|
+
throw new Error(`Unsupported serialized block version: ${envelope.v}`);
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
if (envelope.wordType !== this.wordType) {
|
|
1178
|
+
throw new Error(`Can't load data, ${this.wordType} expected but ${envelope.wordType} found.`);
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
if (!Number.isInteger(envelope.capacity) || envelope.capacity < 1 || envelope.capacity > 31) {
|
|
1182
|
+
throw new RangeError("Invalid serialized block capacity");
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
const capacityElements = 2 ** envelope.capacity;
|
|
1186
|
+
|
|
1187
|
+
if (!Number.isSafeInteger(envelope.occupied) || envelope.occupied < 0 || envelope.occupied > capacityElements) {
|
|
1188
|
+
throw new RangeError("Invalid serialized block occupancy");
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
if (typeof envelope.le !== "boolean") {
|
|
1192
|
+
throw new TypeError("Invalid serialized endianness flag");
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1195
|
+
const payload = envelope.payload;
|
|
1196
|
+
|
|
1197
|
+
if (!isTypedArray(payload) || payload.constructor !== this.bucketArray || payload.length !== envelope.occupied) {
|
|
1198
|
+
throw new TypeError(`Invalid payload: expected ${this.bucketType}Array with ${envelope.occupied} elements`);
|
|
1199
|
+
}
|
|
1200
|
+
|
|
1201
|
+
if (payload.BYTES_PER_ELEMENT !== this.wordSize || payload.byteLength !== envelope.occupied * this.wordSize) {
|
|
1202
|
+
throw new TypeError("Serialized payload has an invalid element size");
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
const handler = this.alloc(capacityElements);
|
|
1206
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
1207
|
+
this.put(handler, payload);
|
|
1208
|
+
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, envelope.occupied, IS_LITTLE_ENDIAN);
|
|
1209
|
+
|
|
1210
|
+
return handler;
|
|
1211
|
+
}
|
|
1212
|
+
|
|
1213
|
+
// ============= UTILITÁRIOS ==============
|
|
1214
|
+
|
|
1215
|
+
/**
|
|
1216
|
+
* [USO INTERNO]
|
|
1217
|
+
* Decodifica os metadados associados a um handler.
|
|
1218
|
+
*
|
|
1219
|
+
* O handler é dividido em geração e endereço do header. O cookie armazenado
|
|
1220
|
+
* no header é então recalculado para validar a combinação; somente após
|
|
1221
|
+
* essa validação os metadados são lidos.
|
|
1222
|
+
*
|
|
1223
|
+
* Os campos decodificados são escritos no objeto `out`, que é retornado
|
|
1224
|
+
* pela própria função. O objeto pode ser reutilizado entre chamadas para
|
|
1225
|
+
* evitar novas alocações.
|
|
1226
|
+
*
|
|
1227
|
+
* @param {number} handler - Handler a ser decodificado e validado.
|
|
1228
|
+
* @param {Metadata} out - Objeto que receberá os metadados decodificados.
|
|
1229
|
+
* @returns {Metadata} A mesma referência fornecida em `out`.
|
|
1230
|
+
* @throws {Error} Se o cookie do header não corresponder ao handler ou
|
|
1231
|
+
* se o handler não identificar um header válido.
|
|
1232
|
+
* @private
|
|
1233
|
+
*/
|
|
1234
|
+
extractMetadata(handler, out) {
|
|
1235
|
+
out.generation = (handler / ROTATE_32BITS) & CLAMP_11BITS;
|
|
1236
|
+
out.headerAddress = handler >>> 0;
|
|
1237
|
+
|
|
1238
|
+
const cookie = this.controlAdapter.getUint8(out.headerAddress + COOKIE_OFFSET);
|
|
1239
|
+
|
|
1240
|
+
|
|
1241
|
+
if (cookie !== this.bakeCookie(out.headerAddress, out.generation)) {
|
|
1242
|
+
throw new Error("Invalid or corrupted handle");
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1245
|
+
out.dataAddress = this.controlAdapter.getUint32(out.headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
|
|
1246
|
+
out.capacityExponent = this.controlAdapter.getUint8(out.headerAddress + CAPACITY_OFFSET);
|
|
1247
|
+
out.byteCapacity = (1 << out.capacityExponent >>> 0) * this.wordSize;
|
|
1248
|
+
out.occupied = this.controlAdapter.getUint32(out.headerAddress + OCCUPIED_OFFSET, IS_LITTLE_ENDIAN);
|
|
1249
|
+
|
|
1250
|
+
return out;
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1253
|
+
/**
|
|
1254
|
+
* [USO INTERNO]
|
|
1255
|
+
* Calcula o cookie de validação de um header.
|
|
1256
|
+
*
|
|
1257
|
+
* O cookie é derivado do endereço do header e dos 11 bits da geração por
|
|
1258
|
+
* meio de fast hash.
|
|
1259
|
+
* O resultado é reduzido para 8 bits.
|
|
1260
|
+
*
|
|
1261
|
+
* O valor zero é reservado como indicador de header inválido; por isso,
|
|
1262
|
+
* quando o cálculo produz zero, o método retorna `1`.
|
|
1263
|
+
*
|
|
1264
|
+
* O cookie não constitui um mecanismo criptográfico. Sua finalidade é
|
|
1265
|
+
* detectar handlers inválidos, stale ou corrompidos dentro do modelo de
|
|
1266
|
+
* gerenciamento de memória do alocador.
|
|
1267
|
+
*
|
|
1268
|
+
* @param {number} addr - Endereço do header.
|
|
1269
|
+
* @param {number} gen - Geração associada ao handler. Somente os 11 bits
|
|
1270
|
+
* menos significativos são considerados.
|
|
1271
|
+
* @returns {number} Cookie de 8 bits no intervalo [1, 255].
|
|
1272
|
+
* @private
|
|
1273
|
+
*/
|
|
1274
|
+
bakeCookie(addr, gen) {
|
|
1275
|
+
return (addr ^ (gen & 0x7FF * 0x9e3779b1)) & 0xff || 1;
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
/**
|
|
1279
|
+
* Retorna a quantidade de regiões atualmente armazenadas na lista de
|
|
1280
|
+
* reciclagem.
|
|
1281
|
+
*
|
|
1282
|
+
* Cada região corresponde a um bloco liberado que não pôde ser devolvido
|
|
1283
|
+
* diretamente ao topo do `dataBus` e, portanto, permanece disponível para
|
|
1284
|
+
* reutilização por uma alocação futura de capacidade idêntica.
|
|
1285
|
+
*
|
|
1286
|
+
* @returns {number} Número de regiões livres mantidas em `recycle`.
|
|
1287
|
+
*/
|
|
1288
|
+
recycleCount() {
|
|
1289
|
+
let count = 0;
|
|
1290
|
+
|
|
1291
|
+
for (const [, page] of this.recycle) {
|
|
1292
|
+
count += page[0];
|
|
1293
|
+
}
|
|
1294
|
+
|
|
1295
|
+
return count;
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
/**
|
|
1299
|
+
* Retorna o total de bytes pertencentes às regiões atualmente armazenadas
|
|
1300
|
+
* na lista de reciclagem.
|
|
1301
|
+
*
|
|
1302
|
+
* O valor é calculado somando a capacidade de cada região livre multiplicada
|
|
1303
|
+
* pela quantidade de regiões registradas para aquela capacidade.
|
|
1304
|
+
*
|
|
1305
|
+
* @returns {number} Número de bytes ocupados por regiões recicláveis.
|
|
1306
|
+
*/
|
|
1307
|
+
get recycleBytes() {
|
|
1308
|
+
let total = 0;
|
|
1309
|
+
|
|
1310
|
+
for (const [capacity, page] of this.recycle) {
|
|
1311
|
+
total += page[0] * capacity;
|
|
1312
|
+
}
|
|
1313
|
+
|
|
1314
|
+
return total;
|
|
1315
|
+
}
|
|
1316
|
+
|
|
1317
|
+
/**
|
|
1318
|
+
* Retorna a quantidade de bytes alocados que não pertencem às regiões
|
|
1319
|
+
* atualmente recicláveis.
|
|
1320
|
+
*
|
|
1321
|
+
* O valor é obtido subtraindo do avanço total do `dataPointer` os bytes
|
|
1322
|
+
* pertencentes às regiões livres mantidas em `recycle`.
|
|
1323
|
+
*
|
|
1324
|
+
* @returns {number} Número de bytes associados às regiões não recicláveis
|
|
1325
|
+
* dentro da área já utilizada pelo `dataBus`.
|
|
1326
|
+
*/
|
|
1327
|
+
get allocatedBytes() {
|
|
1328
|
+
return this.dataPointer - this.recycleBytes;
|
|
1329
|
+
}
|
|
1330
|
+
|
|
1331
|
+
/**
|
|
1332
|
+
* Retorna a quantidade de bytes ainda não utilizada no topo do `dataBus`.
|
|
1333
|
+
*
|
|
1334
|
+
* Esse espaço corresponde à região entre `dataPointer` e o final da
|
|
1335
|
+
* capacidade atualmente reservada para o buffer.
|
|
1336
|
+
*
|
|
1337
|
+
* @returns {number} Número de bytes disponíveis após `dataPointer`.
|
|
1338
|
+
*/
|
|
1339
|
+
get unallocatedBytes() {
|
|
1340
|
+
return this.size - this.dataPointer;
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
/**
|
|
1344
|
+
* Retorna a razão entre a memória reciclável e a área de heap utilizada.
|
|
1345
|
+
*
|
|
1346
|
+
* A métrica considera como fragmentação as regiões livres mantidas em
|
|
1347
|
+
* `recycle` e utiliza `dataPointer` como denominador. Quando nenhum byte
|
|
1348
|
+
* foi utilizado pelo heap, o resultado é zero.
|
|
1349
|
+
*
|
|
1350
|
+
* O valor não representa a fração de toda a capacidade do `dataBus`, mas
|
|
1351
|
+
* especificamente a proporção de bytes recicláveis dentro da área já
|
|
1352
|
+
* percorrida pelo bump pointer.
|
|
1353
|
+
*
|
|
1354
|
+
* @returns {number} Razão de fragmentação no intervalo [0, 1] em condições
|
|
1355
|
+
* normais de operação.
|
|
1356
|
+
*/
|
|
1357
|
+
get fragmentationRatio() {
|
|
1358
|
+
if (this.dataPointer === 0) return 0;
|
|
1359
|
+
return this.recycleBytes / this.dataPointer;
|
|
1360
|
+
}
|
|
1361
|
+
|
|
1362
|
+
}
|