@structs-arena/skip-list 0.0.0-stage → 1.0.0

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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +38 -3
  3. package/package.json +40 -6
  4. package/src/index.js +589 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Augusto Vasques
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,38 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # @structs-arena/skip-list
2
+
3
+ A probabilistic skip list for unsigned integer keys. Node records are stored in a Balloc-managed contiguous arena; associated values are stored separately.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @structs-arena/skip-list
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```js
14
+ import { SkipList } from "@structs-arena/skip-list";
15
+
16
+ const list = new SkipList();
17
+ list.insert(10, "ten");
18
+ list.insert(20, "twenty");
19
+
20
+ console.log(list.get(10)); // "ten"
21
+ console.log(list.has(20)); // true
22
+
23
+ list.delete(10);
24
+ console.log(list.has(10)); // false
25
+ ```
26
+
27
+ ## API overview
28
+
29
+ - `new SkipList(probability?, seed?, size?)`: create a skip list.
30
+ - `insert(key, value)`, `get(key)`, `has(key)`, `delete(key)`: update and query entries.
31
+ - `clear()`, `purge()`: clear entries or reclaim unused structure.
32
+ - `entries()`, `keys()`, `values()`: iterate in key order.
33
+ - `count`, `height`, `probability`: inspect structure state.
34
+ - `dump()`, `SkipList.load(data)`: serialize and restore the structure.
35
+
36
+ ## License
37
+
38
+ MIT
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
- {
2
- "name": "@structs-arena/skip-list",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@structs-arena/skip-list",
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "main": "./src/index.js",
6
+ "exports": {
7
+ ".": "./src/index.js"
8
+ },
9
+ "files": [
10
+ "src",
11
+ "LICENSE"
12
+ ],
13
+ "license": "MIT",
14
+ "description": "Probabilistic skip list for unsigned integer keys.",
15
+ "keywords": [
16
+ "skip-list",
17
+ "data-structures",
18
+ "javascript",
19
+ "balloc"
20
+ ],
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "https://github.com/AugustoVasques75/structs-arena.git",
24
+ "directory": "packages/skip-list"
25
+ },
26
+ "bugs": {
27
+ "url": "https://github.com/AugustoVasques75/structs-arena/issues"
28
+ },
29
+ "scripts": {
30
+ "test": "vitest run",
31
+ "test:watch": "vitest"
32
+ },
33
+ "dependencies": {
34
+ "balloc": "^2.0.1",
35
+ "cbor-x": "^1.6.8"
36
+ },
37
+ "engines": {
38
+ "node": ">=20"
39
+ }
40
+ }
package/src/index.js ADDED
@@ -0,0 +1,589 @@
1
+ import Balloc from "balloc";
2
+ import { encode, decode } from "cbor-x";
3
+
4
+
5
+ const UNKNOWN = 0xFFFFFFFF >>> 0;
6
+ const IS_HEAD = 0xFFFFFFFE >>> 0;
7
+
8
+
9
+ /**
10
+ * An indexed skip list backed by a contiguous Balloc-managed arena.
11
+ */
12
+ const KEY = 0 >>> 0;
13
+ const NEXT = 1 >>> 0;
14
+ const BOTTOM = 2 >>> 0;
15
+ const LANE = 3 >>> 0;
16
+
17
+ /**
18
+ * An indexed skip list backed by a contiguous Balloc-managed arena.
19
+ */
20
+ const STRIDE = 4;
21
+
22
+ /**
23
+ * An indexed skip list backed by a contiguous Balloc-managed arena.
24
+ */
25
+ const HEAD = 0;
26
+
27
+ /**
28
+ * An indexed skip list backed by a contiguous Balloc-managed arena.
29
+
30
+ * @private
31
+ */
32
+ class Xorshift32 {
33
+ state;
34
+
35
+ /**
36
+ * Creates a new list or restores a serialized instance.
37
+
38
+ * @param {number}
39
+ */
40
+ constructor(seed = 0x9E3779B9) {
41
+ this.state = seed >>> 0 || 1;
42
+ }
43
+
44
+ /**
45
+ * Moves the active cursor to the next node.
46
+
47
+ * @returns {number}
48
+ */
49
+ next() {
50
+ let x = this.state;
51
+ x ^= x << 13;
52
+ x ^= x >>> 17;
53
+ x ^= x << 5;
54
+ return this.state = x >>> 0;
55
+ }
56
+ }
57
+
58
+ /**
59
+ * An indexed skip list backed by a contiguous Balloc-managed arena.
60
+
61
+ * @example
62
+ */
63
+ export class SkipList {
64
+ #memory;
65
+ #arena;
66
+ #recycle;
67
+ #values;
68
+
69
+ #random;
70
+ #probability;
71
+ #threshold;
72
+
73
+ #count = 0; // Number of occupied slots in the arena.
74
+ #lane0 = 0; // HEAD offset for level 0.
75
+ #size = 0;
76
+
77
+ static #token = Symbol("SkipList");
78
+
79
+ /**
80
+ * Creates a new list or restores a serialized instance.
81
+
82
+ * @param {number}
83
+ * @param {number}
84
+ * @param {number}
85
+ * @throws {RangeError}
86
+ * @throws {SkipListDeserializationError}
87
+ */
88
+ constructor(probability = 0.25, seed = 0x9E3779B9, size = 1024) {
89
+ if (probability === SkipList.#token) {
90
+ try {
91
+ const pack = decode(seed);
92
+ if (pack.format !== "SkipList") throw new TypeError(`Unable to read the structure. Expected SkipList, received v${pack.format ?? "null"}.`);
93
+ if (pack.version !== 2) throw new RangeError(`Invalid dump version. Expected v2, received v${pack.version ?? "null"}.`);
94
+ this.#size = pack.size;
95
+ this.#memory = new Balloc(0x80000000, "32u");
96
+ this.#probability = pack.probability;
97
+ this.#threshold = this.#probability * 0x100000000;
98
+ this.#random = new Xorshift32(0x9E3779B9);
99
+ this.#random.state = pack.state;
100
+ this.#arena = this.#memory.load(pack.data.arena);
101
+ this.#recycle = this.#memory.load(pack.data.recycle);
102
+ this.#values = pack.data.values;
103
+ this.#count = pack.count;
104
+ this.#lane0 = pack.lane0;
105
+ } catch (e) {
106
+ throw new SkipListDeserializationError("Unable to deserialize the data package. See cause for details.", { cause: e });
107
+ }
108
+ } else {
109
+
110
+ if (!Number.isFinite(probability) || probability < 0 || probability > 1) {
111
+ throw new RangeError("Invalid key");
112
+ }
113
+
114
+ this.#size = size;
115
+ this.#memory = new Balloc(0x80000000, "32u");
116
+ this.#probability = probability;
117
+ this.#threshold = probability * 0x100000000;
118
+ this.#random = new Xorshift32(seed);
119
+
120
+ this.#arena = this.#memory.alloc(size * 4);
121
+ this.#memory.fillAll(this.#arena, 0);
122
+
123
+ this.#recycle = this.#memory.alloc();
124
+
125
+ this.#memory.withView(this.#arena, view => {
126
+ view.set([
127
+ IS_HEAD, //KEY
128
+ UNKNOWN, //NEXT
129
+ UNKNOWN, //BOTTOM
130
+ 0 //LANE
131
+ ], HEAD); // HEAD of the highest level (level 0).
132
+ });
133
+ this.#count = 1; //1 slot ocupado pelo head
134
+ this.#values = Object.create(null);
135
+ }
136
+ }
137
+
138
+ /**
139
+ * An indexed skip list backed by a contiguous Balloc-managed arena.
140
+
141
+ * @returns {number}
142
+ */
143
+ get count() {
144
+ return this.#count - this.#memory.occupied(this.#recycle);
145
+ }
146
+
147
+ /**
148
+ * An indexed skip list backed by a contiguous Balloc-managed arena.
149
+
150
+ * @returns {number}
151
+ */
152
+ get height() {
153
+ return this.#memory.get(this.#arena, HEAD + LANE) + 1;
154
+ }
155
+
156
+ /**
157
+ * An indexed skip list backed by a contiguous Balloc-managed arena.
158
+
159
+ * @returns {number}
160
+ */
161
+ get probability() {
162
+ return this.#probability;
163
+ }
164
+
165
+ /**
166
+ * An indexed skip list backed by a contiguous Balloc-managed arena.
167
+
168
+ * @private
169
+ * @returns {number}
170
+ */
171
+ #randomHeight() {
172
+ let height = 1;
173
+ while (height <= this.height && this.#random.next() < this.#threshold) height++;
174
+ return height;
175
+ }
176
+
177
+ /**
178
+ * An indexed skip list backed by a contiguous Balloc-managed arena.
179
+
180
+ * @private
181
+ * @param {number}
182
+ * @throws {Error}
183
+ */
184
+ #recyclePush(offset) {
185
+ if (this.#memory.push(this.#recycle, offset)) return;
186
+
187
+ this.#memory.realloc(this.#recycle);
188
+
189
+ if (!this.#memory.push(this.#recycle, offset)) {
190
+ throw new Error("Recycle buffer insertion failed after realloc");
191
+ }
192
+ }
193
+
194
+ /**
195
+ * Serializes the list state into a CBOR-encoded binary buffer.
196
+
197
+ * @returns {Uint8Array}
198
+ */
199
+ dump() {
200
+ return encode({
201
+ format: "SkipList",
202
+ version: 2,
203
+ size: this.#size,
204
+ count: this.#count,
205
+ probability: this.#probability,
206
+ state: this.#random.state,
207
+ lane0: this.#lane0,
208
+ data: {
209
+ arena: this.#memory.dump(this.#arena),
210
+ recycle: this.#memory.dump(this.#recycle),
211
+ values: this.#values,
212
+ }
213
+ });
214
+ }
215
+
216
+ /**
217
+ * Restores a list from a CBOR-encoded binary buffer.
218
+
219
+ * @param {Buffer | Uint8Array}
220
+ * @returns {SkipList}
221
+ * @throws {SkipListDeserializationError}
222
+ */
223
+ static load(data) {
224
+ return new SkipList(SkipList.#token, data);
225
+ }
226
+
227
+ /**
228
+ * Inserts a value into the list.
229
+
230
+ * @param {number}
231
+ * @param {*}
232
+ * @throws {RangeError}
233
+ * @throws {Error}
234
+ * @returns {void}
235
+ */
236
+ insert(key, value) {
237
+ if (!Number.isInteger(key) || key < 0 || key >= IS_HEAD) {
238
+ throw new RangeError("Invalid key");
239
+ }
240
+
241
+ const nodeheight = this.#randomHeight();
242
+ const height = this.height;
243
+ const headGrowth = Math.max(0, nodeheight - height);
244
+ const growth = (headGrowth + nodeheight) * STRIDE;
245
+ const required = this.#count * STRIDE + growth;
246
+ const capacity = this.#memory.length(this.#arena);
247
+
248
+ if (required > capacity) {
249
+ this.#memory.realloc(this.#arena);
250
+ this.#memory.fill(this.#arena, 0, capacity);
251
+ }
252
+
253
+ this.#memory.withView(this.#arena, view => {
254
+ let cursor = HEAD;
255
+ let next = UNKNOWN;
256
+ let bottom = UNKNOWN;
257
+ let lane = UNKNOWN;
258
+ let offset = UNKNOWN;
259
+ let upper = UNKNOWN;
260
+
261
+ while (nodeheight > this.height) {
262
+ next = view[cursor + NEXT];
263
+ bottom = view[cursor + BOTTOM];
264
+ lane = view[cursor + LANE];
265
+ offset = STRIDE * this.#count;
266
+
267
+ if (this.#memory.occupied(this.#recycle) > 0) {
268
+ offset = this.#memory.pop(this.#recycle);
269
+ } else {
270
+ this.#count++;
271
+ }
272
+
273
+ view.copyWithin(offset, HEAD, HEAD + STRIDE);
274
+ view.set([IS_HEAD, UNKNOWN, offset, lane + 1], 0);
275
+
276
+ if (lane === 0) this.#lane0 = offset;
277
+ }
278
+
279
+ while (true) {
280
+ next = view[cursor + NEXT];
281
+ bottom = view[cursor + BOTTOM];
282
+ lane = view[cursor + LANE];
283
+ offset = STRIDE * this.#count;
284
+
285
+ if (next !== UNKNOWN && view[next + KEY] < key) {
286
+ cursor = next;
287
+ continue;
288
+ }
289
+
290
+ if (nodeheight <= lane) {
291
+ cursor = bottom;
292
+ continue;
293
+ }
294
+
295
+ if (next !== UNKNOWN && view[next + KEY] === key) break;
296
+
297
+ if (this.#memory.occupied(this.#recycle) > 0) {
298
+ offset = this.#memory.pop(this.#recycle);
299
+ } else {
300
+ this.#count++;
301
+ }
302
+
303
+ if (offset + STRIDE > view.length) {
304
+ throw new Error(`Offset out of bounds: key=${key}, offset=${offset}, viewLength=${view.length}, count=${this.#count}`);
305
+ }
306
+
307
+ view[offset + KEY] = key;
308
+ view[offset + NEXT] = view[cursor + NEXT];
309
+ view[cursor + NEXT] = offset;
310
+ view[offset + BOTTOM] = UNKNOWN;
311
+ view[offset + LANE] = lane;
312
+
313
+ if (upper !== UNKNOWN) {
314
+ const upperKey = view[upper + KEY];
315
+
316
+ if (upper + STRIDE > view.length || upperKey !== key) {
317
+ throw new Error(`Invalid upper: key=${key}, upper=${upper}, upperKey=${upperKey}, lane=${lane}, viewLength=${view.length}, count=${this.#count}`);
318
+ }
319
+
320
+ view[upper + BOTTOM] = offset;
321
+ }
322
+
323
+ upper = offset;
324
+
325
+ if (lane === 0) break;
326
+
327
+ cursor = bottom;
328
+ }
329
+ });
330
+
331
+ this.#values[key] = value;
332
+ }
333
+
334
+ /**
335
+ * An indexed skip list backed by a contiguous Balloc-managed arena.
336
+
337
+ * @returns {void}
338
+ * @throws {Error}
339
+ */
340
+ purge() {
341
+ if (this.#memory.get(this.#arena, HEAD + NEXT) !== UNKNOWN) return;
342
+ if (this.#memory.get(this.#arena, HEAD + LANE) === 0) return;
343
+
344
+ this.#memory.withView(this.#arena, view => {
345
+ let next = UNKNOWN;
346
+ let bottom = UNKNOWN;
347
+ let lane = UNKNOWN;
348
+ let offset = UNKNOWN;
349
+
350
+ while (true) {
351
+ next = view[HEAD + NEXT];
352
+ bottom = view[HEAD + BOTTOM];
353
+ lane = view[HEAD + LANE];
354
+
355
+ if (next !== UNKNOWN || lane === 0) return;
356
+ if (bottom === UNKNOWN) throw new Error("Invalid HEAD chain");
357
+
358
+ offset = STRIDE * (this.#count - 1);
359
+
360
+ if (bottom === offset) {
361
+ this.#count--;
362
+ } else {
363
+ this.#recyclePush(bottom);
364
+ }
365
+
366
+ view.copyWithin(HEAD, bottom, bottom + STRIDE);
367
+
368
+ if (lane === 1) this.#lane0 = HEAD;
369
+ }
370
+ });
371
+ }
372
+
373
+ /**
374
+ * Removes the node selected by the active cursor.
375
+
376
+ * @param {number}
377
+ * @throws {RangeError}
378
+ * @returns {void}
379
+ */
380
+ delete(key) {
381
+ if (!Number.isInteger(key) || key < 0 || key >= IS_HEAD) {
382
+ throw new RangeError("Invalid key");
383
+ }
384
+
385
+ this.#memory.withView(this.#arena, view => {
386
+ let cursor = HEAD;
387
+ let k = UNKNOWN;
388
+ let next = UNKNOWN;
389
+ let bottom = UNKNOWN;
390
+ let offset = UNKNOWN; // Offset of the last node in the arena.
391
+ while (true) {
392
+ k = view[cursor + KEY];
393
+ next = view[cursor + NEXT];
394
+ bottom = view[cursor + BOTTOM];
395
+ offset = STRIDE * (this.#count - 1);
396
+
397
+ if (offset === HEAD) break;
398
+ if (cursor === UNKNOWN) break;
399
+ if (next === UNKNOWN || view[next + KEY] > key) {
400
+ cursor = bottom;
401
+ continue;
402
+ }
403
+ if (view[next + KEY] === key) {
404
+ view[cursor + NEXT] = view[next + NEXT];
405
+
406
+ if (offset === next) {
407
+ this.#count--;
408
+ } else {
409
+ this.#recyclePush(next);
410
+ }
411
+
412
+ cursor = bottom;
413
+ continue;
414
+ }
415
+ cursor = next;
416
+ }
417
+
418
+ });
419
+ delete this.#values[key];
420
+ this.purge();
421
+ if (this.count === 1) {
422
+ this.#count = 1;
423
+ this.#memory.free(this.#recycle);
424
+ this.#recycle = this.#memory.alloc();
425
+ }
426
+ }
427
+
428
+ /**
429
+ * Returns the value associated with the specified key.
430
+
431
+ * @param {number}
432
+ * @throws {RangeError}
433
+ * @returns {*}
434
+ */
435
+ get(key) {
436
+ if (!Number.isInteger(key) || key < 0 || key >= IS_HEAD) {
437
+ throw new RangeError("Invalid key");
438
+ }
439
+
440
+ return this.#memory.withView(this.#arena, view => {
441
+ let cursor = HEAD;
442
+ let k = UNKNOWN;
443
+ let next = UNKNOWN;
444
+ let bottom = UNKNOWN;
445
+ while (true) {
446
+ k = view[cursor + KEY];
447
+ next = view[cursor + NEXT];
448
+ bottom = view[cursor + BOTTOM];
449
+
450
+ if (k === key) return this.#values[key];
451
+ if (cursor === UNKNOWN) return undefined;
452
+
453
+ if (k === IS_HEAD) {
454
+ cursor = next === UNKNOWN ? bottom : next;
455
+ continue;
456
+ }
457
+ if (next === UNKNOWN || view[next + KEY] > key) {
458
+ cursor = bottom;
459
+ continue;
460
+ }
461
+ cursor = next;
462
+ }
463
+ });
464
+ }
465
+
466
+ /**
467
+ * Checks whether the specified key exists.
468
+
469
+ * @param {number}
470
+ * @throws {RangeError}
471
+ * @returns {boolean}
472
+ */
473
+ has(key) {
474
+ if (!Number.isInteger(key) || key < 0 || key >= IS_HEAD) {
475
+ throw new RangeError("Invalid key");
476
+ }
477
+
478
+ return this.#memory.withView(this.#arena, view => {
479
+ let cursor = HEAD;
480
+ let k = UNKNOWN;
481
+ let next = UNKNOWN;
482
+ let bottom = UNKNOWN;
483
+ while (true) {
484
+ k = view[cursor + KEY];
485
+ next = view[cursor + NEXT];
486
+ bottom = view[cursor + BOTTOM];
487
+
488
+ if (k === key) return true;
489
+ if (cursor === UNKNOWN) return false;
490
+
491
+ if (k === IS_HEAD) {
492
+ cursor = next === UNKNOWN ? bottom : next;
493
+ continue;
494
+ }
495
+ if (next === UNKNOWN || view[next + KEY] > key) {
496
+ cursor = bottom;
497
+ continue;
498
+ }
499
+ cursor = next;
500
+ }
501
+ });
502
+ }
503
+
504
+ /**
505
+ * Removes all nodes and reinitializes the list's internal storage.
506
+
507
+ * @returns {void}
508
+ */
509
+ clear() {
510
+ this.#memory.free(this.#arena);
511
+ this.#memory.free(this.#recycle);
512
+ this.#arena = this.#memory.alloc(this.#size * 4);
513
+ this.#memory.fillAll(this.#arena, 0);
514
+ this.#recycle = this.#memory.alloc();
515
+
516
+ this.#memory.withView(this.#arena, view => {
517
+ view.set([
518
+ IS_HEAD, //KEY
519
+ UNKNOWN, //NEXT
520
+ UNKNOWN, //BOTTOM
521
+ 0 //HEIGHT
522
+ ], HEAD); // HEAD of the highest level (level 0).
523
+ });
524
+ this.#count = 1; //1 slot ocupado pelo head
525
+ this.#lane0 = 0; // HEAD offset for level 0.
526
+ this.#values = Object.create(null);
527
+ }
528
+
529
+ /**
530
+ * An indexed skip list backed by a contiguous Balloc-managed arena.
531
+
532
+ * @yields {[number, *]}
533
+ */
534
+ *entries() {
535
+ let cursor = this.#lane0;
536
+ let k = UNKNOWN;
537
+
538
+ while (true) {
539
+ cursor = this.#memory.get(this.#arena, cursor + NEXT);
540
+ if (cursor === UNKNOWN) break;
541
+ k = this.#memory.get(this.#arena, cursor + KEY);
542
+ yield [k, this.#values[k]];
543
+
544
+ }
545
+ }
546
+
547
+ /**
548
+ * An indexed skip list backed by a contiguous Balloc-managed arena.
549
+
550
+ * @yields {number}
551
+ */
552
+ *keys() {
553
+ for (const [key] of this.entries()) yield key;
554
+ }
555
+
556
+ /**
557
+ * An indexed skip list backed by a contiguous Balloc-managed arena.
558
+
559
+ * @yields {*}
560
+ */
561
+ *values() {
562
+ for (const [, value] of this.entries()) yield value;
563
+ }
564
+
565
+ /**
566
+ * An indexed skip list backed by a contiguous Balloc-managed arena.
567
+
568
+ * @returns {Iterator<[number, *]>}
569
+ */
570
+ [Symbol.iterator]() {
571
+ return this.entries();
572
+ }
573
+
574
+ }
575
+
576
+ /**
577
+ * An indexed skip list backed by a contiguous Balloc-managed arena.
578
+ */
579
+ export class SkipListDeserializationError extends Error {
580
+ /**
581
+ * Creates a new list or restores a serialized instance.
582
+
583
+ * @param {string}
584
+ * @param {ErrorOptions}
585
+ */
586
+ constructor(message, options) {
587
+ super(message, options);
588
+ }
589
+ }