/
AdjacencyList.js
1219 lines (1100 loc) Β· 38.9 KB
/
AdjacencyList.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
// @flow
import assert from 'assert';
import nullthrows from 'nullthrows';
import {SharedBuffer} from '@parcel/utils';
import {fromNodeId, toNodeId} from './types';
import {ALL_EDGE_TYPES, type NullEdgeType, type AllEdgeTypes} from './Graph';
import type {NodeId} from './types';
/** The address of the node in the nodes map. */
opaque type NodeAddress = number;
opaque type EdgeHash = number;
/** The address of the edge in the edges map. */
opaque type EdgeAddress = number;
// eslint-disable-next-line no-unused-vars
export type SerializedAdjacencyList<TEdgeType> = {|
nodes: Uint32Array,
edges: Uint32Array,
|};
// eslint-disable-next-line no-unused-vars
export type AdjacencyListOptions<TEdgeType> = {|
edgeCapacity?: number,
nodeCapacity?: number,
|};
/** The upper bound above which capacity should be increased. */
const LOAD_FACTOR = 0.7;
/** The lower bound below which capacity should be decreased. */
const UNLOAD_FACTOR = 0.3;
/** The max amount by which to grow the capacity. */
const MAX_GROW_FACTOR = 8;
/** The min amount by which to grow the capacity. */
const MIN_GROW_FACTOR = 2;
/** The amount by which to shrink the capacity. */
const SHRINK_FACTOR = 0.5;
export default class AdjacencyList<TEdgeType: number = 1> {
#nodes /*: NodeTypeMap<TEdgeType | NullEdgeType> */;
#edges /*: EdgeTypeMap<TEdgeType | NullEdgeType> */;
constructor(
opts?:
| SerializedAdjacencyList<TEdgeType | NullEdgeType>
| AdjacencyListOptions<TEdgeType | NullEdgeType>,
) {
let nodes;
let edges;
if (opts?.nodes) {
({nodes, edges} = opts);
this.#nodes = new NodeTypeMap(nodes);
this.#edges = new EdgeTypeMap(edges);
} else {
let {
nodeCapacity = NodeTypeMap.MIN_CAPACITY,
edgeCapacity = EdgeTypeMap.MIN_CAPACITY,
} = opts ?? {};
assert(
nodeCapacity <= NodeTypeMap.MAX_CAPACITY,
'Node capacity overflow!',
);
assert(
edgeCapacity <= EdgeTypeMap.MAX_CAPACITY,
'Edge capacity overflow!',
);
this.#nodes = new NodeTypeMap(nodeCapacity);
this.#edges = new EdgeTypeMap(edgeCapacity);
}
}
/**
* Create a new `AdjacencyList` from the given options.
*/
static deserialize(
opts: SerializedAdjacencyList<TEdgeType>,
): AdjacencyList<TEdgeType> {
return new AdjacencyList(opts);
}
/**
* Returns a serializable object of the nodes and edges in the graph.
*/
serialize(): SerializedAdjacencyList<TEdgeType> {
return {
nodes: this.#nodes.data,
edges: this.#edges.data,
};
}
get stats(): {|
/** The number of nodes in the graph. */
nodes: number,
/** The number of edge types associated with nodes in the graph. */
nodeEdgeTypes: number,
/** The maximum number of nodes the graph can contain. */
nodeCapacity: number,
/** The size of the raw nodes buffer, in mb. */
nodeBufferSize: string,
/** The current load on the nodes array. */
nodeLoad: string,
/** The number of edges in the graph. */
edges: number,
/** The number of edges deleted from the graph. */
deleted: number,
/** The maximum number of edges the graph can contain. */
edgeCapacity: number,
/** The size of the raw edges buffer, in mb. */
edgeBufferSize: string,
/** The current load on the edges array, including deletes. */
edgeLoadWithDeletes: string,
/** The current load on the edges array. */
edgeLoad: string,
/** The total number of edge hash collisions. */
collisions: number,
/** The number of collisions for the most common hash. */
maxCollisions: number,
/** The average number of collisions per hash. */
avgCollisions: number,
/** The likelihood of uniform distribution. ~1.0 indicates certainty. */
uniformity: number,
|} {
let buckets = new Map();
for (let {from, to, type} of this.getAllEdges()) {
let hash = this.#edges.hash(from, to, type);
let bucket = buckets.get(hash) || new Set();
let key = `${String(from)}, ${String(to)}, ${String(type)}`;
assert(!bucket.has(key), `Duplicate node detected: ${key}`);
bucket.add(key);
buckets.set(hash, bucket);
}
let maxCollisions = 0;
let collisions = 0;
let distribution = 0;
for (let bucket of buckets.values()) {
maxCollisions = Math.max(maxCollisions, bucket.size - 1);
collisions += bucket.size - 1;
distribution += (bucket.size * (bucket.size + 1)) / 2;
}
let uniformity =
distribution /
((this.#edges.count / (2 * this.#edges.capacity)) *
(this.#edges.count + 2 * this.#edges.capacity - 1));
return {
nodes: fromNodeId(this.#nodes.nextId),
nodeEdgeTypes: this.#nodes.count,
nodeCapacity: this.#nodes.capacity,
nodeLoad: `${Math.round(this.#nodes.load * 100)}%`,
nodeBufferSize: this.#nodes.bufferSize,
edges: this.#edges.count,
deleted: this.#edges.deletes,
edgeCapacity: this.#edges.capacity,
edgeLoad: `${Math.round(this.#edges.load * 100)}%`,
edgeLoadWithDeletes: `${Math.round(
this.#edges.getLoad(this.#edges.count + this.#edges.deletes) * 100,
)}%`,
edgeBufferSize: this.#edges.bufferSize,
collisions,
maxCollisions,
avgCollisions: Math.round((collisions / buckets.size) * 100) / 100 || 0,
uniformity: Math.round(uniformity * 100) / 100 || 0,
};
}
/**
* Resize the internal nodes array.
*
* This is used in `addNode` when the `numNodes` meets or exceeds
* the allocated size of the `nodes` array.
*/
resizeNodes(size: number) {
let nodes = this.#nodes;
// Allocate the required space for a `nodes` map of the given `size`.
this.#nodes = new NodeTypeMap(size);
// Copy the existing nodes into the new array.
this.#nodes.set(nodes.data);
}
/**
* Resize the internal edges array.
*
* This is used in `addEdge` when the `numEdges` meets or exceeds
* the allocated size of the `edges` array.
*/
resizeEdges(size: number) {
// Allocate the required space for new `nodes` and `edges` maps.
let copy = new AdjacencyList({
nodeCapacity: this.#nodes.capacity,
edgeCapacity: size,
});
// Copy the existing edges into the new array.
copy.#nodes.nextId = this.#nodes.nextId;
this.#edges.forEach(
edge =>
void copy.addEdge(
this.#edges.from(edge),
this.#edges.to(edge),
this.#edges.typeOf(edge),
),
);
// We expect to preserve the same number of edges.
assert(
this.#edges.count === copy.#edges.count,
`Edge mismatch! ${this.#edges.count} does not match ${
copy.#edges.count
}.`,
);
// Finally, copy the new data arrays over to this graph.
this.#nodes = copy.#nodes;
this.#edges = copy.#edges;
}
/**
* Adds a node to the graph.
*
* Returns the id of the added node.
*/
addNode(): NodeId {
let id = this.#nodes.getId();
// If we're in danger of overflowing the `nodes` array, resize it.
if (this.#nodes.load > LOAD_FACTOR) {
this.resizeNodes(increaseNodeCapacity(this.#nodes.capacity));
}
return id;
}
/**
* Adds an edge to the graph.
*
* Returns `true` if the edge was added,
* or `false` if the edge already exists.
*/
addEdge(
from: NodeId,
to: NodeId,
type: TEdgeType | NullEdgeType = 1,
): boolean {
assert(type > 0, `Unsupported edge type ${type}`);
let hash = this.#edges.hash(from, to, type);
let edge = this.#edges.addressOf(hash, from, to, type);
// The edge is already in the graph; do nothing.
if (edge !== null) return false;
let capacity = this.#edges.capacity;
// We add 1 to account for the edge we are adding.
let count = this.#edges.count + 1;
// Since the space occupied by deleted edges isn't reclaimed,
// we include them in our count to avoid overflowing the `edges` array.
let deletes = this.#edges.deletes;
let total = count + deletes;
// If we have enough space to keep adding edges, we can
// put off reclaiming the deleted space until the next resize.
if (this.#edges.getLoad(total) > LOAD_FACTOR) {
if (this.#edges.getLoad(deletes) > UNLOAD_FACTOR) {
// If we have a significant number of deletes, we compute our new
// capacity based on the current count, even though we decided to
// resize based on the sum total of count and deletes.
// In this case, resizing is more like a compaction.
this.resizeEdges(
getNextEdgeCapacity(capacity, count, this.#edges.getLoad(count)),
);
} else {
this.resizeEdges(
getNextEdgeCapacity(capacity, total, this.#edges.getLoad(total)),
);
}
// We must rehash because the capacity has changed.
hash = this.#edges.hash(from, to, type);
}
let toNode = this.#nodes.addressOf(to, type);
let fromNode = this.#nodes.addressOf(from, type);
if (toNode === null || fromNode === null) {
// If we're in danger of overflowing the `nodes` array, resize it.
if (this.#nodes.load >= LOAD_FACTOR) {
this.resizeNodes(increaseNodeCapacity(this.#nodes.capacity));
// We need to update our indices since the `nodes` array has changed.
toNode = this.#nodes.addressOf(to, type);
fromNode = this.#nodes.addressOf(from, type);
}
}
if (toNode === null) toNode = this.#nodes.add(to, type);
if (fromNode === null) fromNode = this.#nodes.add(from, type);
// Add our new edge to its hash bucket.
edge = this.#edges.add(hash, from, to, type);
// Link this edge to the node's list of incoming edges.
let prevIn = this.#nodes.linkIn(toNode, edge);
if (prevIn !== null) this.#edges.linkIn(prevIn, edge);
// Link this edge to the node's list of outgoing edges.
let prevOut = this.#nodes.linkOut(fromNode, edge);
if (prevOut !== null) this.#edges.linkOut(prevOut, edge);
return true;
}
*getAllEdges(): Iterator<{|
type: TEdgeType | NullEdgeType,
from: NodeId,
to: NodeId,
|}> {
for (let edge of this.#edges) {
yield {
from: this.#edges.from(edge),
to: this.#edges.to(edge),
type: this.#edges.typeOf(edge),
};
}
}
/**
* Check if the graph has an edge connecting the `from` and `to` nodes.
*/
hasEdge(
from: NodeId,
to: NodeId,
type: TEdgeType | NullEdgeType = 1,
): boolean {
let hash = this.#edges.hash(from, to, type);
return this.#edges.addressOf(hash, from, to, type) !== null;
}
/**
*
*/
removeEdge(
from: NodeId,
to: NodeId,
type: TEdgeType | NullEdgeType = 1,
): void {
let hash = this.#edges.hash(from, to, type);
let edge = this.#edges.addressOf(hash, from, to, type);
// The edge is not in the graph; do nothing.
if (edge === null) return;
let toNode = nullthrows(this.#nodes.addressOf(to, type));
let fromNode = nullthrows(this.#nodes.addressOf(from, type));
// Update the terminating node's first and last incoming edges.
this.#nodes.unlinkIn(
toNode,
edge,
this.#edges.prevIn(edge),
this.#edges.nextIn(edge),
);
// Update the originating node's first and last outgoing edges.
this.#nodes.unlinkOut(
fromNode,
edge,
this.#edges.prevOut(edge),
this.#edges.nextOut(edge),
);
// Splice the removed edge out of the linked list of edges in the bucket.
this.#edges.unlink(hash, edge);
// Splice the removed edge out of the linked list of incoming edges.
this.#edges.unlinkIn(edge);
// Splice the removed edge out of the linked list of outgoing edges.
this.#edges.unlinkOut(edge);
// Finally, delete the edge.
this.#edges.delete(edge);
}
hasInboundEdges(to: NodeId): boolean {
let node = this.#nodes.head(to);
while (node !== null) {
if (this.#nodes.firstIn(node) !== null) return true;
node = this.#nodes.next(node);
}
return false;
}
getInboundEdgesByType(
to: NodeId,
): {|type: TEdgeType | NullEdgeType, from: NodeId|}[] {
let edges = [];
let node = this.#nodes.head(to);
while (node !== null) {
let type = this.#nodes.typeOf(node);
let edge = this.#nodes.firstIn(node);
while (edge !== null) {
let from = this.#edges.from(edge);
edges.push({from, type});
edge = this.#edges.nextIn(edge);
}
node = this.#nodes.next(node);
}
return edges;
}
getOutboundEdgesByType(
from: NodeId,
): {|type: TEdgeType | NullEdgeType, to: NodeId|}[] {
let edges = [];
let node = this.#nodes.head(from);
while (node !== null) {
let type = this.#nodes.typeOf(node);
let edge = this.#nodes.firstOut(node);
while (edge !== null) {
let to = this.#edges.to(edge);
edges.push({to, type});
edge = this.#edges.nextOut(edge);
}
node = this.#nodes.next(node);
}
return edges;
}
/**
* Get the list of nodes connected from this node.
*/
getNodeIdsConnectedFrom(
from: NodeId,
type:
| AllEdgeTypes
| TEdgeType
| NullEdgeType
| Array<TEdgeType | NullEdgeType> = 1,
): NodeId[] {
let matches = node =>
type === ALL_EDGE_TYPES ||
(Array.isArray(type)
? type.includes(this.#nodes.typeOf(node))
: type === this.#nodes.typeOf(node));
let nodes = [];
let seen = new Set<NodeId>();
let node = this.#nodes.head(from);
while (node !== null) {
if (matches(node)) {
let edge = this.#nodes.firstOut(node);
while (edge !== null) {
let to = this.#edges.to(edge);
if (!seen.has(to)) {
nodes.push(to);
seen.add(to);
}
edge = this.#edges.nextOut(edge);
}
}
node = this.#nodes.next(node);
}
return nodes;
}
/**
* Get the list of nodes connected to this node.
*/
getNodeIdsConnectedTo(
to: NodeId,
type:
| AllEdgeTypes
| TEdgeType
| NullEdgeType
| Array<TEdgeType | NullEdgeType> = 1,
): NodeId[] {
let matches = node =>
type === ALL_EDGE_TYPES ||
(Array.isArray(type)
? type.includes(this.#nodes.typeOf(node))
: type === this.#nodes.typeOf(node));
let nodes = [];
let seen = new Set<NodeId>();
let node = this.#nodes.head(to);
while (node !== null) {
if (matches(node)) {
let edge = this.#nodes.firstIn(node);
while (edge !== null) {
let from = this.#edges.from(edge);
if (!seen.has(from)) {
nodes.push(from);
seen.add(from);
}
edge = this.#edges.nextIn(edge);
}
}
node = this.#nodes.next(node);
}
return nodes;
}
inspect(): any {
return {
nodes: this.#nodes.inspect(),
edges: this.#edges.inspect(),
};
}
}
/**
* `SharedTypeMap` is a hashmap of items,
* where each item has its own 'type' field.
*
* The `SharedTypeMap` is backed by a shared array buffer of fixed length.
* The buffer is partitioned into:
* - a header, which stores the capacity and number of items in the map,
* - a hash table, which is an array of pointers to linked lists of items
* with the same hash,
* - an items array, which is where the linked items are stored.
*
* hash table item
* (capacity) (ITEM_SIZE)
* ββββββββ΄βββββββ ββββ΄βββ
* ββββ¬βββ¬βββ¬ββββββββ¬βββ¬βββ¬βββ¬ββββββββ¬βββ¬βββ
* β β β β ... β β β β ... β β β
* ββββ΄βββ΄βββ΄ββββββββ΄βββ΄βββ΄βββ΄ββββββββ΄βββ΄βββ
* ββββ¬βββ βββββββββββ¬ββββββββββ
* header items
* (HEADER_SIZE) (capacity * ITEM_SIZE * BUCKET_SIZE)
*
*
* An item is added with a hash key that fits within the range of the hash
* table capacity. The item is stored at the next available address after the
* hash table, and a pointer to the address is stored in the hash table at
* the index matching the hash. If the hash is already pointing at an item,
* the pointer is stored in the `next` field of the existing item instead.
*
* hash table items
* βββββββββββ΄ββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββ
* 0 1 2 11 17 23 29 35
* βββββββββββββββββββββββββ¬βββββββββ¬βββββββββ¬βββββββββ¬βββββββββ¬βββββββββ
* β17 ββ11 ββ35 ββ...ββ23 β 1 ββ29 β 1 ββ 0 β 2 ββ 0 β 2 ββ 0 β 1 ββ...β
* βββββββββββββββββββββββββ΄βββββββββ΄βββββββββ΄βββββββββ΄βββββββββ΄βββββββββ
* β β β β² β² β² β² β²
* ββββββΌβββββΌββββββββββΌβββββββββ΄βββββββββΌβββββββββ β
* ββββββΌββββββββββ΄ββββββββββββββββββ β
* βββββββββββββββββββββββββββββββββββββββββββββββ
*/
export class SharedTypeMap<TItemType, THash, TAddress: number>
implements Iterable<TAddress>
{
/**
* The header for the `SharedTypeMap` comprises 2 4-byte chunks:
*
* struct SharedTypeMapHeader {
* int capacity;
* int count;
* }
*
* ββββββββββββ¬ββββββββ
* β CAPACITY β COUNT β
* ββββββββββββ΄ββββββββ
*/
static HEADER_SIZE: number = 2;
/** The offset from the header where the capacity is stored. */
static #CAPACITY: 0 = 0;
/** The offset from the header where the count is stored. */
static #COUNT: 1 = 1;
/**
* Each item in `SharedTypeMap` comprises 2 4-byte chunks:
*
* struct Node {
* int next;
* int type;
* }
*
* ββββββββ¬βββββββ
* β NEXT β TYPE β
* ββββββββ΄βββββββ
*/
static ITEM_SIZE: number = 2;
/** The offset at which a link to the next item in the same bucket is stored. */
static #NEXT: 0 = 0;
/** The offset at which an item's type is stored. */
static #TYPE: 1 = 1;
/** The number of items to accommodate per hash bucket. */
static BUCKET_SIZE: number = 2;
data: Uint32Array;
get capacity(): number {
return this.data[SharedTypeMap.#CAPACITY];
}
get count(): number {
return this.data[SharedTypeMap.#COUNT];
}
get load(): number {
return this.getLoad();
}
get length(): number {
return this.getLength();
}
get addressableLimit(): number {
return this.constructor.HEADER_SIZE + this.capacity;
}
get bufferSize(): string {
return `${(this.data.byteLength / 1024 / 1024).toLocaleString(undefined, {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})} mb`;
}
constructor(capacityOrData: number | Uint32Array) {
if (typeof capacityOrData === 'number') {
let {BYTES_PER_ELEMENT} = Uint32Array;
let CAPACITY = SharedTypeMap.#CAPACITY;
// $FlowFixMe[incompatible-call]
this.data = new Uint32Array(
new SharedBuffer(this.getLength(capacityOrData) * BYTES_PER_ELEMENT),
);
this.data[CAPACITY] = capacityOrData;
} else {
this.data = capacityOrData;
assert(this.getLength() === this.data.length, 'Data appears corrupt.');
}
}
set(data: Uint32Array): void {
let {HEADER_SIZE, ITEM_SIZE} = this.constructor;
let NEXT = SharedTypeMap.#NEXT;
let COUNT = SharedTypeMap.#COUNT;
let CAPACITY = SharedTypeMap.#CAPACITY;
let delta = this.capacity - data[CAPACITY];
assert(delta >= 0, 'Cannot copy to a map with smaller capacity.');
// Copy the header.
this.data.set(data.subarray(COUNT, HEADER_SIZE), COUNT);
// Copy the hash table.
let toTable = this.data.subarray(HEADER_SIZE, HEADER_SIZE + this.capacity);
toTable.set(data.subarray(HEADER_SIZE, HEADER_SIZE + data[CAPACITY]));
// Offset first links to account for the change in table capacity.
let max = toTable.length;
for (let i = 0; i < max; i++) {
if (toTable[i]) toTable[i] += delta;
}
// Copy the items.
let toItems = this.data.subarray(HEADER_SIZE + this.capacity);
toItems.set(data.subarray(HEADER_SIZE + data[CAPACITY]));
// Offset next links to account for the change in table capacity.
max = toItems.length;
for (let i = 0; i < max; i += ITEM_SIZE) {
if (toItems[i + NEXT]) toItems[i + NEXT] += delta;
}
}
getLoad(count: number = this.count): number {
let {BUCKET_SIZE} = this.constructor;
return count / (this.capacity * BUCKET_SIZE);
}
getLength(capacity: number = this.capacity): number {
let {HEADER_SIZE, ITEM_SIZE, BUCKET_SIZE} = this.constructor;
return capacity + HEADER_SIZE + ITEM_SIZE * BUCKET_SIZE * capacity;
}
/** Get the next available address in the map. */
getNextAddress(): TAddress {
let {HEADER_SIZE, ITEM_SIZE} = this.constructor;
return (HEADER_SIZE + this.capacity + this.count * ITEM_SIZE: any);
}
/** Get the address of the first item with the given hash. */
head(hash: THash): TAddress | null {
let {HEADER_SIZE} = this.constructor;
return (this.data[HEADER_SIZE + (hash: any)]: any) || null;
}
/** Get the address of the next item with the same hash as the given item. */
next(item: TAddress): TAddress | null {
let NEXT = SharedTypeMap.#NEXT;
return (this.data[(item: any) + NEXT]: any) || null;
}
typeOf(item: TAddress): TItemType {
return (this.data[item + SharedTypeMap.#TYPE]: any);
}
link(hash: THash, item: TAddress, type: TItemType): void {
let COUNT = SharedTypeMap.#COUNT;
let NEXT = SharedTypeMap.#NEXT;
let TYPE = SharedTypeMap.#TYPE;
let {HEADER_SIZE} = this.constructor;
this.data[item + TYPE] = (type: any);
let prev = this.head(hash);
if (prev !== null) {
let next = this.next(prev);
while (next !== null) {
prev = next;
next = this.next(next);
}
this.data[prev + NEXT] = item;
} else {
// This is the first item in the bucket!
this.data[HEADER_SIZE + (hash: any)] = item;
}
this.data[COUNT]++;
}
unlink(hash: THash, item: TAddress): void {
let COUNT = SharedTypeMap.#COUNT;
let NEXT = SharedTypeMap.#NEXT;
let TYPE = SharedTypeMap.#TYPE;
let {HEADER_SIZE} = this.constructor;
this.data[item + TYPE] = 0;
let head = this.head(hash);
// No bucket to unlink from.
if (head === null) return;
let next = this.next(item);
let prev = null;
let candidate = head;
while (candidate !== null && candidate !== item) {
prev = candidate;
candidate = this.next(candidate);
}
if (prev !== null && next !== null) {
this.data[prev + NEXT] = next;
} else if (prev !== null) {
this.data[prev + NEXT] = 0;
} else if (next !== null) {
this.data[HEADER_SIZE + (hash: any)] = next;
} else {
this.data[HEADER_SIZE + (hash: any)] = 0;
}
this.data[item + NEXT] = 0;
this.data[COUNT]--;
}
forEach(cb: (item: TAddress) => void): void {
let max = this.count;
let len = this.length;
let {ITEM_SIZE} = this.constructor;
for (
let i = this.addressableLimit, count = 0;
i < len && count < max;
i += ITEM_SIZE
) {
// Skip items that don't have a type.
if (this.typeOf((i: any))) {
cb((i: any));
count++;
}
}
}
// Trick Flow into believing in `Symbol.iterator`.
// See https://github.com/facebook/flow/issues/1163#issuecomment-353523840
/*:: @@iterator(): Iterator<TAddress> { return ({}: any); } */
// $FlowFixMe[unsupported-syntax]
*[Symbol.iterator](): Iterator<TAddress> {
let max = this.count;
let len = this.length;
let {ITEM_SIZE} = this.constructor;
for (
let i = this.addressableLimit, count = 0;
i < len && count < max;
i += ITEM_SIZE
) {
if (this.data.subarray(i, i + ITEM_SIZE).some(Boolean)) {
yield (i: any);
count++;
}
}
}
inspect(): {|
header: Uint32Array,
table: Uint32Array,
data: Uint32Array,
|} {
const {HEADER_SIZE, ITEM_SIZE, BUCKET_SIZE} = this.constructor;
let min = HEADER_SIZE + this.capacity;
let max = min + this.capacity * BUCKET_SIZE * ITEM_SIZE;
return {
header: this.data.subarray(0, HEADER_SIZE),
table: this.data.subarray(HEADER_SIZE, min),
data: this.data.subarray(min, max),
};
}
}
/**
* Nodes are stored in a `SharedTypeMap`, keyed on node id plus an edge type.
* This means that for any given unique node id, there may be `e` nodes in the
* map, where `e` is the number of possible edge types in the graph.
*/
export class NodeTypeMap<TEdgeType> extends SharedTypeMap<
TEdgeType,
NodeId,
NodeAddress,
> {
/**
* In addition to the header defined by `SharedTypeMap`, the header for
* the node map includes a 4-byte `nextId` chunk:
*
* struct NodeTypeMapHeader {
* int capacity; // from `SharedTypeMap`
* int count; // from `SharedTypeMap`
* int nextId;
* }
*
* ββββββββββββ¬ββββββββ¬ββββββββββ
* β CAPACITY β COUNT β NEXT_ID β
* ββββββββββββ΄ββββββββ΄ββββββββββ
*/
static HEADER_SIZE: number = 3;
/** The offset from the header where the next available node id is stored. */
static #NEXT_ID = 2;
/**
* In addition to the item fields defined by `SharedTypeMap`,
* each node includes another 4 4-byte chunks:
*
* struct Node {
* int next; // from `SharedTypeMap`
* int type; // from `SharedTypeMap`
* int firstIn;
* int firstOut;
* int lastIn;
* int lastOut;
* }
*
* ββββββββ¬βββββββ¬βββββββββββ¬ββββββββββββ¬ββββββββββ¬βββββββββββ
* β NEXT β TYPE β FIRST_IN β FIRST_OUT β LAST_IN β LAST_OUT β
* ββββββββ΄βββββββ΄βββββββββββ΄ββββββββββββ΄ββββββββββ΄βββββββββββ
*/
static ITEM_SIZE: number = 6;
/** The offset at which a node's first incoming edge of this type is stored. */
static #FIRST_IN = 2;
/** The offset at which a node's first outgoing edge of this type is stored. */
static #FIRST_OUT = 3;
/** The offset at which a node's last incoming edge of this type is stored. */
static #LAST_IN = 4;
/** The offset at which a node's last outgoing edge of this type is stored. */
static #LAST_OUT = 5;
/** The smallest functional node map capacity. */
static MIN_CAPACITY: number = 2;
/** The largest possible node map capacity. */
static MAX_CAPACITY: number = Math.floor(
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length#what_went_wrong
(2 ** 31 - 1 - NodeTypeMap.HEADER_SIZE) /
NodeTypeMap.ITEM_SIZE /
NodeTypeMap.BUCKET_SIZE,
);
get nextId(): NodeId {
return toNodeId(this.data[NodeTypeMap.#NEXT_ID]);
}
set nextId(nextId: NodeId) {
this.data[NodeTypeMap.#NEXT_ID] = fromNodeId(nextId);
}
/** Get a unique node id. */
getId(): NodeId {
return toNodeId(this.data[NodeTypeMap.#NEXT_ID]++);
}
getLoad(count: number = this.count): number {
return Math.max(
fromNodeId(this.nextId) / this.capacity,
super.getLoad(count),
);
}
add(node: NodeId, type: TEdgeType): NodeAddress {
let index = fromNodeId(node);
assert(
index >= 0 && index < this.data[NodeTypeMap.#NEXT_ID],
`Invalid node id ${String(node)} (${this.data[NodeTypeMap.#NEXT_ID]})`,
);
let address = this.getNextAddress();
this.link(node, address, type);
return address;
}
addressOf(node: NodeId, type: TEdgeType): NodeAddress | null {
let address = this.head(node);
while (address !== null) {
if (this.typeOf(address) === type) {
return address;
}
address = this.next(address);
}
return null;
}
firstIn(node: NodeAddress): EdgeAddress | null {
return this.data[node + NodeTypeMap.#FIRST_IN] || null;
}
firstOut(node: NodeAddress): EdgeAddress | null {
return this.data[node + NodeTypeMap.#FIRST_OUT] || null;
}
lastIn(node: NodeAddress): EdgeAddress | null {
return this.data[node + NodeTypeMap.#LAST_IN] || null;
}
lastOut(node: NodeAddress): EdgeAddress | null {
return this.data[node + NodeTypeMap.#LAST_OUT] || null;
}
linkIn(node: NodeAddress, edge: EdgeAddress): EdgeAddress | null {
let first = this.firstIn(node);
let last = this.lastIn(node);
if (first === null) this.data[node + NodeTypeMap.#FIRST_IN] = edge;
this.data[node + NodeTypeMap.#LAST_IN] = edge;
return last;
}
unlinkIn(
node: NodeAddress,
edge: EdgeAddress,
prev: EdgeAddress | null,
next: EdgeAddress | null,
): void {
let first = this.firstIn(node);
let last = this.lastIn(node);
if (last === edge) {
this.data[node + NodeTypeMap.#LAST_IN] = prev === null ? 0 : prev;
}
if (first === edge) {
this.data[node + NodeTypeMap.#FIRST_IN] = next === null ? 0 : next;
}
}
linkOut(node: NodeAddress, edge: EdgeAddress): EdgeAddress | null {
let first = this.firstOut(node);
let last = this.lastOut(node);
if (first === null) this.data[node + NodeTypeMap.#FIRST_OUT] = edge;
this.data[node + NodeTypeMap.#LAST_OUT] = edge;
return last;
}
unlinkOut(
node: NodeAddress,
edge: EdgeAddress,
prev: EdgeAddress | null,
next: EdgeAddress | null,
): void {
let first = this.firstOut(node);
let last = this.lastOut(node);
if (last === edge) {
this.data[node + NodeTypeMap.#LAST_OUT] = prev === null ? 0 : prev;
}
if (first === edge) {
this.data[node + NodeTypeMap.#FIRST_OUT] = next === null ? 0 : next;
}
}
}
/**
* Edges are stored in a `SharedTypeMap`,
* keyed on the 'from' and 'to' node ids, and the edge type.
*/
export class EdgeTypeMap<TEdgeType> extends SharedTypeMap<
TEdgeType,
EdgeHash,
EdgeAddress,
> {
/**
* In addition to the header defined by `SharedTypeMap`, the header for
* the edge map includes a 4-byte `deletes` chunk:
*
* struct EdgeTypeMapHeader {
* int capacity; // from `SharedTypeMap`
* int count; // from `SharedTypeMap`
* int deletes;
* }
*
* ββββββββββββ¬ββββββββ¬ββββββββββ
* β CAPACITY β COUNT β DELETES β
* ββββββββββββ΄ββββββββ΄ββββββββββ
*/
static HEADER_SIZE: number = 3;
/** The offset from the header where the delete count is stored. */
static #DELETES = 2;