-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathNode.zig
More file actions
1375 lines (1165 loc) · 50.1 KB
/
Node.zig
File metadata and controls
1375 lines (1165 loc) · 50.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
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
///! Merkle node backed by a memory pool
const std = @import("std");
const Allocator = std.mem.Allocator;
const hashOne = @import("hashing").hashOne;
const getZeroHash = @import("hashing").getZeroHash;
const max_depth = @import("hashing").max_depth;
const Depth = @import("hashing").Depth;
const Gindex = @import("gindex.zig").Gindex;
hash: [32]u8,
left: Id,
right: Id,
state: State,
const Node = @This();
pub const Error = error{
/// Attempt to access a child of a node that is not a branch node.
InvalidNode,
/// Attempt to use a length beyond the tree's length at a given depth.
InvalidLength,
// Attempt to increment the reference count of a node that has reached the maximum reference count.
RefCountOverflow,
// Out of memory
OutOfMemory,
};
/// An enum which manages `node_type`, `ref_count`, and `next_free`.
/// Used by the Pool to manage the free list (single-linked-list) and reference count.
///
/// The high bit is used to indicate if the node is free or not.
/// If the high bit is set, the `next_free` is stored in the next 31 bits.
///
/// `[1, next_free]`
///
/// If the high bit is not set, the next 3 bits determine the `node_type`
/// The following 28 bits are used for the `ref_count`.
///
/// `[0, node_type, ref_count]`
pub const State = enum(u32) {
_,
pub const free: State = @enumFromInt(0x80000000);
pub const max_next_free = 0x7FFFFFFF;
// five types of nodes, use 3 bits
const node_type = 0x70000000;
pub const zero: State = @enumFromInt(0x00000000);
pub const leaf: State = @enumFromInt(0x10000000);
pub const branch_lazy: State = @enumFromInt(0x20000000);
pub const branch_computed: State = @enumFromInt(0x30000000);
pub const branch_struct_lazy: State = @enumFromInt(0x40000000);
pub const branch_struct_computed: State = @enumFromInt(0x50000000);
pub const max_ref_count = 0x0FFFFFFF;
pub inline fn isFree(node: State) bool {
return @intFromEnum(node) & @intFromEnum(free) != 0;
}
pub inline fn initNextFree(next_free: Id) State {
return @enumFromInt(@intFromEnum(free) | @intFromEnum(next_free));
}
pub inline fn getNextFree(node: State) Id {
return @enumFromInt(@intFromEnum(node) & max_next_free);
}
pub inline fn isZero(node: State) bool {
return @intFromEnum(node) & node_type == @intFromEnum(zero);
}
pub inline fn isLeaf(node: State) bool {
return @intFromEnum(node) & node_type == @intFromEnum(leaf);
}
pub inline fn isBranch(node: State) bool {
return @intFromEnum(node) & @intFromEnum(branch_lazy) != 0;
}
pub inline fn isBranchLazy(node: State) bool {
return @intFromEnum(node) & node_type == @intFromEnum(branch_lazy);
}
pub inline fn isBranchComputed(node: State) bool {
return @intFromEnum(node) & node_type == @intFromEnum(branch_computed);
}
pub inline fn isBranchStruct(node: State) bool {
return @intFromEnum(node) & @intFromEnum(branch_struct_lazy) != 0;
}
pub inline fn isBranchStructLazy(node: State) bool {
return @intFromEnum(node) & node_type == @intFromEnum(branch_struct_lazy);
}
pub inline fn isBranchStructComputed(node: State) bool {
return @intFromEnum(node) & node_type == @intFromEnum(branch_struct_computed);
}
pub inline fn setBranchComputed(node: *State) void {
node.* = @enumFromInt(@intFromEnum(node.*) | @intFromEnum(branch_computed));
}
pub inline fn setBranchStructComputed(node: *State) void {
node.* = @enumFromInt(@intFromEnum(node.*) | @intFromEnum(branch_struct_computed));
}
pub inline fn initRefCount(node: State) State {
return node;
}
pub inline fn getRefCount(node: State) u32 {
return @intFromEnum(node) & max_ref_count;
}
pub inline fn incRefCount(node: *State) Error!u32 {
const ref_count = node.getRefCount();
if (ref_count == max_ref_count) {
return error.RefCountOverflow;
}
node.* = @enumFromInt(@intFromEnum(node.*) + 1);
return ref_count + 1;
}
pub inline fn decRefCount(node: *State) u32 {
const ref_count = node.getRefCount();
if (ref_count == 0) {
return 0;
}
node.* = @enumFromInt(@intFromEnum(node.*) - 1);
return ref_count - 1;
}
};
/// Stores nodes in a memory pool
pub const Pool = struct {
allocator: Allocator,
nodes: std.MultiArrayList(Node).Slice,
next_free_node: Id,
pub const BranchStructRef = struct {
ptr: *anyopaque,
get_root: *const fn (ptr: *const anyopaque, out: *[32]u8) void,
deinit: *const fn (ptr: *anyopaque, allocator: Allocator) void,
};
pub const free_bit: u32 = 0x80000000;
pub const max_ref_count: u32 = 0x7FFFFFFF;
/// Initializes the memory pool with `pool_size` + `zero_hash_max_depth` items.
pub fn init(allocator: Allocator, pool_size: u32) Error!Pool {
var pool: Pool = .{
.allocator = allocator,
.nodes = undefined,
.next_free_node = @enumFromInt(max_depth),
};
if (pool_size + max_depth >= free_bit) {
return error.OutOfMemory;
}
var nodes = std.MultiArrayList(Node).empty;
try nodes.resize(allocator, pool_size + max_depth);
nodes.len = max_depth;
pool.nodes = nodes.slice();
// Populate zero hashes (at index 0 to zero_hash_max_depth - 1)
for (0..max_depth) |i| {
pool.nodes.set(@intCast(i), Node{
.hash = getZeroHash(@intCast(i)).*,
.left = if (i == 0) undefined else @enumFromInt(i - 1),
.right = if (i == 0) undefined else @enumFromInt(i - 1),
.state = .zero,
});
}
try pool.preheat(pool_size);
return pool;
}
pub fn deinit(self: *Pool) void {
self.nodes.deinit(self.allocator);
self.* = undefined;
}
/// Preheats the memory pool by pre-allocating `size` items.
/// This allows up to `size` active allocations before an
/// `OutOfMemory` error might happen when calling `create*()`.
pub fn preheat(self: *Pool, additional_size: u32) Allocator.Error!void {
const size = self.nodes.len;
const new_size = size + additional_size;
if (new_size >= free_bit) {
return error.OutOfMemory;
}
var nodes = self.nodes.toMultiArrayList();
try nodes.resize(self.allocator, new_size);
self.nodes = nodes.slice();
const states = self.nodes.items(.state);
for (size..new_size) |i| {
states[i] = State.initNextFree(@enumFromInt(@as(u32, @intCast(i + 1))));
}
}
/// Assumes that self.next_free_node is in bounds and will not allocate
/// Assumes that the caller will initialize the Id's state / ref count
inline fn createUnsafe(self: *Pool, states: []State) Id {
// pop from the free list
const n: Id = self.next_free_node;
// mask away the free bit
self.next_free_node = states[@intFromEnum(n)].getNextFree();
return n;
}
fn create(self: *Pool) Allocator.Error!Id {
std.debug.assert(@intFromEnum(self.next_free_node) <= self.nodes.len);
if (@intFromEnum(self.next_free_node) == self.nodes.len) {
try self.preheat(1);
}
return self.createUnsafe(self.nodes.items(.state));
}
/// Returns the number of nodes currently in use (not free)
pub fn getNodesInUse(self: *Pool) usize {
var count: usize = 0;
const states = self.nodes.items(.state);
for (states) |state| {
if (!state.isFree()) {
count += 1;
}
}
return count;
}
pub fn createLeaf(self: *Pool, hash: *const [32]u8) Allocator.Error!Id {
const node_id = try self.create();
self.nodes.items(.hash)[@intFromEnum(node_id)] = hash.*;
self.nodes.items(.state)[@intFromEnum(node_id)] = State.leaf.initRefCount();
return node_id;
}
pub fn createLeafFromUint(self: *Pool, uint: u256) Allocator.Error!Id {
var hash: [32]u8 = undefined;
std.mem.writeInt(u256, &hash, uint, .little);
return self.createLeaf(&hash);
}
pub fn createBranch(self: *Pool, left_id: Id, right_id: Id) Error!Id {
std.debug.assert(@intFromEnum(left_id) < self.nodes.len);
std.debug.assert(@intFromEnum(right_id) < self.nodes.len);
const node_id = try self.create();
const states = self.nodes.items(.state);
std.debug.assert(!states[@intFromEnum(left_id)].isFree());
std.debug.assert(!states[@intFromEnum(right_id)].isFree());
self.nodes.items(.left)[@intFromEnum(node_id)] = left_id;
self.nodes.items(.right)[@intFromEnum(node_id)] = right_id;
states[@intFromEnum(node_id)] = State.branch_lazy.initRefCount();
try self.refUnsafe(left_id, states);
try self.refUnsafe(right_id, states);
return node_id;
}
/// The pool allocates and owns a clone of `ptr`; the caller retains ownership of its data.
pub fn createBranchStruct(self: *Pool, comptime T: type, ptr: *const T) Error!Id {
const cloned = try T.init(self.allocator, ptr);
errdefer @constCast(cloned).deinit(self.allocator);
const branch_struct_ref = try self.allocator.create(BranchStructRef);
errdefer self.allocator.destroy(branch_struct_ref);
branch_struct_ref.* = .{
.ptr = @ptrCast(@constCast(cloned)),
.get_root = struct {
fn call(ptr_erased: *const anyopaque, out: *[32]u8) void {
const typed_ptr: *const T = @ptrCast(@alignCast(ptr_erased));
typed_ptr.getRoot(out);
}
}.call,
.deinit = struct {
fn call(ptr_erased: *anyopaque, allocator: Allocator) void {
const typed_ptr: *T = @ptrCast(@alignCast(ptr_erased));
typed_ptr.deinit(allocator);
}
}.call,
};
const node_id = try self.create();
const ptr_usize = @intFromPtr(branch_struct_ref);
const right_ptr_value: u32 = @intCast(ptr_usize & 0xFFFFFFFF);
self.nodes.items(.right)[@intFromEnum(node_id)] = @enumFromInt(right_ptr_value);
if (comptime @sizeOf(usize) == 8) {
const left_ptr_value: u32 = @intCast(ptr_usize >> 32);
self.nodes.items(.left)[@intFromEnum(node_id)] = @enumFromInt(left_ptr_value);
} else {
self.nodes.items(.left)[@intFromEnum(node_id)] = @enumFromInt(0);
}
self.nodes.items(.state)[@intFromEnum(node_id)] = State.branch_struct_lazy.initRefCount();
return node_id;
}
/// Allocates nodes into the pool.
///
/// All nodes are allocated with refcount=0.
/// Nodes allocated here are expected to be attached via `rebind`.
/// Return true if pool had to allocate more memory, false otherwise.
pub fn alloc(self: *Pool, out: []Id) Allocator.Error!bool {
var states = self.nodes.items(.state);
var allocated: bool = false;
for (0..out.len) |i| {
std.debug.assert(@intFromEnum(self.next_free_node) <= self.nodes.len);
if (@intFromEnum(self.next_free_node) == self.nodes.len) {
const remaining = out.len - i;
try self.preheat(@intCast(remaining));
// TODO how to handle failing to resize here
// errdefer self.free(out[0..i]);
states = self.nodes.items(.state);
allocated = true;
}
out[i] = self.createUnsafe(states);
states[@intFromEnum(out[i])] = State.branch_lazy.initRefCount();
// Initialize left/right children to zero.
//
// The node is marked as `branch_lazy`, so `unref` will attempt to traverse its children during cleanup.
// If an error occurs before the node is fully constructed and `free` is called, stale values in `left`/`right`
// could lead to accessing invalid memory. Setting them to zero ensures safe cleanup.
self.nodes.items(.left)[@intFromEnum(out[i])] = @enumFromInt(0);
self.nodes.items(.right)[@intFromEnum(out[i])] = @enumFromInt(0);
}
return allocated;
}
/// Unrefs nodes from the pool.
pub fn free(self: *Pool, out: []Id) void {
for (out) |node_id| {
self.unref(node_id);
}
}
/// Rebinds nodes in the pool.
///
/// It is assumed that `out` nodes have been freshly allocated and are not referenced elsewhere.
pub fn rebind(self: *Pool, out: []Id, left_ids: []Id, right_ids: []Id) Error!void {
std.debug.assert(out.len == left_ids.len);
std.debug.assert(out.len == right_ids.len);
const lefts = self.nodes.items(.left);
const rights = self.nodes.items(.right);
const states = self.nodes.items(.state);
for (0..out.len) |i| {
std.debug.assert(@intFromEnum(out[i]) < self.nodes.len);
lefts[@intFromEnum(out[i])] = left_ids[i];
rights[@intFromEnum(out[i])] = right_ids[i];
try self.refUnsafe(left_ids[i], states);
try self.refUnsafe(right_ids[i], states);
}
}
pub fn ref(self: *Pool, node_id: Id) Error!void {
// Check if the node is in bounds
if (@intFromEnum(node_id) >= self.nodes.len) {
return;
}
const states = self.nodes.items(.state);
// Check if the node is free
if (states[@intFromEnum(node_id)].isFree()) {
return;
}
try self.refUnsafe(node_id, states);
}
// Assumes `node_id` to be in bounds and not free
fn refUnsafe(self: *Pool, node_id: Id, states: []Node.State) Error!void {
_ = self; // suppress unused for now (no member access needed)
if (states[@intFromEnum(node_id)].isZero()) {
return;
}
_ = try states[@intFromEnum(node_id)].incRefCount();
}
pub fn getStructPtr(self: *Pool, node_id: Id, comptime T: type) Error!*const T {
const state = self.nodes.items(.state)[@intFromEnum(node_id)];
if (!state.isBranchStruct()) {
return Error.InvalidNode;
}
const struct_ref = self.getBranchStructRefUnsafe(node_id);
const ptr: *const T = @ptrCast(@alignCast(struct_ref.ptr));
return ptr;
}
pub fn getBranchStructRefUnsafe(self: *Pool, node_id: Id) *BranchStructRef {
const left_ptr_value: u32 = @intFromEnum(self.nodes.items(.left)[@intFromEnum(node_id)]);
const right_ptr_value: u32 = @intFromEnum(self.nodes.items(.right)[@intFromEnum(node_id)]);
const ptr_int: usize = if (comptime @sizeOf(usize) == 8)
@as(u64, left_ptr_value) << 32 | @as(u64, right_ptr_value)
else
right_ptr_value;
return @ptrFromInt(ptr_int);
}
pub fn unref(self: *Pool, node_id: Id) void {
const states = self.nodes.items(.state);
const lefts = self.nodes.items(.left);
const rights = self.nodes.items(.right);
var stack: [max_depth]Id = undefined;
var current: ?Id = node_id;
var sp: Depth = 0;
while (true) {
const id = current orelse {
if (sp == 0) {
break;
}
sp -= 1;
current = stack[sp];
continue;
};
// Continue if the the node is out of bounds
if (@intFromEnum(id) >= self.nodes.len) {
current = null;
continue;
}
// Detect unref on already-freed node (indicates a bug in ref counting)
// Must check isFree() before isZero() because freed nodes have node_type bits = 0
const is_free = states[@intFromEnum(id)].isFree();
if (is_free) {
current = null;
continue;
}
// Continue if zero node (zero nodes are not ref counted)
if (states[@intFromEnum(id)].isZero()) {
current = null;
continue;
}
// Decrement the reference count
const ref_count = states[@intFromEnum(id)].decRefCount();
// If the reference count is not zero, continue
if (ref_count != 0) {
current = null;
continue;
}
// If the node is a branch, push its children onto the stack
if (states[@intFromEnum(id)].isBranch()) {
stack[sp] = rights[@intFromEnum(id)];
sp += 1;
current = lefts[@intFromEnum(id)];
} else {
current = null;
}
if (states[@intFromEnum(id)].isBranchStruct()) {
const struct_ref = self.getBranchStructRefUnsafe(id);
struct_ref.deinit(struct_ref.ptr, self.allocator);
self.allocator.destroy(struct_ref);
}
// Return the node to the free list
states[@intFromEnum(id)] = State.initNextFree(self.next_free_node);
self.next_free_node = id;
}
}
};
/// A handle which uniquely identifies the node
///
/// This handle only has meaning in the context of a `Pool`.
pub const Id = enum(u32) {
_,
/// Returns true if navigation to the child node is not possible
pub inline fn noChild(node_id: Id, state: State) bool {
return state.isLeaf() or state.isBranchStruct() or @intFromEnum(node_id) == 0;
}
/// Returns the root hash of the tree, computing any lazy branches as needed.
pub fn getRoot(node_id: Id, pool: *Pool) *const [32]u8 {
const state = &pool.nodes.items(.state)[@intFromEnum(node_id)];
const hash = &pool.nodes.items(.hash)[@intFromEnum(node_id)];
if (state.isBranchLazy()) {
const left = pool.nodes.items(.left)[@intFromEnum(node_id)].getRoot(pool);
const right = pool.nodes.items(.right)[@intFromEnum(node_id)].getRoot(pool);
hashOne(hash, left, right);
state.setBranchComputed();
}
if (state.isBranchStructLazy()) {
const struct_ref = pool.getBranchStructRefUnsafe(node_id);
struct_ref.get_root(struct_ref.ptr, hash);
state.setBranchStructComputed();
}
return hash;
}
pub fn getLeft(node_id: Id, pool: *Pool) Error!Id {
const state = pool.nodes.items(.state)[@intFromEnum(node_id)];
if (node_id.noChild(state)) {
return Error.InvalidNode;
}
return pool.nodes.items(.left)[@intFromEnum(node_id)];
}
pub fn getRight(node_id: Id, pool: *Pool) Error!Id {
const state = pool.nodes.items(.state)[@intFromEnum(node_id)];
if (node_id.noChild(state)) {
return Error.InvalidNode;
}
return pool.nodes.items(.right)[@intFromEnum(node_id)];
}
pub fn getState(node_id: Id, pool: *Pool) State {
return pool.nodes.items(.state)[@intFromEnum(node_id)];
}
pub fn getNode(root_node: Id, pool: *Pool, gindex: Gindex) Error!Id {
if (@intFromEnum(gindex) <= 1) {
return root_node;
}
const path_len = gindex.pathLen();
var path = gindex.toPath();
const states = pool.nodes.items(.state);
const lefts = pool.nodes.items(.left);
const rights = pool.nodes.items(.right);
var node_id: Id = root_node;
for (0..path_len) |_| {
if (node_id.noChild(states[@intFromEnum(node_id)])) {
return Error.InvalidNode;
}
if (path.left()) {
node_id = lefts[@intFromEnum(node_id)];
} else {
node_id = rights[@intFromEnum(node_id)];
}
path.next();
}
return node_id;
}
pub fn getNodeAtDepth(root_node: Id, pool: *Pool, depth: Depth, index: usize) Error!Id {
return try root_node.getNode(
pool,
Gindex.fromDepth(depth, index),
);
}
pub fn setNode(root_node: Id, pool: *Pool, gindex: Gindex, node_id: Id) Error!Id {
if (@intFromEnum(gindex) <= 1) {
return node_id;
}
const path_len = gindex.pathLen();
var path = gindex.toPath();
var path_lefts_buf: [max_depth]Id = undefined;
var path_rights_buf: [max_depth]Id = undefined;
var path_parents_buf: [max_depth]Id = undefined;
const path_lefts = path_lefts_buf[0..path_len];
const path_rights = path_rights_buf[0..path_len];
const path_parents = path_parents_buf[0..path_len];
_ = try pool.alloc(path_parents);
errdefer pool.free(path_parents);
const states = pool.nodes.items(.state);
const lefts = pool.nodes.items(.left);
const rights = pool.nodes.items(.right);
var id = root_node;
for (0..path_len - 1) |i| {
if (id.noChild(states[@intFromEnum(id)])) {
return Error.InvalidNode;
}
if (path.left()) {
path_lefts[i] = path_parents[i + 1];
path_rights[i] = rights[@intFromEnum(id)];
id = lefts[@intFromEnum(id)];
} else {
path_lefts[i] = lefts[@intFromEnum(id)];
path_rights[i] = path_parents[i + 1];
id = rights[@intFromEnum(id)];
}
path.next();
}
// final layer
if (id.noChild(states[@intFromEnum(id)])) {
return Error.InvalidNode;
}
if (path.left()) {
path_lefts[path_len - 1] = node_id;
path_rights[path_len - 1] = rights[@intFromEnum(id)];
} else {
path_lefts[path_len - 1] = lefts[@intFromEnum(id)];
path_rights[path_len - 1] = node_id;
}
try pool.rebind(
path_parents,
path_lefts,
path_rights,
);
return path_parents[0];
}
pub fn setNodeAtDepth(root_node: Id, pool: *Pool, depth: Depth, index: usize, node_id: Id) Error!Id {
return try root_node.setNode(
pool,
Gindex.fromDepth(depth, index),
node_id,
);
}
/// Get multiple nodes in a single traversal
///
/// Stores `out.len` nodes at the specified `depth`, starting from `start_index`.
pub fn getNodesAtDepth(root_node: Id, pool: *Pool, depth: Depth, start_index: usize, out: []Id) Error!void {
std.debug.assert(out.len > 0);
const base_gindex = Gindex.fromDepth(depth, 0);
if (@intFromEnum(base_gindex) <= 1) {
out[0] = root_node;
return;
}
const path_len = base_gindex.pathLen();
var parents_buf: [max_depth]Id = undefined;
var node_id = root_node;
var diffi = depth;
const states = pool.nodes.items(.state);
const lefts = pool.nodes.items(.left);
const rights = pool.nodes.items(.right);
// For each index specified
for (0..out.len) |i| {
// Calculate the gindex bits for the current index
const index = start_index + i;
const gindex: Gindex = @enumFromInt(@as(Gindex.Uint, @intCast(@intFromEnum(base_gindex) | index)));
const d = path_len - diffi;
var path = gindex.toPath();
path.nextN(d);
// Navigate down (from the depth diff) to the current index, populating parents
for (d..path_len) |bit_i| {
if (node_id.noChild(states[@intFromEnum(node_id)])) {
return Error.InvalidNode;
}
parents_buf[bit_i] = node_id;
if (path.left()) {
node_id = lefts[@intFromEnum(node_id)];
} else {
node_id = rights[@intFromEnum(node_id)];
}
path.next();
}
// Populate the output
out[i] = node_id;
// Calculate the depth diff to navigate from current index to the next
// This is always gt 0 (unless an index is repeated)
diffi = if (i == out.len - 1)
depth
else
@intCast(@bitSizeOf(Gindex) - @clz(index ^ index + 1));
// Navigate upwards depth diff times
node_id = parents_buf[path_len - diffi];
}
}
/// Set multiple nodes in batch, editing and traversing nodes strictly once.
/// - indexes MUST be sorted in ascending order beforehand.
/// - All indexes must be at the exact same depth.
/// - Depth must be > 0, if 0 just replace the root node.
pub fn setNodesAtDepth(root_node: Id, pool: *Pool, depth: Depth, indices: []const usize, nodes: []Id) Error!Id {
std.debug.assert(nodes.len == indices.len);
if (indices.len == 0) {
return root_node;
}
const base_gindex = Gindex.fromDepth(depth, 0);
if (@intFromEnum(base_gindex) <= 1) {
return nodes[0];
}
const path_len = base_gindex.pathLen();
var path_parents_buf: [max_depth]Id = undefined;
// at each level, there is at most 1 unfinalized parent per traversal
// "unfinalized" means it may or may not be part of the new tree
var unfinalized_parents_buf: [max_depth]?Id = undefined;
var path_lefts_buf: [max_depth]Id = undefined;
var path_rights_buf: [max_depth]Id = undefined;
// right_move means it's part of the new tree, it happens when we traverse right
var right_move: [max_depth]bool = undefined;
const path_parents = path_parents_buf[0..path_len];
const path_lefts = path_lefts_buf[0..path_len];
const path_rights = path_rights_buf[0..path_len];
var node_id = root_node;
errdefer {
// at any points, node_id is the root of the in-progress new tree
if (node_id != root_node) pool.unref(node_id);
// orphaned nodes were unrefed along the way through unfinalized_parents_buf
// path_parents may or maynot be part of the in-progress new tree, there is no issue to double unref()
pool.free(path_parents);
}
// The shared depth between the previous and current index
// This is initialized as 0 since the first index has no previous index
var d_offset: Depth = 0;
var states = pool.nodes.items(.state);
var lefts = pool.nodes.items(.left);
var rights = pool.nodes.items(.right);
// For each index specified, maintain/update path_lefts and path_rights from root (depth 0) all the way to path_len
// but only allocate and update path_parents from the next shared depth to path_len
for (0..indices.len) |i| {
// Calculate the gindex bits for the current index
const index = indices[i];
const gindex: Gindex = @enumFromInt(@as(Gindex.Uint, @intCast(@intFromEnum(base_gindex) | index)));
// Calculate the depth offset to navigate from current index to the next
const next_d_offset = if (i == indices.len - 1)
// 0 because there is no next index, it also means node_id is now the new root
0
else
path_len - @as(Depth, @intCast(@bitSizeOf(usize) - @clz(index ^ indices[i + 1])));
if (try pool.alloc(path_parents[next_d_offset..path_len])) {
states = pool.nodes.items(.state);
lefts = pool.nodes.items(.left);
rights = pool.nodes.items(.right);
}
var path = gindex.toPath();
// Navigate down (to the depth offset), attaching any new updates
// d_offset is the shared depth between the previous and current index so we can reuse path_lefts and path_rights up that point
// but update them to the path_parents to rebind starting from next_d_offset if needed
if (d_offset > next_d_offset) {
path.nextN(next_d_offset);
for (next_d_offset..d_offset) |bit_i| {
if (path.left()) {
path_lefts[bit_i] = path_parents[bit_i + 1];
right_move[bit_i] = false;
// move left, unfinalized
unfinalized_parents_buf[bit_i] = path_parents[bit_i];
} else {
path_rights[bit_i] = path_parents[bit_i + 1];
right_move[bit_i] = true;
}
path.next();
}
} else {
path.nextN(d_offset);
}
// right move at d_offset, make all unfinalized parents at lower levels as finalized
if (path.right()) {
for (d_offset + 1..path_len) |bit_i| {
unfinalized_parents_buf[bit_i] = null;
}
}
// Navigate down (from the depth offset) to the current index, populating parents
for (d_offset..path_len - 1) |bit_i| {
if (node_id.noChild(states[@intFromEnum(node_id)])) {
return Error.InvalidNode;
}
if (path.left()) {
path_lefts[bit_i] = path_parents[bit_i + 1];
path_rights[bit_i] = rights[@intFromEnum(node_id)];
node_id = lefts[@intFromEnum(node_id)];
right_move[bit_i] = false;
unfinalized_parents_buf[bit_i] = path_parents[bit_i];
} else {
path_lefts[bit_i] = lefts[@intFromEnum(node_id)];
path_rights[bit_i] = path_parents[bit_i + 1];
node_id = rights[@intFromEnum(node_id)];
right_move[bit_i] = true;
}
path.next();
}
// final layer
if (node_id.noChild(states[@intFromEnum(node_id)])) {
return Error.InvalidNode;
}
if (path.left()) {
path_lefts[path_len - 1] = nodes[i];
path_rights[path_len - 1] = rights[@intFromEnum(node_id)];
right_move[path_len - 1] = false;
unfinalized_parents_buf[path_len - 1] = path_parents[path_len - 1];
} else {
path_lefts[path_len - 1] = lefts[@intFromEnum(node_id)];
path_rights[path_len - 1] = nodes[i];
right_move[path_len - 1] = true;
}
// Rebind upwards depth diff times
try pool.rebind(
path_parents[next_d_offset..path_len],
path_lefts[next_d_offset..path_len],
path_rights[next_d_offset..path_len],
);
// unref prev parents if it's not part of the new tree
// can only unref after the rebind
for (next_d_offset..path_len) |bit_i| {
if (right_move[bit_i] and unfinalized_parents_buf[bit_i] != null) {
pool.unref(unfinalized_parents_buf[bit_i].?);
unfinalized_parents_buf[bit_i] = null;
}
}
node_id = path_parents[next_d_offset];
d_offset = next_d_offset;
}
return node_id;
}
/// Zeroes every node strictly to the right of `index` at the provided `depth`.
pub fn truncateAfterIndex(root_node: Id, pool: *Pool, depth: Depth, index: usize) Error!Id {
if (depth == 0) {
return root_node;
}
const max_length = @as(Gindex.Uint, 1) << depth;
if (index >= max_length - 1) {
if (index >= max_length) {
return Error.InvalidLength;
}
return root_node;
}
const path_len = @as(usize, depth);
var path_lefts_buf: [max_depth]Id = undefined;
var path_rights_buf: [max_depth]Id = undefined;
var path_parents_buf: [max_depth]Id = undefined;
const path_lefts = path_lefts_buf[0..path_len];
const path_rights = path_rights_buf[0..path_len];
const path_parents = path_parents_buf[0..path_len];
_ = try pool.alloc(path_parents);
errdefer pool.free(path_parents);
const states = pool.nodes.items(.state);
const lefts = pool.nodes.items(.left);
const rights = pool.nodes.items(.right);
var node_id = root_node;
for (0..path_len - 1) |i| {
if (node_id.noChild(states[@intFromEnum(node_id)])) {
return Error.InvalidNode;
}
const depthi = path_len - i - 1;
const go_left = isLeftIndex(depthi, index);
if (go_left) {
path_lefts[i] = path_parents[i + 1];
const zero_depth: Depth = @intCast(depthi);
path_rights[i] = @enumFromInt(zero_depth);
node_id = lefts[@intFromEnum(node_id)];
} else {
path_lefts[i] = lefts[@intFromEnum(node_id)];
path_rights[i] = path_parents[i + 1];
node_id = rights[@intFromEnum(node_id)];
}
}
if (node_id.noChild(states[@intFromEnum(node_id)])) {
return Error.InvalidNode;
}
const go_left_last = isLeftIndex(0, index);
if (go_left_last) {
path_lefts[path_len - 1] = lefts[@intFromEnum(node_id)];
path_rights[path_len - 1] = @enumFromInt(0);
} else {
path_lefts[path_len - 1] = lefts[@intFromEnum(node_id)];
path_rights[path_len - 1] = rights[@intFromEnum(node_id)];
}
try pool.rebind(path_parents, path_lefts, path_rights);
return path_parents[0];
}
inline fn isLeftIndex(depthi: usize, index: usize) bool {
const mask: usize = @as(usize, 1) << @intCast(depthi);
return (index & mask) == 0;
}
/// Set multiple nodes in batch, editing and traversing nodes strictly once.
/// - gindexes MUST be sorted in ascending order beforehand.
pub fn setNodes(root_node: Id, pool: *Pool, gindices: []const Gindex, nodes: []Id) Error!Id {
std.debug.assert(nodes.len == gindices.len);
if (gindices.len == 0) {
return root_node;
}
const base_gindex = gindices[0];
if (@intFromEnum(base_gindex) <= 1) {
return nodes[0];
}
const path_len = base_gindex.pathLen();
var path_parents_buf: [max_depth]Id = undefined;
// at each level, there is at most 1 unfinalized parent per traversal
// "unfinalized" means it may or may not be part of the new tree
var unfinalized_parents_buf: [max_depth]?Id = undefined;
var path_lefts_buf: [max_depth]Id = undefined;
var path_rights_buf: [max_depth]Id = undefined;
// right_move means it's part of the new tree, it happens when we traverse right
var right_move: [max_depth]bool = undefined;
var node_id = root_node;
errdefer {
// at any points, node_id is the root of the in-progress new tree
if (node_id != root_node) pool.unref(node_id);
// orphaned nodes were unrefed along the way through unfinalized_parents_buf
// path_parents_buf may or maynot be part of the in-progress new tree, there is no issue to double unref()
pool.free(&path_parents_buf);
}
// The shared depth between the previous and current index
// This is initialized as 0 since the first index has no previous index
var d_offset: Depth = 0;
var states = pool.nodes.items(.state);
var lefts = pool.nodes.items(.left);
var rights = pool.nodes.items(.right);
// For each index specified, maintain/update path_lefts and path_rights from root (depth 0) all the way to path_len
// but only allocate and update path_parents from the next shared depth to path_len
for (0..gindices.len) |i| {
// Calculate the gindex bits for the current index
const gindex = gindices[i];
// Calculate the depth offset to navigate from current index to the next
const next_d_offset = if (i == gindices.len - 1)
// 0 because there is no next gindex, it also means node_id is now the new root
0
else
path_len - @as(Depth, @intCast(@bitSizeOf(usize) - @clz(@intFromEnum(gindex) ^ @intFromEnum(gindices[i + 1]))));
if (try pool.alloc(path_parents_buf[next_d_offset..path_len])) {
states = pool.nodes.items(.state);
lefts = pool.nodes.items(.left);
rights = pool.nodes.items(.right);
}
var path = gindex.toPath();
// Navigate down (to the depth offset), attaching any new updates
// d_offset is the shared depth between the previous and current index so we can reuse path_lefts and path_rights up that point
// but update them to the path_parents to rebind starting from next_d_offset if needed
if (d_offset > next_d_offset) {
path.nextN(next_d_offset);
for (next_d_offset..d_offset) |bit_i| {
if (path.left()) {
path_lefts_buf[bit_i] = path_parents_buf[bit_i + 1];
right_move[bit_i] = false;
// move left, unfinalized
unfinalized_parents_buf[bit_i] = path_parents_buf[bit_i];