nickel-lang-vector 0.2.0

Persistent vectors for Nickel
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
//! [`Vector`] is a persistent vector (also known as a "bitmapped vector trie").
//!
//! Most of the operations on `Vector` have similar asymptotic (but
//! with a slower constant-factor) run-time to the same operations on the
//! standard-library `Vec`. For example, you can quickly push an element to
//! the back, or pop one from the back; random-access indexing is also fast.
//! On the other hand, pushing/popping from the front or insertion/deletion in
//! the middle are both slow. (Actually, we haven't even implemented these slow
//! operations because we don't need them.)
//!
//! The main advantage that [`Vector`] has over [`std::vec::Vec`] is *persistence*:
//! you can cheaply clone a `Vector` and then modify the clone. The clone and the
//! original will share most of their storage.
//!
//! There's a good explanation of the data structure
//! [here](https://hypirion.com/musings/understanding-persistent-vector-pt-1).
//! Very briefly, a vector is stored as a tree with a fixed branching factor, where
//! all leaves are the same distance from the root.
//! Unlike most tree data-structures, it isn't balanced. Instead, it's "packed left"
//! as much as possible.
//!
//! Persistence is achieved by cloning the path leading down
//! to the node you want to modify: say you want to push a new element, and the're
//! room for it in the right-most leaf. Then you clone the right-most leaf and
//! add your new element. Then you clone the leaf's parent and populate it with
//! pointers to the leaf's (unmodified) siblings, plus the leaf's new clone. Then
//! you clone the leaf's grandparent and populate it with pointers to the leaf's
//! (unmodified) uncles, plus the leaf's parent's new clone. You continue up the
//! tree like this, and you end up with a tree where the path from the leaf to
//! the root is new but everything else is shared with the previous version of
//! the vector.
//!
//! In this implementation, the pointers in the tree are `Rc` pointers, and we
//! use `Rc::make_mut` to clone-on-write: when a tree node is only present in
//! the tree that we're modifying, the clones in the description above
//! are replaced by direct modification.
//!
//! ## Branching factor `N`.
//!
//! `Vector` stores its data in a tree, and you get to choose the branching factor
//! `N`. It must be a power of 2 between 2 and 128 (inclusive), and something like
//! 32 seems to be reasonable. There is a trade-off involved, of course. Large
//! values of `N` make traditional array operations -- like random access, pushing,
//! and popping -- fast because the tree becomes very flat. On the other hand, the
//! copy-on-write operations suffer when `N` is large because blocks of size `N`
//! are the smallest units of shareable data.
//!
//! For example, if `N` is 128 and you have a vector of less than 128 entries,
//! it will be stored in a single flat array of capacity 128. If you then clone
//! the `Vector` and modify the clone, the whole length-128 array will be
//! cloned. If the vector is stored as a taller tree, only the blocks on the
//! path from the root to the modified entry will be duplicated. That is, modifying
//! an entry in a `Vector` of length `n` and branching factor `N` has
//! cost `O(N * log_N n)`.
//!
//! ## Comparison to `rpds`
//!
//! The same structure is implemented in [rpds](https://crates.io/crates/rpds),
//! but our implementation is faster for Nickel's use-cases:
//! - rpds's internal nodes are implemented with `Vec`, meaning that there's a
//!   double pointer indirection. We store our internal nodes inline.
//! - rpds wraps its leaves in `Rc` pointers, but we are mainly interested in
//!   storing things that are already reference-counted under the hood. We store
//!   our leaves inline, and require that they be `Clone`.
//! - we have optimized implementations of `Extend`, and support fast iteration
//!   over subslices.
//! - we have better support for "consuming" operations, such as an
//!   implementation of `into_iter` that avoids cloning the data unless
//!   necessary for persistence.

use std::{iter::Peekable, ops::Index, rc::Rc};

use imbl_sized_chunks::Chunk;

use crate::{Const, ValidBranchingConstant};

// In principle we could decouple the size of the interior nodes from the size of the leaves.
// This might make sense when `T` is large, because the interior nodes are always pointer-sized.
type Interior<T, const N: usize> = Chunk<Rc<Node<T, N>>, N>;
type ChunkIter<T, const N: usize> = imbl_sized_chunks::sized_chunk::Iter<T, N>;
type InteriorChunkIter<T, const N: usize> = ChunkIter<Rc<Node<T, N>>, N>;

