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
use std::{collections::VecDeque, ops::Range};

use itertools::Itertools as _;

use re_types_core::SizeBytes;

// ---

/// A [`FlatVecDeque`] that can be erased into a trait object.
///
/// Methods that don't require monomorphization over `T` are made dynamically dispatchable.
pub trait ErasedFlatVecDeque: std::any::Any {
    fn as_any(&self) -> &dyn std::any::Any;

    fn as_any_mut(&mut self) -> &mut dyn std::any::Any;

    fn into_any(self: Box<Self>) -> Box<dyn std::any::Any>;

    /// Dynamically dispatches to [`FlatVecDeque::clone`].
    ///
    /// This is prefixed with `dyn_` to avoid method dispatch ambiguities that are very hard to
    /// avoid even with explicit syntax and that silently lead to infinite recursions.
    fn dyn_clone(&self) -> Box<dyn ErasedFlatVecDeque + Send + Sync>;

    /// Dynamically dispatches to [`FlatVecDeque::num_entries`].
    ///
    /// This is prefixed with `dyn_` to avoid method dispatch ambiguities that are very hard to
    /// avoid even with explicit syntax and that silently lead to infinite recursions.
    fn dyn_num_entries(&self) -> usize;

    /// Dynamically dispatches to [`FlatVecDeque::num_values`].
    ///
    /// This is prefixed with `dyn_` to avoid method dispatch ambiguities that are very hard to
    /// avoid even with explicit syntax and that silently lead to infinite recursions.
    fn dyn_num_values(&self) -> usize;

    /// Dynamically dispatches to [`FlatVecDeque::remove`].
    ///
    /// This is prefixed with `dyn_` to avoid method dispatch ambiguities that are very hard to
    /// avoid even with explicit syntax and that silently lead to infinite recursions.
    fn dyn_remove(&mut self, at: usize);

    /// Dynamically dispatches to [`FlatVecDeque::remove`].
    ///
    /// This is prefixed with `dyn_` to avoid method dispatch ambiguities that are very hard to
    /// avoid even with explicit syntax and that silently lead to infinite recursions.
    fn dyn_remove_range(&mut self, range: Range<usize>);

    /// Dynamically dispatches to [`FlatVecDeque::truncate`].
    ///
    /// This is prefixed with `dyn_` to avoid method dispatch ambiguities that are very hard to
    /// avoid even with explicit syntax and that silently lead to infinite recursions.
    fn dyn_truncate(&mut self, at: usize);

    /// Dynamically dispatches to [`<FlatVecDeque<T> as SizeBytes>::total_size_bytes(self)`].
    ///
    /// This is prefixed with `dyn_` to avoid method dispatch ambiguities that are very hard to
    /// avoid even with explicit syntax and that silently lead to infinite recursions.
    fn dyn_total_size_bytes(&self) -> u64;
}

impl<T: SizeBytes + 'static> ErasedFlatVecDeque for FlatVecDeque<T>
where
    T: Send + Sync + Clone,
{
    #[inline]
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    #[inline]
    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }

    #[inline]
    fn dyn_clone(&self) -> Box<dyn ErasedFlatVecDeque + Send + Sync> {
        Box::new((*self).clone())
    }

    #[inline]
    fn into_any(self: Box<Self>) -> Box<dyn std::any::Any> {
        self
    }

    #[inline]
    fn dyn_num_entries(&self) -> usize {
        self.num_entries()
    }

    #[inline]
    fn dyn_num_values(&self) -> usize {
        self.num_values()
    }

    #[inline]
    fn dyn_remove(&mut self, at: usize) {
        FlatVecDeque::<T>::remove(self, at);
    }

    #[inline]
    fn dyn_remove_range(&mut self, range: Range<usize>) {
        FlatVecDeque::<T>::remove_range(self, range);
    }

    #[inline]
    fn dyn_truncate(&mut self, at: usize) {
        FlatVecDeque::<T>::truncate(self, at);
    }

    #[inline]
    fn dyn_total_size_bytes(&self) -> u64 {
        <FlatVecDeque<T> as SizeBytes>::total_size_bytes(self)
    }
}

