-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.js
2014 lines (1593 loc) · 46.2 KB
/
common.js
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -------------------------------------------------------------------------- */
'use strict';
/* -------------------------------------------------------------------------- */
export const dbg = true;
const qualifierOp = {get : (t, name) => (
typeof name === `string`
? qualifier(`${t.ns}-${name}`)
: (_ => `${t.ns}`))};
function qualifier(ns) {
return new Proxy({ns}, qualifierOp);};
export const namespace = `galk`;
export const galk = qualifier(namespace);
export function isIterable(xs) {
return xs != null && typeof xs[Symbol.iterator] === `function`;
};
export function isAsyncIterable(xs) {
return xs != null && typeof xs[Symbol.asyncIterator] === `function`;
};
function isValidLength(len) {
return Number.isSafeInteger(len) && len >= 0;
};
function lengthOf(xs) {
let len = Object(xs).length;
return isValidLength(len) ? len : -1;
};
function hasLength(xs) {
return lengthOf(xs) >= 0;
};
export function isInt32(x) {
return typeof x === `number` && (x|0) === x;
};
export function int32Popcnt(i) {
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
};
export function tryParseUint31(s) {
/* parse a string representing a 31-bit int of the form ^(0|[1-9][0-9]*)$
returns the integer, or any negative integer if the string was malformed */
dbg && assert.str(s);
let len = s.length;
let lenNibble = len & 0b1111; /* prevent excessive iteration */
let c0 = s.charCodeAt(0) - 48;
let invalid =
(lenNibble === 0)
| (len > 10)
| ((c0 >>> 1) > 4) /* c0 < 0 || c0 > 9 */
| ((c0 << 3) < (lenNibble >>> 1)) /* c0 === 0 && lenNibble !== 1 */
| (lenNibble === 10 && s > `2147483647`);
let n = c0;
for (let i = 1; i < lenNibble; ++i) {
let c = s.charCodeAt(i) - 48;
n = Math.imul(10, n) + c;
invalid |= ((c >>> 1) > 4); /* c < 0 || c > 9 */
};
return n | -invalid;
};
export const queueMicrotask =
(typeof self.queueMicrotask === `function`)
? self.queueMicrotask.bind(null)
: (p => function queueMicrotask(callback) {
return p.then(callback);
})(Promise.resolve());
export function tryParseHref(href) {
try {
return new URL(href);
} catch (x) {
return null;};
};
export function isSafeUrl(url) {
/* http(s) only, no credentials */
if (url instanceof URL) {
let p = url.protocol;
return (p === `http:` || p === `https:`)
&& url.host !== ``
&& url.username === `` && url.password === ``;
};
return false;
};
/* attempt to detect decimal point and group separator characters
from current locale: */
const numFormat = (nf => {
let sep = `,`;
{
let s = nf.format(0x7fffffff);
let i = s.search(/[^0-9]/u);
if (i >= 0) {
sep = String.fromCodePoint(s.codePointAt(i));};
};
let pt = `.`;
{
let s = nf.format(0.1);
let i = s.search(/[^0-9]/u);
if (i >= 0) {
pt = String.fromCodePoint(s.codePointAt(i));};
};
return {sep, pt};
})(new Intl.NumberFormat(undefined, {numberingSystem : `latn`}));
export const numGroupSeparator = numFormat.sep;
export const numDecimalPoint = numFormat.pt;
export function ensureSubMap(m, k) {
dbg && assert(m instanceof Map);
let sub = m.get(k);
if (sub === undefined) {
sub = new Map;
m.set(k, sub);
};
dbg && assert(sub instanceof Map);
return sub;
};
export function getFromSubMap(m, k1, k2) {
dbg && assert(m instanceof Map);
let sub = m.get(k1);
if (sub !== undefined) {
dbg && assert(sub instanceof Map);
return sub.get(k2);
};
return undefined;
};
/* --- assertion --- */
let onAssertionFailure = () => {};
export function assignOnAssertionFailure(f) {onAssertionFailure = f;};
export function assert(value, message) {
if (!value) {
if (message == null) {
message = `value was falsey`;
} else if (message instanceof Error) {
throw message;};
debugger;
onAssertionFailure();
throw new Error(message);
};
return value;
};
function assertInternal(x, actual, stackStartFn = assertInternal) {
let result =
typeof x === `function`
? x(actual)
: typeof actual === x;
if (!result) {
let err = new TypeError(
typeof x === `function`
? `value did not satisfy predicate ${x.name}`
: `value was not of type ${x}`);
if (typeof Error.captureStackTrace === `function`) {
Error.captureStackTrace(err, stackStartFn);};
debugger;
onAssertionFailure();
throw err;
};
return actual;
};
assert.type = function assertType(t, actual) {
return assertInternal(t, actual, assertType);
};
assert.str = function assertStr(x) {
return assertInternal(`string`, x, assertStr);};
assert.num = function assertNum(x) {
return assertInternal(`number`, x, assertNum);};
assert.obj = function assertObj(x) {
return assertInternal(
v => (typeof v === `object` && v !== null),
x, assertObj);
};
assert.objOrNull = function assertObjOrNull(x) {
return assertInternal(`object`, x, assertObjOrNull);};
assert.fn = function assertFn(x) {
return assertInternal(`function`, x, assertFn);};
assert.sym = function assertSym(x) {
return assertInternal(`symbol`, x, assertSym);};
assert.bool = function assertBool(x) {
return assertInternal(`boolean`, x, assertBool);};
assert.bigInt = function assertBigInt(x) {
return assertInternal(`bigint`, x, assertBigInt);};
assert.undef = function assertUndef(x) {
return assertInternal(`undefined`, x, assertUndef);};
assert.int32 = function assertInt32(x) {
return assertInternal(isInt32, x, assertInt32);};
assert.uint31 = function assertUint31(x) {
return assertInternal(v => isInt32(v) && v >= 0, x, assertUint31);};
assert.safeInt = function assertSafeInt(x) {
return assertInternal(Number.isSafeInteger, x, assertSafeInt);};
assert.sequ = function assertSequ(x) {
return assertInternal(isIterable, x, assertSequ);};
assert.arr = function assertArr(x) {
return assertInternal(Array.isArray, x, assertArr);};
assert.arrOrNull = function assertArrOrNull(x) {
return assertInternal(
v => (v === null || Array.isArray(v)),
x, assertArrOrNull);
};
assert.asyncSequ = function assertAsyncSequ(x) {
return assertInternal(isAsyncIterable, x, assertAsyncSequ);};
/* --- logging --- */
export function log(...xs) {
console.log(`[${namespace}]`, ...xs);
};
log.warn = function logWarn(...xs) {
console.warn(`[${namespace}]`, ...xs);
};
log.error = function logError(...xs) {
console.error(`[${namespace}]`, ...xs);
};
log.debug = function logDebug(...xs) {
dbg && console.debug(`[${namespace}]`, ...xs);
};
Object.freeze(log);
/* --- chainable exceptions --- */
function errorClass(baseClass) {
return class extends baseClass {
constructor(msg, innerXcep) {
super(msg);
if (typeof Error.captureStackTrace === `function`) {
Error.captureStackTrace(this, this.constructor);};
if (innerXcep !== undefined) {
if (typeof innerXcep !== `object`
|| !(innerXcep instanceof Error))
{
log.warn(`GalkError instanciated with invalid `+
`inner error object (${innerXcep})`);
} else {
this.stack += `\ncaused by → ${innerXcep.name}: `
+`${innerXcep.message}\n`
+`${innerXcep.stack}`;
};
};
};
};
};
export const GalkError = errorClass(Error);
export const GalkTypeError = errorClass(TypeError);
export const GalkRangeError = errorClass(RangeError);
/* --- sequence functions --- */
const iterDoneRv = Object.freeze({done : true, value : undefined});
function iterRv(value) {
return {done : false, value};
};
export function first(xs, pred = () => true, elseVal = undefined) {
dbg && assert.sequ(xs);
dbg && assert.fn(pred);
for (let value, iter = xs[Symbol.iterator]();
!({value} = iter.next()).done;)
{
if (pred(value)) {
return value;};
};
return elseVal;
};
export function single(xs, pred = () => true, elseVal = undefined) {
dbg && assert.sequ(xs);
dbg && assert.fn(pred);
let rv = elseVal;
let found = false;
for (let value, iter = xs[Symbol.iterator]();
!({value} = iter.next()).done;)
{
if (pred(value)) {
if (found) {
return elseVal;
} else {
rv = value;
found = true;
};
};
};
return rv;
};
const chainIterProto = {
next() {
while (this.idx < this.xss.length) {
if (this.subIter === null) {
this.subIter =
this.xss[this.idx][Symbol.iterator]();};
let next = this.subIter.next();
if (!next.done) {
return next;};
this.subIter = null;
++this.idx;
};
return iterDoneRv;
},
[Symbol.iterator]() {return this;},
};
const chainResultProto = {
[Symbol.iterator]() {
return {
__proto__ : chainIterProto,
xss : this.xss,
idx : 0,
subIter : null,};
},
};
export function chainFrom(xss) {
dbg && assert.arr(xss);
dbg && xss.every(assert.sequ);
return {
__proto__ : chainResultProto,
xss,};
};
export function chain(...xss) {
return chainFrom(xss);
};
const filterIterProto = {
next() {
while (!this.done) {
let next = this.xsIter.next();
if (next.done) {
this.done = next.done;
return next;
} else if (this.pred(next.value)) {
return next;};
};
return iterDoneRv;
},
[Symbol.iterator]() {return this;},
};
const filterResultProto = {
[Symbol.iterator]() {
return {
__proto__ : filterIterProto,
xsIter : this.xs[Symbol.iterator](),
pred : this.pred,
done : false,};
},
};
export function filter(xs, pred) {
dbg && assert.sequ(xs);
return {
__proto__ : filterResultProto,
xs,
pred,};
};
const mapIterProto = {
next() {
let next = this.iter.next();
if (next.done) {return next;};
return iterRv(this.f(next.value));
},
[Symbol.iterator]() {return this;},
};
const mapResultProto = {
[Symbol.iterator]() {
return {
__proto__ : mapIterProto,
iter : this.xs[Symbol.iterator](),
f : this.f,};
},
};
export function map(xs, f) {
dbg && assert.sequ(xs);
return {
__proto__ : mapResultProto,
xs,
f,};
};
export function every(xs, pred) {
dbg && assert.sequ(xs);
dbg && assert(typeof pred === `function`);
for (let value, it = xs[Symbol.iterator](); !({value} = it.next()).done;) {
if (!pred(value)) {return false;};};
return true;
};
export function some(xs, pred) {
dbg && assert.sequ(xs);
if (pred === undefined) {
return !xs[Symbol.iterator]().next().done;};
dbg && assert(typeof pred === `function`);
for (let value, it = xs[Symbol.iterator](); !({value} = it.next()).done;) {
if (pred(value)) {return true;};};
return false;
};
export function count(xs, upTo = Infinity) {
let len = lengthOf(xs);
if (len >= 0) {
return len;};
dbg && assert.sequ(xs);
dbg && assert(typeof upTo === `number`);
len = 0;
for (const iter = xs[Symbol.iterator]();
len < upTo && !iter.next().done;
++len) {};
return len;
};
const enumerateIterProto = {
next() {
let next = this.iter.next();
if (next.done) {return next;};
return iterRv([this.i++, next.value]);
},
[Symbol.iterator]() {return this;},
};
const enumerateResultProto = {
[Symbol.iterator]() {
return {
__proto__ : enumerateIterProto,
iter : this.xs[Symbol.iterator](),
i : this.i,};
},
};
export function enumerate(xs, start = 0) {
dbg && assert.sequ(xs);
dbg && assert.num(start);
return {
__proto__ : enumerateResultProto,
xs,
i : start,};
};
export function joinString(xs, sep) {
dbg && assert.sequ(xs);
let s = ``;
const iter = xs[Symbol.iterator]();
let next;
if (sep === undefined) {
while (!(next = iter.next()).done) {
s += next.value;};
} else {
next = iter.next();
if (!next.done) {
s += next.value;
const sepStr = `${sep}`;
while (!(next = iter.next()).done) {
s += sepStr+next.value;};
};
};
return s;
};
const subseqIterProto = {
_initialise() {
this.initialised = true;
let {start, end, xs} = this;
if (this.len >= 0) {
/* known length (assumes .length is correct) */
if (start < end) {
let iter = xs[Symbol.iterator]();
/* advance iter to start offset: */
for (let i = 0; i < start; ++i) {
iter.next();};
this.n = end - start;
this.iter = iter;
};
} else {
let iter = xs[Symbol.iterator]();
/* advance iter to start offset: */
let skipN = Math.min(start, Infinity * (end - start));
let i = 0;
for (; i < skipN; ++i) {
let next = iter.next();
if (next.done) {
/* reached the end of the source;
ensure next() is not called again */
i = end;
this.doneNext = next;
break;
};
};
this.n = end - i;
this.iter = iter;
};
},
next() {
if (!this.initialised) {
this._initialise();};
if (this.n > 0) {
let rv = this.iter.next();
--this.n;
if (rv.done) {
this.n = 0;
this.doneNext = rv;
};
return rv;
} else {
return this.doneNext;};
},
[Symbol.iterator]() {return this;},
};
const subseqResultProto = {
get length() {
return this.len >= 0 ? this.len : undefined;
},
[Symbol.iterator]() {
return {
__proto__ : subseqIterProto,
initialised : false,
xs : this.xs,
n : 0,
iter : null,
doneNext : iterDoneRv,
start : this.start,
end : this.end,
len : this.len,};
},
};
export function subseq(xs, start = 0, end = Infinity) {
dbg && assert.sequ(xs);
dbg && assert.num(start);
dbg && assert.num(end);
start = Math.trunc(start);
end = Math.trunc(end);
let len = lengthOf(xs);
if (len >= 0) {
start = normaliseIntSliceTerm(start, len);
end = normaliseIntSliceTerm(end, len);
len = start < end ? end - start : 0;
} else if (start < 0 || end < 0) {
throw new RangeError(`can't slice a sequence of unknown length `
+`using negative indices`);};
return {
__proto__ : subseqResultProto,
xs,
start,
end,
len,};
};
function normaliseIntSliceTerm(val, len) {
dbg && assert.safeInt(len && len >= 0);
let n = +val;
if (!(n >= 0)) {
n += len;
if (!(n >= 0)) {
n = 0;};
} else if (n > len) {
n = len;};
return n;
};
const iotaIterProto = {
next() {
let rv = {
value : this.i,
done :
this.up
? !(this.i < this.end)
: !(this.i > this.end)};
if (!rv.done) {
this.i += this.step;};
return rv;
},
[Symbol.iterator]() {return this;},
};
const iotaResultProto = {
[Symbol.iterator]() {
return {
__proto__ : iotaIterProto,
i : this.begin,
end : this.end,
step : this.step,
up : this.begin < this.end,};
},
};
export function iota(begin, end, step = 1) {
/* iota(x) is equivalent to iota(0, x) */
if (end === undefined) {
dbg && assert(begin >= 0);
end = begin;
begin = 0;};
dbg && assert.num(step);
dbg && assert.num(begin);
dbg && assert.num(end);
return {
__proto__ : iotaResultProto,
begin, end, step,};
};
/* --- sorting --- */
export function defaultCompare(v1, v2) {
return Object.is(v1, v2) ? 0 : (v1 < v2 ? -1 : 1);
};
export function compareArrays(xs, ys, compare = defaultCompare) {
/* returns 0 or <0 or >0 */
dbg && assert(hasLength(xs));
dbg && assert(hasLength(ys));
dbg && assert.fn(compare);
if (xs === ys) {return 0;};
let nX = xs.length;
let nY = ys.length;
for (let i = 0, n = Math.min(nX, nY); i < n; ++i) {
let d = compare(xs[i], ys[i]);
if (d !== 0) {return d;};
};
return nX - nY;
};
export function sort(xs, compare) {
dbg && assert.sequ(xs);
let arr = Array.from(xs);
arr.sort(compare);
// todo:
// reimplement as drain to binary-heap followed by lazy sorting ?
return arr;
};
/* --- sorted set --- */
/* structure:
root: branch
branch: {branchBmp : int32, leafBmp : int32, subs : [sub, sub, ...]}
sub: entry | branch
entry: any value except `undefined`
key: Uint8Array
entries are sorted according to their key, which is `keyFor(entry)`.
keys are Uint8Arrays of any length. entries with the same key are
considered equivalent.
keys are interpreted as a sequence of 5-bit units. bits outside the bounds of
the array are considered zero. each subsequent unit corresponds to the depth
in the tree at which those bits apply.
a branch can have 2 to 32 subs, except the root which can have 0 to 32.
a branch may be either a regular branch or a collisison branch.
in a regular branch, `leafBmp` and `branchBmp` are bitmaps where each bit
indicates the presence of a key with the corresponding 5-bit unit (equal to
the bit's position). the `subs` array contains one element for every `1` bit
in `leafBmp|branchBmp`. the two bitmaps indicate which of the subs are
entries and which are sub-branches, respectively.
//
(todo: more details)
[leaf,leaf] collision; branchBmp: ~0, leafBmp: ~bit
[leaf,branch] collision; branchBmp: ~bit, leafBmp: ~bit
*/
export function createSortedSet() {
return bitTrieCreateEmptyBranch();
};
function bitTrieCreateEmptyBranch() {
return {branchBmp : 0, leafBmp : 0, subs : []};
};
export function iterateSortedSet(root) {
/* note: mutating the tree during iteration leads to undefined behaviour */
return {
__proto__ : sortedSetIterProto,
state : {branch : root, i : -1, bit : 0},
stack : [],};
};
const sortedSetIterProto = {
next() {
while (true) {
if (this.state === null) {
return {value : undefined, done : true};};
let {state} = this;
dbg && bitTrieAssertBranch(state.branch);
let {subs, branchBmp, leafBmp} = state.branch;
if (bitTrieIsCollisionBmps(branchBmp, leafBmp)) {
++state.i;
if (state.i === 0) {
/* subs[0] is always a leaf */
return {value : subs[0], done : false};
} else {
dbg && assert(state.i === 1);
if (branchBmp === ~0) {
/* subs[1] is a leaf */
this.state = this.stack.pop() || null;
return {value : subs[1], done : false};
} else {
/* subs[1] is a branch */
this.state = {branch : subs[1], bit : 0, i : -1};
dbg && bitTrieAssertBranch(this.state.branch);
continue;
};
};
} else {
let n = subs.length;
++state.i;
dbg && assert(state.i <= n);
if (state.i === n) {
/* branch depleted */
this.state = this.stack.pop() || null;
continue;
} else {
if (state.bit === 0) {
state.bit = bitTrieLowestBit(branchBmp, leafBmp);
} else {
state.bit = bitTrieHigherBit(
branchBmp, leafBmp, state.bit);};
if ((state.bit & leafBmp) !== 0) {
/* subs[i] is a leaf */
return {value : subs[state.i], done : false};
} else {
dbg && assert((state.bit & branchBmp) !== 0);
/* subs[i] is a branch */
this.stack.push(state);
this.state = {branch : subs[state.i], bit : 0, i : -1};
dbg && bitTrieAssertBranch(this.state.branch);
continue;
};
};
};
assert(false, `unreachable`);
};
},
[Symbol.iterator]() {return this;},
};
export function operateSortedSet(root, {
operate, /* (entry|undef, next|undef) => entry|undef */
atKey, /* bytes */
keyFor, /* (entry) => bytes */})
{
/* rules:
• entries can't be `undefined`
• once an entry is inserted,
keyFor(entry) must always yield the same key
• if `operate` updates an existing entry,
keyFor(newEntry) must equal keyFor(oldEntry)
• if `operate` or `keyFor` throws an exception,
the map remains unaltered
• if any exception is thrown not originating from `operate` or `keyFor`,
an error occurred and the map is in an undefined state
• the map can't be mutated from inside `operate` (i.e. no reentrance)
*/
dbg && assert.fn(operate);
dbg && assert.fn(keyFor);
dbg && bitTrieAssertKey(atKey);
if (dbg) {
let f = keyFor;
keyFor = x => {assert(x !== undefined); return f(x);};
};
let depth = 0;
let branch = root;
let nextSubtree = null; /* {branch, bit, i} | null */
let parentBranch = null;
while (true) {
dbg && bitTrieAssertBranch(branch, {isRoot : branch === root});
let {leafBmp, branchBmp} = branch;
let bit = bitTrieKeyBit(atKey, depth);
let i;
if (bitTrieIsCollisionBmps(leafBmp, branchBmp)) {
if (leafBmp !== ~bit) {
/* atKey doesn't collide at this depth: */
bitTrieOperateResolveCollision(branch,
{atKey, bit, depth, nextSubtree, operate, keyFor});
break;
};
/* atKey collides at this depth */
if (branchBmp === ~0) {
/* [leaf, leaf] collision: */
bitTrieOperateTwoLeafCollision(branch, {
atKey, bit, depth, nextSubtree, parentBranch, operate,
keyFor});
break;
};
/* [leaf, branch] collision */
let leafDiff = bitTrieCompareKeys(
atKey, keyFor(branch.subs[0]), depth);
if (leafDiff < 0) {
/* atKey belongs before leaf at subs[0]: */
bitTrieOperateCollisionWithLeafAfterKey(branch,
{bit, depth, operate, atKey, keyFor});
break;
} else if (leafDiff === 0) {
/* atKey matches leaf at subs[0]: */
bitTrieOperateCollisionWithLeafAtKey(branch,
{bit, operate, atKey, keyFor});
break;
};
dbg && assert(leafDiff > 0);
/* search sub-branch: */
i = 1;
dbg && assert(branchBmp === ~bit);
} else if ((bit & leafBmp) !== 0) {
/* reached leaf: */
bitTrieOperateBranchWithLeafAtKey(branch, {
atKey, bit, depth, nextSubtree, parentBranch, operate, keyFor});
break;
} else if ((bit & branchBmp) === 0) {
/* no matching leaf or sub-branch: */
bitTrieOperateBranchWithNothingAtKey(branch,
{atKey, bit, nextSubtree, operate, keyFor});
break;
} else {
/* search sub-branch: */
i = bitTrieIndex(branch, bit);
let nextBit = bitTrieHigherBit(
branch.branchBmp, branch.leafBmp, bit);
if (nextBit !== 0) {
dbg && assert(branch.subs.length > i + 1);
nextSubtree = {branch, bit : nextBit, i : i + 1};
};
};
dbg && assert(i < branch.subs.length);
parentBranch = branch;
branch = branch.subs[i];
++depth;
};
dbg && bitTrieAssertBranch(root, {isRoot : true});
};
function bitTrieOperateBranchWithLeafAtKey(branch,
{atKey, bit, depth, nextSubtree, parentBranch, operate, keyFor})
{
dbg && assert(!bitTrieIsCollision(branch));
dbg && assert((branch.leafBmp & bit) === bit);
dbg && assert((branch.branchBmp & bit) === 0);
let {subs} = branch;
let i = bitTrieIndex(branch, bit);
let leaf = subs[i];
let kLeaf = keyFor(leaf);
let diff = bitTrieCompareKeys(atKey, kLeaf, depth);
let next;
if (diff < 0) {
next = leaf;
} else {
let nextBit = bitTrieHigherBit(branch.branchBmp, branch.leafBmp, bit);
if (nextBit !== 0) {
next = bitTrieSubtreeFirstEntry({branch, bit : nextBit, i : i + 1});
} else {
next = bitTrieSubtreeFirstEntry(nextSubtree);};
};
if (diff === 0) {
/* atKey matches existing leaf */
let entry = bitTrieOperate(leaf, next, {operate, atKey, keyFor});
if (entry === undefined) {
/* delete existing entry: */
if (subs.length === 2) {
/* `branch` is a two-sub branch */
let sibling = subs[(i + 1) & 1];
if (branch.branchBmp !== 0) {
/* `sibling` is a branch */
bitTrieElevateBranchInto(
sibling, branch, branch.branchBmp);
/* elevated sibling overwrites contents of `branch` */
} else if (parentBranch === null) {
dbg && assert(branch.leafBmp !== 0);
/* `branch` is a two-sub root branch; `sibling` is a leaf */