// Can we improve the memory layout? We like N to be a power of 2 for
// performance (because it allows adjusting the indices using just bitwise
// operations), but it would also be cool if the total size of the node were a
// nice round number (so it would exactly fit in a small integer number of cache
// lines). The discriminant makes it hard to have both of these at once.
// Since we always know (based on the tree height) which type we *expect* a node
// to have, we could use a `union` instead of an `enum` (at the cost of lots of
// unsafe code).
//
// `N` must be a power of 2; this is important for efficiency because it allows
// the use of bitwise operations for a lot of things. I tried allowing `N` to
// be arbitrary, hoping that the compiler would be smart enough to do the fast
// thing when `N` is a power of 2. It wasn't.
//
// It would be nice to encode the power-of-2 restriction more efficiently (for
// example, by parametrizing with `B` and setting `N = 1 << B`). This sort of
// needs the `generic_const_exprs` feature to work, though.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum Node<T, const N: usize> {
    Leaf { data: Chunk<T, N> },
    Interior { children: Interior<T, N> },
}

/// `idx` is the global index into the root node, and we are some
/// possibly-intermediate node at height `height` (where the leaf is at height
/// zero). Which of our children does the global index belong to?
fn extract_index<const N: usize>(idx: usize, height: u8) -> usize {
    let shifted: usize = idx >> (N.ilog2() * u32::from(height));
    shifted & (N - 1)
}

impl<T: Clone, const N: usize> Node<T, N>
where
    Const<N>: ValidBranchingConstant,
{
    /// An inefficient but correct (and simple) method for computing the length
    /// of this subtree. We cache the length in the top-level vector, so this is
    /// only used for sanity-checks.
    fn len(&self) -> usize {
        match self {
            Node::Leaf { data } => data.len(),
            Node::Interior { children } => {
                // This could be faster if we used the tree height to compute
                // the size of the packed part of the tree. But this function is
                // only used for checking invariants, so speed isn't important.
                children.iter().map(|c| c.len()).sum()
            }
        }
    }

    /// If this node is at height `height`, try to get the element at the given
    /// index.
    fn get(&self, height: u8, idx: usize) -> Option<&T> {
        match self {
            Node::Leaf { data } => {
                debug_assert_eq!(height, 0);
                data.get(idx & (N - 1))
            }
            Node::Interior { children } => {
                let bucket_idx = extract_index::<N>(idx, height);
                children
                    .get(bucket_idx)
                    .and_then(|child| child.get(height - 1, idx))
            }
        }
    }

    /// Set the element at the given index.
    ///
    /// The index is allowed to point to the uninitialized slot just past the
    /// end of the initialized part, but it must point to a valid index within
    /// this node (i.e. if this node is full then it can't point past the end).
    ///
    /// Panics if the index is invalid.
    fn set(&mut self, height: u8, idx: usize, elt: T) {
        match self {
            Node::Leaf { data } => {
                let idx = idx & (N - 1);
                debug_assert_eq!(height, 0);
                debug_assert!(idx <= data.len());
                if idx < data.len() {
                    data.set(idx, elt);
                } else {
                    data.push_back(elt);
                }
            }
            Node::Interior { children } => {
                let bucket_idx = extract_index::<N>(idx, height);
                assert!(height >= 1);
                assert!(bucket_idx <= children.len());
                if bucket_idx < children.len() {
                    Rc::make_mut(&mut children[bucket_idx]).set(height - 1, idx, elt);
                } else {
                    let mut leaf = Chunk::new();
                    leaf.push_back(elt);

                    let mut child = Node::Leaf { data: leaf };
                    for _ in 1..height {
                        let mut children = Chunk::new();
                        children.push_back(Rc::new(child));
                        child = Node::Interior { children };
                    }
                    children.push_back(Rc::new(child));
                }
            }
        }
    }

    /// Deletes and returns the last element of this subtree (which is assumed to be non-empty).
    ///
    /// Returns true if popping made this subtree empty.
    fn pop(&mut self) -> (T, bool) {
        match self {
            Node::Leaf { data } => {
                debug_assert!(!data.is_empty());
                let ret = data.pop_back();
                (ret, data.is_empty())
            }
            Node::Interior { children } => {
                let (ret, child_empty) =
                    Rc::make_mut(children.last_mut().expect("empty interior node")).pop();
                if child_empty {
                    children.pop_back();
                }
                (ret, children.is_empty())
            }
        }
    }

    /// Shrinks the length of this subtree to `len`.
    ///
    /// Assumes that the length is less than this node's current length.
    fn truncate(&mut self, height: u8, len: usize) {
        match self {
            Node::Leaf { data } => {
                debug_assert!(height == 0);
                data.drop_right(len);
            }
            Node::Interior { children } => {
                // If `len` is small enough, we may just want to drop some children
                // and their entire subtrees.
                let max_child_len = N.pow(u32::from(height));
                let num_full_children = len / max_child_len;
                let extra = len % max_child_len;
                if extra > 0 {
                    children.drop_right(num_full_children + 1);
                    Rc::make_mut(&mut children[num_full_children]).truncate(height - 1, extra);
                } else {
                    children.drop_right(num_full_children);
                }
            }
        }
    }
}