// ---

/// A double-ended queue implemented with a pair of growable ring buffers, where every single
/// entry is a flattened array of values.
///
/// Logically like a `VecDeque<Box<[T]>>`, but with a less fragmented memory layout (each `Box<[T]>`
/// gets copied/inlined into the `FlatVecDeque`).
/// `FlatVecDeque` therefore optimizes for reads (cache locality, specifically) while `VecDeque<Box<[T]>>`
/// optimizes for writes.
///
/// You can think of this as the native/deserialized version of an Arrow `ListArray`.
/// This is particularly useful when working with many small arrays of data (e.g. Rerun's `Scalar`s).
//
// TODO(cmc): We could even use a bitmap for T=Option<Something>, which would bring this that much
// closer to a deserialized version of an Arrow array.
#[derive(Debug, Clone)]
pub struct FlatVecDeque<T> {
    /// Stores every value in the `FlatVecDeque` in a flattened `VecDeque`.
    ///
    /// E.g.:
    /// - `FlatVecDeque[]` -> values=`[]`.
    /// - `FlatVecDeque[[], [], []]` -> values=`[]`.
    /// - `FlatVecDeque[[], [0], [1, 2, 3], [4, 5]]` -> values=`[0, 1, 2, 3, 4, 5]`.
    values: VecDeque<T>,

    /// Keeps track of each entry, i.e. logical slices of data.
    ///
    /// E.g.:
    /// - `FlatVecDeque[]` -> offsets=`[]`.
    /// - `FlatVecDeque[[], [], []]` -> offsets=`[0, 0, 0]`.
    /// - `FlatVecDeque[[], [0], [1, 2, 3], [4, 5]]` -> offsets=`[0, 1, 4, 6]`.
    offsets: VecDeque<usize>,
}

impl<T: SizeBytes> SizeBytes for FlatVecDeque<T> {
    #[inline]
    fn heap_size_bytes(&self) -> u64 {
        // NOTE: It's all on the heap at this point.

        let values_size_bytes = if T::is_pod() {
            (self.num_values() * std::mem::size_of::<T>()) as _
        } else {
            self.values
                .iter()
                .map(SizeBytes::total_size_bytes)
                .sum::<u64>()
        };

        let offsets_size_bytes = self.num_entries() * std::mem::size_of::<usize>();

        values_size_bytes + offsets_size_bytes as u64
    }
}

impl<T> From<VecDeque<T>> for FlatVecDeque<T> {
    #[inline]
    fn from(values: VecDeque<T>) -> Self {
        let num_values = values.len();
        Self {
            values,
            offsets: std::iter::once(num_values).collect(),
        }
    }
}

impl<T> From<Vec<T>> for FlatVecDeque<T> {
    #[inline]
    fn from(values: Vec<T>) -> Self {
        let num_values = values.len();
        Self {
            values: values.into(),
            offsets: std::iter::once(num_values).collect(),
        }
    }
}

impl<T> Default for FlatVecDeque<T> {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl<T> FlatVecDeque<T> {
    #[inline]
    pub const fn new() -> Self {
        Self {
            values: VecDeque::new(),
            offsets: VecDeque::new(),
        }
    }

    #[inline]
    pub fn from_vecs(entries: impl IntoIterator<Item = Vec<T>>) -> Self {
        let mut this = Self::new();

        // NOTE: Do not use any of the insertion methods, they rely on `from_vecs` in the first
        // place!
        let mut value_offset = 0;
        for entry in entries {
            value_offset += entry.len(); // increment first!
            this.offsets.push_back(value_offset);
            this.values.extend(entry);
        }

        this
    }

    /// How many entries are there in the deque?
    ///
    /// Keep in mind: each entry is itself an array of values.
    /// Use [`Self::num_values`] to get the total number of values across all entries.
    #[inline]
    pub fn num_entries(&self) -> usize {
        self.offsets.len()
    }

    /// How many values are there in the deque?
    ///
    /// Keep in mind: each entry in the deque holds an array of values.
    /// Use [`Self::num_entries`] to get the total number of entries, irrelevant of how many
    /// values each entry holds.
    #[inline]
    pub fn num_values(&self) -> usize {
        self.values.len()
    }

    #[inline]
    fn value_offset(&self, entry_index: usize) -> usize {
        if entry_index == 0 {
            0
        } else {
            self.offsets[entry_index - 1]
        }
    }

    #[inline]
    fn iter_offset_ranges(&self) -> impl Iterator<Item = Range<usize>> + '_ {
        std::iter::once(0)
            .chain(self.offsets.iter().copied())
            .tuple_windows::<(_, _)>()
            .map(|(start, end)| (start..end))
    }
}

// ---

impl<T> FlatVecDeque<T> {
    /// Iterates over all the entries in the deque.
    ///
    /// This is the same as `self.range(0..self.num_entries())`.
    ///
    /// Keep in mind that each entry is an array of values!
    #[inline]
    pub fn iter(&self) -> impl Iterator<Item = &[T]> {
        self.range(0..self.num_entries())
    }

    /// Iterates over all the entries in the deque in the given `entry_range`.
    ///
    /// Keep in mind that each entry is an array of values!
    #[inline]
    pub fn range(&self, entry_range: Range<usize>) -> impl Iterator<Item = &[T]> {
        let (values_left, values_right) = self.values.as_slices();
        // NOTE: We can't slice into our offsets, we don't even know if they're contiguous in
        // memory at this point -> skip() and take().
        self.iter_offset_ranges()
            .skip(entry_range.start)
            .take(entry_range.len())
            .map(|offsets| {
                if offsets.is_empty() {
                    return &[] as &'_ [T];
                }

                // NOTE: We do not need `make_contiguous` here because we always guarantee
                // that a single entry's worth of values is fully contained in either the left or
                // right buffer, but never straddling across both.
                if offsets.start < values_left.len() {
                    &values_left[offsets]
                } else {
                    &values_right[offsets]
                }
            })
    }
}

#[test]
fn range() {
    let mut v: FlatVecDeque<i64> = FlatVecDeque::new();

    assert_eq!(0, v.num_entries());
    assert_eq!(0, v.num_values());

    v.insert_many(0, [vec![1, 2, 3], vec![4, 5, 6, 7], vec![8, 9, 10]]);
    assert_deque_eq(&[&[1, 2, 3], &[4, 5, 6, 7], &[8, 9, 10]], &v);

    assert_iter_eq(&[&[1, 2, 3]], v.range(0..1));
    assert_iter_eq(&[&[4, 5, 6, 7]], v.range(1..2));
    assert_iter_eq(&[&[8, 9, 10]], v.range(2..3));

    assert_iter_eq(
        &[&[1, 2, 3], &[4, 5, 6, 7], &[8, 9, 10]],
        v.range(0..v.num_entries()),
    );

    assert_iter_eq(&[&[1, 2, 3], &[4, 5, 6, 7], &[8, 9, 10]], v.iter());
}

// ---

impl<T> FlatVecDeque<T> {
    /// Prepends an entry comprised of `values` to the deque.
    ///
    /// This is the same as `self.insert(0, values)`.
    ///
    /// See [`Self::insert`] for more information.
    #[inline]
    pub fn push_front(&mut self, values: impl IntoIterator<Item = T>) {
        self.insert(0, values);
    }

    /// Appends an entry comprised of `values` to the deque.
    ///
    /// This is the same as `self.insert(self.num_entries(), values)`.
    ///
    /// See [`Self::insert`] for more information.
    #[inline]
    pub fn push_back(&mut self, values: impl IntoIterator<Item = T>) {
        self.insert(self.num_entries(), values);
    }