/// A persistent vector.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Vector<T, const N: usize>
where
    Const<N>: ValidBranchingConstant,
{
    root: Option<Rc<Node<T, N>>>,
    length: usize,
    // TODO: could save some space by taking 8 bits out of length
    height: u8,
}

/// A borrowed iterator over a [`Vector`].
#[derive(Debug, Clone)]
pub struct Iter<'a, T, const N: usize>
where
    Const<N>: ValidBranchingConstant,
{
    stack: Vec<std::slice::Iter<'a, Rc<Node<T, N>>>>,
    leaf: std::slice::Iter<'a, T>,
}

impl<'a, T, const N: usize> Iterator for Iter<'a, T, N>
where
    Const<N>: ValidBranchingConstant,
{
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(ret) = self.leaf.next() {
            Some(ret)
        } else {
            let height = self.stack.len();
            let mut next = loop {
                match self.stack.last_mut() {
                    Some(iter) => {
                        if let Some(next) = iter.next() {
                            break next;
                        } else {
                            self.stack.pop();
                        }
                    }
                    None => {
                        return None;
                    }
                }
            };

            let cur_len = self.stack.len();
            for _ in cur_len..height {
                let Node::Interior { children } = next.as_ref() else {
                    unreachable!();
                };
                let mut children_iter = children.iter();
                next = children_iter.next().expect("empty interior node");
                self.stack.push(children_iter);
            }

            let Node::Leaf { data } = next.as_ref() else {
                unreachable!();
            };
            debug_assert!(!data.is_empty());
            self.leaf = data.iter();
            self.leaf.next()
        }
    }
}

/// A mutable iterator over a [`Vector`].
#[derive(Debug)]
pub struct IterMut<'a, T, const N: usize>
where
    Const<N>: ValidBranchingConstant,
{
    stack: Vec<std::slice::IterMut<'a, Rc<Node<T, N>>>>,
    leaf: std::slice::IterMut<'a, T>,
}

impl<'a, T, const N: usize> Iterator for IterMut<'a, T, N>
where
    Const<N>: ValidBranchingConstant,
    T: Clone,
{
    type Item = &'a mut T;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(ret) = self.leaf.next() {
            Some(ret)
        } else {
            let height = self.stack.len();
            let mut next = loop {
                match self.stack.last_mut() {
                    Some(iter) => {
                        if let Some(next) = iter.next() {
                            break next;
                        } else {
                            self.stack.pop();
                        }
                    }
                    None => {
                        return None;
                    }
                }
            };

            let cur_len = self.stack.len();
            for _ in cur_len..height {
                let Node::Interior { children } = Rc::make_mut(next) else {
                    unreachable!();
                };
                let mut children_iter = children.iter_mut();
                next = children_iter.next().expect("empty interior node");
                self.stack.push(children_iter);
            }

            let Node::Leaf { data } = Rc::make_mut(next) else {
                unreachable!();
            };
            debug_assert!(!data.is_empty());
            self.leaf = data.iter_mut();
            self.leaf.next()
        }
    }
}