    /// Inserts a single entry at `entry_index`, comprised of the multiple elements given as `values`.
    ///
    /// This is O(1) if `entry_index` corresponds to either the start or the end of the deque.
    /// Otherwise, this requires splitting the deque into two pieces then stitching them back together
    /// at both ends of the added data.
    ///
    /// Panics if `entry_index` is out of bounds.
    /// Panics if `values` is empty.
    #[inline]
    pub fn insert(&mut self, entry_index: usize, values: impl IntoIterator<Item = T>) {
        let values: VecDeque<T> = values.into_iter().collect();
        let deque = values.into();
        self.insert_deque(entry_index, deque);
    }

    /// Prepends multiple entries, each comprised of the multiple elements given in `entries`,
    /// to the deque.
    ///
    /// This is the same as `self.insert_many(0, entries)`.
    ///
    /// See [`Self::insert_many`] for more information.
    #[inline]
    pub fn push_many_front(&mut self, entries: impl IntoIterator<Item = Vec<T>>) {
        self.insert_many(0, entries);
    }

    /// Appends multiple entries, each comprised of the multiple elements given in `entries`,
    /// to the deque.
    ///
    /// This is the same as `self.insert_many(self.num_entries(), entries)`.
    ///
    /// See [`Self::insert_many`] for more information.
    #[inline]
    pub fn push_many_back(&mut self, entries: impl IntoIterator<Item = Vec<T>>) {
        self.insert_many(self.num_entries(), entries);
    }

    /// Inserts multiple entries, starting at `entry_index` onwards, each comprised of the multiple elements
    /// given in `entries`.
    ///
    /// This is O(1) if `entry_index` corresponds to either the start or the end of the deque.
    /// Otherwise, this requires splitting the deque into two pieces then stitching them back together
    /// at both ends of the added data.
    ///
    /// Panics if `entry_index` is out of bounds.
    /// Panics if any of the value arrays in `entries` is empty.
    #[inline]
    pub fn insert_many(&mut self, entry_index: usize, entries: impl IntoIterator<Item = Vec<T>>) {
        let deque = Self::from_vecs(entries);
        self.insert_deque(entry_index, deque);
    }

    /// Prepends another full deque to the deque.
    ///
    /// This is the same as `self.insert_deque(0, rhs)`.
    ///
    /// See [`Self::insert_deque`] for more information.
    #[inline]
    pub fn push_front_deque(&mut self, rhs: FlatVecDeque<T>) {
        self.insert_deque(0, rhs);
    }

    /// Appends another full deque to the deque.
    ///
    /// This is the same as `self.insert_deque(0, rhs)`.
    ///
    /// See [`Self::insert_deque`] for more information.
    #[inline]
    pub fn push_back_deque(&mut self, rhs: FlatVecDeque<T>) {
        self.insert_deque(self.num_entries(), rhs);
    }

    /// Inserts another full deque, starting at `entry_index` and onwards.
    ///
    /// This is O(1) if `entry_index` corresponds to either the start or the end of the deque.
    /// Otherwise, this requires splitting the deque into two pieces then stitching them back together
    /// at both ends of the added data.
    ///
    /// Panics if `entry_index` is out of bounds.
    /// Panics if any of the value arrays in `entries` is empty.
    pub fn insert_deque(&mut self, entry_index: usize, mut rhs: FlatVecDeque<T>) {
        // NOTE: We're inserting _beyond_ the last element.
        if entry_index == self.num_entries() {
            let max_value_offset = self.offsets.back().copied().unwrap_or_default();
            self.offsets
                .extend(rhs.offsets.into_iter().map(|o| o + max_value_offset));
            self.values.extend(rhs.values);
            return;
        } else if entry_index == 0 {
            rhs.push_back_deque(std::mem::take(self));
            *self = rhs;
            return;
        }

        let right = self.split_off(entry_index);
        self.push_back_deque(rhs);
        self.push_back_deque(right);

        debug_assert!(self.iter_offset_ranges().all(|r| r.start <= r.end));
    }
}