/// An owned iterator over a [`Vector`].
//
// `IntoIter` and `Iter` share a bunch of almost-identical code, and if we
// ever want an `IterMut` then it will also be similar. I tried to make a
// common implementation by defining something like
//
// ```rust
// struct GenericIter<InteriorIter, LeafIter>
// where InteriorIter: Iterator<Item = Either<InteriorIter, LeafIter>>,
// {
//     stack: Vec<InteriorIter>,
//     leaf: LeafIter,
// }
// ```
//
// but it came with a massive 500% performance penalty. I didn't look carefully
// into why.
pub struct IntoIter<T, const N: usize> {
    stack: Vec<InteriorChunkIter<T, N>>,
    leaf: ChunkIter<T, N>,
}

impl<T: Clone, const N: usize> Iterator for IntoIter<T, N> {
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(ret) = self.leaf.next() {
            Some(ret)
        } else {
            let height = self.stack.len();
            let mut next = loop {
                match self.stack.last_mut() {
                    Some(iter) => {
                        if let Some(next) = iter.next() {
                            break next;
                        } else {
                            self.stack.pop();
                        }
                    }
                    None => {
                        return None;
                    }
                }
            };

            let cur_len = self.stack.len();
            for _ in cur_len..height {
                let Node::Interior { children } = Rc::unwrap_or_clone(next) else {
                    unreachable!();
                };
                let mut children_iter = children.into_iter();
                next = children_iter.next().expect("empty interior node");
                self.stack.push(children_iter);
            }

            let Node::Leaf { data } = Rc::unwrap_or_clone(next) else {
                unreachable!();
            };
            debug_assert!(!data.is_empty());
            self.leaf = data.into_iter();
            self.leaf.next()
        }
    }
}

impl<T: Clone, const N: usize> Extend<T> for Vector<T, N>
where
    Const<N>: ValidBranchingConstant,
{
    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
        // Make the iterator peekable, because we need to check if there's an
        // element remaining before we mutate the tree to make room for it.
        let mut iter = iter.into_iter().peekable();

        // Extends a node from an iterator, but does not increase the height of
        // the node. If the node fills up, the iterator may not be fully consumed.
        //
        // Returns the number of elements consumed from the iterator.
        fn extend_rec<T: Clone, I: Iterator<Item = T>, const N: usize>(
            iter: &mut Peekable<I>,
            node: &mut Interior<T, N>,
            height: u8,
        ) -> usize {
            debug_assert!(height >= 1);
            let mut consumed = 0;

            if height == 1 {
                // If there's a leaf that isn't filled, fill it.
                if let Some(last_child) = node.last_mut() {
                    // Usually, we assert that there's a last child because the
                    // interior nodes are guaranteed to be non-empty. But within
                    // this function we sometimes create empty interior nodes to
                    // be filled later.
                    // TODO: can avoid the clone if it's already full
                    let Node::Leaf { data } = Rc::make_mut(last_child) else {
                        unreachable!();
                    };
                    let old_len = data.len();
                    data.extend(iter.take(N - data.len()));
                    consumed += data.len() - old_len;
                }

                while !node.is_full() && iter.peek().is_some() {
                    let data: Chunk<T, N> = iter.take(N).collect();
                    consumed += data.len();
                    node.push_back(Rc::new(Node::Leaf { data }));
                }
            } else {
                if let Some(child) = node.last_mut() {
                    let Node::Interior { children } = Rc::make_mut(child) else {
                        unreachable!();
                    };

                    consumed += extend_rec(iter, children, height - 1);
                }

                while !node.is_full() && iter.peek().is_some() {
                    let mut new_child: Interior<T, N> = Chunk::new();
                    consumed += extend_rec(iter, &mut new_child, height - 1);
                    node.push_back(Rc::new(Node::Interior {
                        children: new_child,
                    }));
                }
            }

            consumed
        }

        if iter.peek().is_some() && self.root.is_none() {
            self.root = Some(Rc::new(Node::Leaf {
                data: Chunk::default(),
            }));
        }
        while iter.peek().is_some() {
            // Unwrap: we ensured that if the iterator has anything, the root is present.
            let consumed = match Rc::make_mut(self.root.as_mut().unwrap()) {
                Node::Leaf { data } => {
                    let old_len = data.len();
                    data.extend((&mut iter).take(N - data.len()));
                    data.len() - old_len
                }
                Node::Interior { children } => extend_rec(&mut iter, children, self.height),
            };
            self.length += consumed;

            // Check if there's more left in the iterator, and add a level if there is.
            if iter.peek().is_some() {
                self.add_level();
            }
        }
    }
}