#[test]
fn insert() {
    let mut v: FlatVecDeque<i64> = FlatVecDeque::new();

    assert_eq!(0, v.num_entries());
    assert_eq!(0, v.num_values());

    v.insert(0, [1, 2, 3]);
    assert_deque_eq(&[&[1, 2, 3]], &v);

    v.insert(0, [4, 5, 6, 7]);
    assert_deque_eq(&[&[4, 5, 6, 7], &[1, 2, 3]], &v);

    v.insert(0, [8, 9]);
    assert_deque_eq(&[&[8, 9], &[4, 5, 6, 7], &[1, 2, 3]], &v);

    v.insert(2, [10, 11, 12, 13]);
    assert_deque_eq(&[&[8, 9], &[4, 5, 6, 7], &[10, 11, 12, 13], &[1, 2, 3]], &v);

    v.insert(v.num_entries(), [14, 15]);
    assert_deque_eq(
        &[
            &[8, 9],
            &[4, 5, 6, 7],
            &[10, 11, 12, 13],
            &[1, 2, 3],
            &[14, 15],
        ],
        &v,
    );

    v.insert(v.num_entries() - 1, [42]);
    assert_deque_eq(
        &[
            &[8, 9],
            &[4, 5, 6, 7],
            &[10, 11, 12, 13],
            &[1, 2, 3],
            &[42],
            &[14, 15],
        ],
        &v,
    );
}

#[test]
fn insert_empty() {
    let mut v: FlatVecDeque<i64> = FlatVecDeque::new();

    assert_eq!(0, v.num_entries());
    assert_eq!(0, v.num_values());

    v.push_back([]);
    v.push_back([]);
    v.push_back([]);

    assert_deque_eq(&[&[], &[], &[]], &v);
}

// Simulate the bug that was making everything crash on the face tracking example (ultimately
// caused by recursive clears).
#[test]
fn insert_some_and_empty() {
    let mut v: FlatVecDeque<i64> = FlatVecDeque::new();

    assert_eq!(0, v.num_entries());
    assert_eq!(0, v.num_values());

    v.push_back([0]);
    v.push_back([]);

    v.push_back([1]);
    v.push_back([]);

    v.push_back([2]);
    v.push_back([]);

    // That used to crash.
    assert_deque_eq(&[&[0], &[], &[1], &[], &[2], &[]], &v);
}

#[test]
fn insert_many() {
    let mut v: FlatVecDeque<i64> = FlatVecDeque::new();

    assert_eq!(0, v.num_entries());
    assert_eq!(0, v.num_values());

    v.insert_many(0, [vec![1, 2, 3], vec![4, 5, 6, 7], vec![8, 9, 10]]);
    assert_deque_eq(&[&[1, 2, 3], &[4, 5, 6, 7], &[8, 9, 10]], &v);

    v.insert_many(0, [vec![20], vec![21], vec![22]]);
    assert_deque_eq(
        &[&[20], &[21], &[22], &[1, 2, 3], &[4, 5, 6, 7], &[8, 9, 10]],
        &v,
    );

    v.insert_many(4, [vec![41, 42], vec![43]]);
    assert_deque_eq(
        &[
            &[20],
            &[21],
            &[22],
            &[1, 2, 3],
            &[41, 42],
            &[43],
            &[4, 5, 6, 7],
            &[8, 9, 10],
        ],
        &v,
    );

    v.insert_many(v.num_entries(), [vec![100], vec![200, 300, 400]]);
    assert_deque_eq(
        &[
            &[20],
            &[21],
            &[22],
            &[1, 2, 3],
            &[41, 42],
            &[43],
            &[4, 5, 6, 7],
            &[8, 9, 10],
            &[100],
            &[200, 300, 400],
        ],
        &v,
    );
}