fn height_for_length<const N: usize>(length: usize) -> u8 {
    // Length zero through N has height zero, length N + 1 through N^2 has height 1, etc.
    // The unwrap is fine unless someone has a usize that's more than 256 bits.
    length.saturating_sub(1).max(1).ilog(N).try_into().unwrap()
}

impl<T, const N: usize> Vector<T, N>
where
    Const<N>: ValidBranchingConstant,
{
    /// Create a new, empty, vector.
    pub fn new() -> Self {
        Self {
            root: None,
            length: 0,
            height: 0,
        }
    }

    /// The number of elements in this vector.
    pub fn len(&self) -> usize {
        self.length
    }

    /// Returns `true` if the length is zero.
    pub fn is_empty(&self) -> bool {
        self.length == 0
    }
}

impl<T: Clone, const N: usize> Vector<T, N>
where
    Const<N>: ValidBranchingConstant,
{
    // Vectors must always be "packed to the left": every child that isn't the
    // right-most child of its parent must have a complete subtree.
    //
    // This function checks that invariant. It's only used in tests.
    fn is_packed(&self) -> bool {
        fn is_packed_rec<T: Clone, const N: usize>(n: &Node<T, N>, right_most: bool) -> bool {
            match n {
                Node::Leaf { data } => data.is_full() || right_most,
                Node::Interior { children } => {
                    if let Some((tail, others)) = children.split_last() {
                        others.iter().all(|n| is_packed_rec(n, false)) && is_packed_rec(tail, true)
                    } else {
                        debug_assert!(false, "empty node");
                        false
                    }
                }
            }
        }

        match &self.root {
            None => true,
            Some(root) => is_packed_rec(root, true),
        }
    }

    /// Checks our internal invariants.
    ///
    /// It's public so that it can be used in out-of-crate tests.
    #[doc(hidden)]
    pub fn check_invariants(&self) {
        assert!(self.is_packed());
        assert_eq!(self.length, self.root.as_ref().map_or(0, |root| root.len()));
        if let Some(root) = self.root.as_ref()
            && let Node::Interior { children } = root.as_ref()
        {
            assert!(children.len() > 1);
        }
        assert_eq!(self.height, height_for_length::<N>(self.len()));
    }

    // Is this vector as full as it can be without increasing the height?
    fn is_full(&self) -> bool {
        self.root.is_none() || self.length == N.pow(u32::from(self.height) + 1)
    }

    /// Gets an element at a given index, or `None` if `idx` is out-of-bounds.
    pub fn get(&self, idx: usize) -> Option<&T> {
        self.root.as_ref().and_then(|r| r.get(self.height, idx))
    }

    /// Sets an element at a given index.
    ///
    /// Panics if the index is out of bounds.
    pub fn set(&mut self, idx: usize, elt: T) {
        if idx >= self.length {
            panic!("index {idx} out of bounds, length is {}", self.length);
        }

        if let Some(root) = self.root.as_mut() {
            Rc::make_mut(root).set(self.height, idx, elt);
        }
    }

    // Increases the height of the tree by one, temporarily breaking the invariant that
    // the root must have at least two children.
    fn add_level(&mut self) {
        match &mut self.root {
            None => {
                // We don't increment height in this case: height zero is used for both
                // the empty vector and a vector with just one leaf.
                // (Maybe we should use height 1 in the latter case?)
                self.root = Some(Rc::new(Node::Leaf { data: Chunk::new() }));
            }
            Some(root) => {
                let old_root = std::mem::replace(
                    root,
                    Rc::new(Node::Interior {
                        children: Chunk::new(),
                    }),
                );

                // TODO: maybe we can avoid the make_mut and the fallible destructuring?
                // It seems a little tricky to do so without increasing some ref-counts.
                let Node::Interior { children } = Rc::make_mut(root) else {
                    unreachable!();
                };
                children.push_back(old_root);
                self.height += 1;
            }
        }
    }

    /// Adds an element to the end of this array.
    ///
    /// Runs in time complexity `O(log n)` where `n` is the array length.
    pub fn push(&mut self, elt: T) {
        if self.is_full() {
            self.add_level();
        }
        let idx = self.len();
        // unwrap: self.add_level ensures that the root is non-empty
        Rc::make_mut(self.root.as_mut().unwrap()).set(self.height, idx, elt);
        self.length += 1;
    }

    /// Removes and returns the element at the end of this array, or
    /// `None` if we're empty.
    ///
    /// Runs in time complexity `O(log self.len())`.
    pub fn pop(&mut self) -> Option<T> {
        if self.is_empty() {
            None
        } else {
            // Unwrap: if we aren't empty, we have a root.
            let root_mut = Rc::make_mut(self.root.as_mut().unwrap());
            let (ret, _empty) = root_mut.pop();
            self.length -= 1;

            // If we've shrunk the root down to a single child, reduce the tree height by 1.
            if let Node::Interior { children } = root_mut
                && children.len() == 1
            {
                self.root = Some(children.pop_back());
                self.height -= 1;
            }
            Some(ret)
        }
    }

    /// If `len` is less than our length, shortens this vector to length `len`.
    ///
    /// If `len` is greater than or equal to our length, does nothing.
    ///
    /// The running time is `O(log self.len() + (len - self.len()))`. That
    /// is, it is linear in the number of elements to be discarded. Even if
    /// the elements to be discarded have trivial destructors, we still need
    /// to destroy (and potentially de-allocate) a linear number of internal
    /// nodes. However, the constant factor in this linear term should be quite
    /// small; you can expect that `truncate` is much faster than multiple calls
    /// to `pop`.
    pub fn truncate(&mut self, len: usize) {
        if len >= self.length {
            return;
        }

        let new_height = height_for_length::<N>(len);
        if new_height < self.height {
            // unwrap: if we were empty, we would have returned at the `len >= self.length` check.
            let mut new_root = self.root.as_ref().unwrap();
            for _ in new_height..self.height {
                let Node::Interior { children } = new_root.as_ref() else {
                    unreachable!();
                };
                new_root = children.first().expect("empty interior node");
            }
            self.root = Some(Rc::clone(new_root));
            self.height = new_height;
        }

        // unwrap: if we were empty, we would have returned at the `len >= self.length` check.
        Rc::make_mut(self.root.as_mut().unwrap()).truncate(self.height, len);

        self.length = len;
    }

    /// Returns an iterator over all elements in this vector.
    ///
    /// Iterator construction runs in `O(log self.len())` time. Each step
    /// of the iteration runs in amortized constant time, worst-case `O(log
    /// self.len())` time.
    pub fn iter(&self) -> Iter<'_, T, N> {
        self.into_iter()
    }

    /// Returns a mutable iterator over all elements in this vector.
    ///
    /// Iterator construction runs in `O(log self.len())` time. Each step
    /// of the iteration runs in amortized constant time, worst-case `O(log
    /// self.len())` time.
    pub fn iter_mut(&mut self) -> IterMut<'_, T, N> {
        self.into_iter()
    }

    /// Returns an iterator over borrowed elements in this vector, starting at a
    /// specific index.
    ///
    /// Iterator construction runs in `O(log self.len())` time. Each step
    /// of the iteration runs in amortized constant time, worst-case
    /// `O(log self.len())` time. In particular, if `idx` is large then this is
    /// much more efficient than calling `iter` and then advancing past `idx`
    /// elements.
    pub fn iter_starting_at(&self, idx: usize) -> Iter<'_, T, N> {
        if idx == self.len() {
            return Iter {
                stack: Vec::new(),
                leaf: [].iter(),
            };
        }
        if idx > self.len() {
            panic!("out of bounds");
        }

        let mut stack = Vec::with_capacity(self.height.into());
        // unwrap: if we got past the initial tests on `idx`, we must be non-empty
        // and so we have a root
        let mut node = self.root.as_ref().unwrap().as_ref();
        let mut height = self.height;

        while let Node::Interior { children } = node {
            let bucket_idx = extract_index::<N>(idx, height);
            let mut node_iter = children[bucket_idx..].iter();

            // expect: we've checked that `idx` is strictly less than the length,
            // so this interior iterator should be non-empty also.
            node = node_iter.next().expect("empty interior node");
            stack.push(node_iter);

            height = height.checked_sub(1).expect("invalid height");
        }

        let Node::Leaf { data } = node else {
            unreachable!();
        };
        Iter {
            stack,
            leaf: data[(idx & (N - 1))..].iter(),
        }
    }

    /// Returns an iterator over mutable elements in this vector, starting at a
    /// specific index.
    ///
    /// Iterator construction runs in `O(log self.len())` time. Each step
    /// of the iteration runs in amortized constant time, worst-case
    /// `O(log self.len())` time. In particular, if `idx` is large then this is
    /// much more efficient than calling `iter` and then advancing past `idx`
    /// elements.
    pub fn iter_mut_starting_at(&mut self, idx: usize) -> IterMut<'_, T, N> {
        if idx == self.len() {
            return IterMut {
                stack: Vec::new(),
                leaf: [].iter_mut(),
            };
        }
        if idx > self.len() {
            panic!("out of bounds");
        }

        let mut stack = Vec::with_capacity(self.height.into());
        // unwrap: if we got past the initial tests on `idx`, we must be non-empty
        // and so we have a root
        let mut node = self.root.as_mut().unwrap();
        let mut height = self.height;

        while let Node::Interior { .. } = node.as_ref() {
            let Node::Interior { children } = Rc::make_mut(node) else {
                unreachable!("but we just checked it");
            };

            let bucket_idx = extract_index::<N>(idx, height);
            let mut node_iter = children[bucket_idx..].iter_mut();

            // expect: we've checked that `idx` is strictly less than the length,
            // so this interior iterator should be non-empty also.
            node = node_iter.next().expect("empty interior node");
            stack.push(node_iter);

            height = height.checked_sub(1).expect("invalid height");
        }

        let Node::Leaf { data } = Rc::make_mut(node) else {
            unreachable!();
        };
        IterMut {
            stack,
            leaf: data[(idx & (N - 1))..].iter_mut(),
        }
    }

    /// Returns an iterator over borrowed elements in this vector, starting at a
    /// specific index.
    ///
    /// Iterator construction runs in `O(log self.len() + idx)` time. Each step
    /// of the iteration runs in amortized constant time, worst-case
    /// `O(log self.len())` time. Unlike the borrowed `iter_starting_at`, this is
    /// not asymptotically faster than calling `into_iter` and then advancing
    /// past `idx` elements, because we need to destruct and then potentially
    /// de-allocate a linear (in `idx`) number of things. However, this method
    /// should be faster in practice than iterating over `idx` elements.
    pub fn into_iter_starting_at(self, mut idx: usize) -> IntoIter<T, N> {
        if idx == self.len() {
            return IntoIter {
                stack: Vec::new(),
                leaf: Chunk::new().into_iter(),
            };
        }
        if idx > self.len() {
            panic!("out of bounds");
        }

        let mut stack = Vec::with_capacity(self.height.into());
        // unwrap: if we got past the initial tests on `idx`, we must be non-empty
        // and so we have a root
        let mut node = Rc::unwrap_or_clone(self.root.unwrap());
        let mut height = self.height;

        while let Node::Interior { mut children } = node {
            let bucket_idx = extract_index::<N>(idx, height);
            children.drop_left(bucket_idx);
            let mut node_iter = children.into_iter();
            node = Rc::unwrap_or_clone(node_iter.next().expect("empty interior node"));
            stack.push(node_iter);

            height = height.checked_sub(1).expect("invalid height");
        }

        let Node::Leaf { mut data } = node else {
            unreachable!();
        };
        idx &= N - 1;
        data.drop_left(idx);
        IntoIter {
            stack,
            leaf: data.into_iter(),
        }
    }
}