#[test]
fn insert_deque() {
    let mut v: FlatVecDeque<i64> = FlatVecDeque::new();

    assert_eq!(0, v.num_entries());
    assert_eq!(0, v.num_values());

    v.insert_deque(
        0,
        FlatVecDeque::from_vecs([vec![1, 2, 3], vec![4, 5, 6, 7], vec![8, 9, 10]]),
    );
    assert_deque_eq(&[&[1, 2, 3], &[4, 5, 6, 7], &[8, 9, 10]], &v);

    v.insert_deque(0, FlatVecDeque::from_vecs([vec![20], vec![21], vec![22]]));
    assert_deque_eq(
        &[&[20], &[21], &[22], &[1, 2, 3], &[4, 5, 6, 7], &[8, 9, 10]],
        &v,
    );

    v.insert_deque(4, FlatVecDeque::from_vecs([vec![41, 42], vec![43]]));
    assert_deque_eq(
        &[
            &[20],
            &[21],
            &[22],
            &[1, 2, 3],
            &[41, 42],
            &[43],
            &[4, 5, 6, 7],
            &[8, 9, 10],
        ],
        &v,
    );

    v.insert_deque(
        v.num_entries(),
        FlatVecDeque::from_vecs([vec![100], vec![200, 300, 400]]),
    );
    assert_deque_eq(
        &[
            &[20],
            &[21],
            &[22],
            &[1, 2, 3],
            &[41, 42],
            &[43],
            &[4, 5, 6, 7],
            &[8, 9, 10],
            &[100],
            &[200, 300, 400],
        ],
        &v,
    );
}

// ---

impl<T> FlatVecDeque<T> {
    /// Splits the deque into two at the given index.
    ///
    /// Returns a newly allocated `FlatVecDeque`. `self` contains entries `[0, entry_index)`,
    /// and the returned deque contains entries `[entry_index, num_entries)`.
    ///
    /// Note that the capacity of `self` does not change.
    ///
    /// Panics if `entry_index` is out of bounds.
    #[inline]
    #[must_use = "use `.truncate()` if you don't need the other half"]
    pub fn split_off(&mut self, entry_index: usize) -> Self {
        let value_offset = self.value_offset(entry_index);

        let mut offsets = self.offsets.split_off(entry_index);
        for offset in &mut offsets {
            *offset -= value_offset;
        }

        Self {
            values: self.values.split_off(value_offset),
            offsets,
        }
    }

    /// Shortens the deque, keeping all entries up to `entry_index` (excluded), and
    /// dropping the rest.
    ///
    /// If `entry_index` is greater or equal to [`Self::num_entries`], this has no effect.
    #[inline]
    pub fn truncate(&mut self, entry_index: usize) {
        if entry_index < self.num_entries() {
            self.values.truncate(self.value_offset(entry_index));
            self.offsets.truncate(entry_index);
        }
    }

    /// Removes the entry at `entry_index` from the deque.
    ///
    /// This is O(1) if `entry_index` corresponds to either the start or the end of the deque.
    /// Otherwise, this requires splitting the deque into three pieces, dropping the superfluous
    /// one, then stitching the two remaining pices back together.
    ///
    /// Panics if `entry_index` is out of bounds.
    pub fn remove(&mut self, entry_index: usize) {
        let (start_offset, end_offset) = (
            self.value_offset(entry_index),
            self.value_offset(entry_index + 1),
        );
        let offset_count = end_offset - start_offset;

        if entry_index + 1 == self.num_entries() {
            self.offsets.truncate(self.num_entries() - 1);
            self.values.truncate(self.values.len() - offset_count);
            return;
        } else if entry_index == 0 {
            *self = self.split_off(entry_index + 1);
            return;
        }

        // NOTE: elegant, but way too slow :)
        // let right = self.split_off(entry_index + 1);
        // _ = self.split_off(self.num_entries() - 1);
        // self.push_back_deque(right);

        _ = self.offsets.remove(entry_index);
        for offset in self.offsets.range_mut(entry_index..) {
            *offset -= offset_count;
        }

        let right = self.values.split_off(end_offset);
        self.values.truncate(self.values.len() - offset_count);
        self.values.extend(right);
    }