impl<'a, T, const N: usize> IntoIterator for &'a Vector<T, N>
where
    Const<N>: ValidBranchingConstant,
{
    type Item = &'a T;
    type IntoIter = Iter<'a, T, N>;

    fn into_iter(self) -> Self::IntoIter {
        let mut stack = Vec::with_capacity(self.height.into());
        let Some(root) = &self.root else {
            return Iter {
                stack,
                leaf: [].iter(),
            };
        };

        let mut node = root.as_ref();
        while let Node::Interior { children } = node {
            let mut node_iter = children.iter();
            node = node_iter.next().expect("empty interior node");
            stack.push(node_iter);
        }

        let Node::Leaf { data } = node else {
            unreachable!();
        };
        Iter {
            stack,
            leaf: data.iter(),
        }
    }
}

impl<'a, T, const N: usize> IntoIterator for &'a mut Vector<T, N>
where
    Const<N>: ValidBranchingConstant,
    T: Clone,
{
    type Item = &'a mut T;
    type IntoIter = IterMut<'a, T, N>;

    fn into_iter(self) -> Self::IntoIter {
        let mut stack = Vec::with_capacity(self.height.into());
        let Some(root) = &mut self.root else {
            return IterMut {
                stack,
                leaf: [].iter_mut(),
            };
        };

        let mut node = root;
        while let Node::Interior { .. } = node.as_ref() {
            let Node::Interior { children } = Rc::make_mut(node) else {
                unreachable!("but we just checked it");
            };
            let mut node_iter = children.iter_mut();
            node = node_iter.next().expect("empty interior node");
            stack.push(node_iter);
        }

        let Node::Leaf { data } = Rc::make_mut(node) else {
            unreachable!();
        };
        IterMut {
            stack,
            leaf: data.iter_mut(),
        }
    }
}

impl<T: Clone, const N: usize> IntoIterator for Vector<T, N>
where
    Const<N>: ValidBranchingConstant,
{
    type Item = T;
    type IntoIter = IntoIter<T, N>;

    fn into_iter(self) -> Self::IntoIter {
        let mut stack = Vec::with_capacity(self.height.into());
        let Some(root) = self.root else {
            return IntoIter {
                stack,
                leaf: Chunk::new().into_iter(),
            };
        };

        let mut node = Rc::unwrap_or_clone(root);
        while let Node::Interior { children } = node {
            let mut node_iter = children.into_iter();
            node = Rc::unwrap_or_clone(node_iter.next().expect("empty interior node"));
            stack.push(node_iter);
        }

        let Node::Leaf { data } = node else {
            unreachable!();
        };
        IntoIter {
            stack,
            leaf: data.into_iter(),
        }
    }
}

impl<T, const N: usize> Default for Vector<T, N>
where
    Const<N>: ValidBranchingConstant,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<T: Clone, const N: usize> FromIterator<T> for Vector<T, N>
where
    Const<N>: ValidBranchingConstant,
{
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        let mut ret = Vector::default();
        ret.extend(iter);
        ret
    }
}

impl<T: Clone, const N: usize> Index<usize> for Vector<T, N>
where
    Const<N>: ValidBranchingConstant,
{
    type Output = T;

    fn index(&self, index: usize) -> &Self::Output {
        self.get(index).expect("index out of range")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn basic() {
        let mut vec = Vector::<u32, 2>::new();
        vec.check_invariants();
        vec.push(1);
        assert_eq!(vec.get(0), Some(&1));
        assert_eq!(vec.get(1), None);
        vec.check_invariants();

        vec.push(2);
        vec.check_invariants();
        vec.push(3);
        vec.check_invariants();
        assert_eq!(vec.get(0), Some(&1));
        assert_eq!(vec.get(1), Some(&2));
        assert_eq!(vec.get(2), Some(&3));
        assert_eq!(vec.get(3), None);

        let mut iter = vec.iter();
        assert_eq!(iter.next(), Some(&1));
        assert_eq!(iter.next(), Some(&2));
        assert_eq!(iter.next(), Some(&3));
        assert_eq!(iter.next(), None);

        assert_eq!(vec.iter().copied().collect::<Vec<_>>(), vec![1, 2, 3]);

        assert_eq!(vec.pop(), Some(3));
        vec.check_invariants();
        vec.push(3);
        vec.check_invariants();

        vec.extend([1, 2, 3]);
        vec.check_invariants();
        let mut iter = vec.iter();
        assert_eq!(iter.next(), Some(&1));
        assert_eq!(iter.next(), Some(&2));
        assert_eq!(iter.next(), Some(&3));
        assert_eq!(iter.next(), Some(&1));
        assert_eq!(iter.next(), Some(&2));
        assert_eq!(iter.next(), Some(&3));
        assert_eq!(iter.next(), None);

        assert_eq!(6, vec.len());
        assert_eq!(
            vec.iter().copied().collect::<Vec<_>>(),
            vec![1, 2, 3, 1, 2, 3]
        );
        assert_eq!(vec.into_iter().collect::<Vec<_>>(), vec![1, 2, 3, 1, 2, 3]);
    }
}