    /// Removes all entries within the given `entry_range` from the deque.
    ///
    /// This is O(1) if `entry_range` either starts at the beginning of the deque, or ends at
    /// the end of the deque, or both.
    /// Otherwise, this requires splitting the deque into three pieces, dropping the superfluous
    /// one, then stitching the two remaining pieces back together.
    ///
    /// Panics if `entry_range` is either out of bounds or isn't monotonically increasing.
    #[inline]
    pub fn remove_range(&mut self, entry_range: Range<usize>) {
        assert!(entry_range.start <= entry_range.end);

        if entry_range.start == entry_range.end {
            return;
        }

        let (start_offset, end_offset) = (
            self.value_offset(entry_range.start),
            self.value_offset(entry_range.end),
        );
        let offset_count = end_offset - start_offset;

        // Reminder: `entry_range.end` is exclusive.
        if entry_range.end == self.num_entries() {
            self.offsets
                .truncate(self.num_entries() - entry_range.len());
            self.values.truncate(self.values.len() - offset_count);
            return;
        } else if entry_range.start == 0 {
            *self = self.split_off(entry_range.end);
            return;
        }

        let right = self.split_off(entry_range.end);
        _ = self.split_off(self.num_entries() - entry_range.len());
        self.push_back_deque(right);
    }
}

#[test]
fn truncate() {
    let mut v: FlatVecDeque<i64> = FlatVecDeque::new();

    assert_eq!(0, v.num_entries());
    assert_eq!(0, v.num_values());

    v.insert_many(0, [vec![1, 2, 3], vec![4, 5, 6, 7], vec![8, 9, 10]]);
    assert_deque_eq(&[&[1, 2, 3], &[4, 5, 6, 7], &[8, 9, 10]], &v);

    {
        let mut v = v.clone();
        v.truncate(0);
        assert_deque_eq(&[], &v);
    }

    {
        let mut v = v.clone();
        v.truncate(1);
        assert_deque_eq(&[&[1, 2, 3]], &v);
    }

    {
        let mut v = v.clone();
        v.truncate(2);
        assert_deque_eq(&[&[1, 2, 3], &[4, 5, 6, 7]], &v);
    }

    {
        let mut v = v.clone();
        v.truncate(3);
        assert_deque_eq(&[&[1, 2, 3], &[4, 5, 6, 7], &[8, 9, 10]], &v);
    }
}

#[test]
fn split_off() {
    let mut v: FlatVecDeque<i64> = FlatVecDeque::new();

    assert_eq!(0, v.num_entries());
    assert_eq!(0, v.num_values());

    v.insert_many(0, [vec![1, 2, 3], vec![4, 5, 6, 7], vec![8, 9, 10]]);
    assert_deque_eq(&[&[1, 2, 3], &[4, 5, 6, 7], &[8, 9, 10]], &v);

    {
        let mut left = v.clone();
        let right = left.split_off(0);

        assert_deque_eq(&[], &left);
        assert_deque_eq(&[&[1, 2, 3], &[4, 5, 6, 7], &[8, 9, 10]], &right);
    }

    {
        let mut left = v.clone();
        let right = left.split_off(1);

        assert_deque_eq(&[&[1, 2, 3]], &left);
        assert_deque_eq(&[&[4, 5, 6, 7], &[8, 9, 10]], &right);
    }

    {
        let mut left = v.clone();
        let right = left.split_off(2);

        assert_deque_eq(&[&[1, 2, 3], &[4, 5, 6, 7]], &left);
        assert_deque_eq(&[&[8, 9, 10]], &right);
    }

    {
        let mut left = v.clone();
        let right = left.split_off(3);

        assert_deque_eq(&[&[1, 2, 3], &[4, 5, 6, 7], &[8, 9, 10]], &left);
        assert_deque_eq(&[], &right);
    }
}

#[test]
fn remove() {
    let mut v: FlatVecDeque<i64> = FlatVecDeque::new();

    assert_eq!(0, v.num_entries());
    assert_eq!(0, v.num_values());

    v.insert(0, [1, 2, 3]);
    assert_deque_eq(&[&[1, 2, 3]], &v);

    v.remove(0);
    assert_deque_eq(&[], &v);

    v.insert(0, [1, 2, 3]);
    assert_deque_eq(&[&[1, 2, 3]], &v);

    v.insert(1, [4, 5, 6, 7]);
    assert_deque_eq(&[&[1, 2, 3], &[4, 5, 6, 7]], &v);

    v.insert(2, [8, 9]);
    assert_deque_eq(&[&[1, 2, 3], &[4, 5, 6, 7], &[8, 9]], &v);

    v.remove(0);
    assert_deque_eq(&[&[4, 5, 6, 7], &[8, 9]], &v);

    v.insert(0, [1, 2, 3]);
    assert_deque_eq(&[&[1, 2, 3], &[4, 5, 6, 7], &[8, 9]], &v);

    v.remove(1);
    assert_deque_eq(&[&[1, 2, 3], &[8, 9]], &v);

    v.insert(1, [4, 5, 6, 7]);
    assert_deque_eq(&[&[1, 2, 3], &[4, 5, 6, 7], &[8, 9]], &v);

    v.remove(2);
    assert_deque_eq(&[&[1, 2, 3], &[4, 5, 6, 7]], &v);

    v.remove(0);
    assert_deque_eq(&[&[4, 5, 6, 7]], &v);

    v.remove(0);
    assert_deque_eq(&[], &v);
}

#[test]
#[should_panic(expected = "Out of bounds access")]
fn remove_empty() {
    let mut v: FlatVecDeque<i64> = FlatVecDeque::new();

    assert_eq!(0, v.num_entries());
    assert_eq!(0, v.num_values());

    v.remove(0);
}

#[test]
#[should_panic(expected = "Out of bounds access")]
fn remove_oob() {
    let mut v: FlatVecDeque<i64> = FlatVecDeque::new();

    assert_eq!(0, v.num_entries());
    assert_eq!(0, v.num_values());

    v.insert(0, [1, 2, 3]);
    assert_deque_eq(&[&[1, 2, 3]], &v);

    assert_eq!(1, v.num_entries());
    assert_eq!(3, v.num_values());

    v.remove(1);
}

#[test]
fn remove_range() {
    let mut v: FlatVecDeque<i64> = FlatVecDeque::new();

    assert_eq!(0, v.num_entries());
    assert_eq!(0, v.num_values());

    v.insert_many(0, [vec![1, 2, 3], vec![4, 5, 6, 7], vec![8, 9, 10]]);
    assert_deque_eq(&[&[1, 2, 3], &[4, 5, 6, 7], &[8, 9, 10]], &v);

    {
        let mut v = v.clone();
        v.remove_range(0..1);
        assert_deque_eq(&[&[4, 5, 6, 7], &[8, 9, 10]], &v);
    }

    {
        let mut v = v.clone();
        v.remove_range(1..2);
        assert_deque_eq(&[&[1, 2, 3], &[8, 9, 10]], &v);
    }

    {
        let mut v = v.clone();
        v.remove_range(2..3);
        assert_deque_eq(&[&[1, 2, 3], &[4, 5, 6, 7]], &v);
    }

    {
        let mut v = v.clone();
        v.remove_range(0..2);
        assert_deque_eq(&[&[8, 9, 10]], &v);
    }

    {
        let mut v = v.clone();
        v.remove_range(1..3);
        assert_deque_eq(&[&[1, 2, 3]], &v);
    }

    {
        let mut v = v.clone();
        v.remove_range(0..3);
        assert_deque_eq(&[], &v);
    }
}

// ---

#[cfg(test)]
fn assert_deque_eq(expected: &[&'_ [i64]], got: &FlatVecDeque<i64>) {
    similar_asserts::assert_eq!(expected, got.iter().collect_vec());
}

#[cfg(test)]
fn assert_iter_eq<'a>(expected: &[&'_ [i64]], got: impl Iterator<Item = &'a [i64]>) {
    similar_asserts::assert_eq!(expected, got.collect_vec());
}