flow-lang-value 0.1.0-rc.5

The Flow runtime value model: data values, their equality, order and text, and the operations std's built-in types declare.
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
//! `List`, `Dict` and `Set` (`data.md`).
//!
//! # What each costs
//!
//! A [`List`] is up to [`EDGE`] elements at its front, a window onto a
//! balanced tree of chunks of elements shared between every list made from
//! it (the `tree` module), and up to [`EDGE`] elements at its back. A list of
//! at most [`EDGE`] elements has no tree. For a list of `n` elements, indexing
//! costs O(log n); taking a contiguous part — the `[x, ..rest]` and
//! `[..init, last]` patterns — costs O(EDGE) and shares the whole tree;
//! growing at either end costs O(EDGE) amortized and leaves the tree as it
//! was until an end holds [`EDGE`], when those move into the tree as one
//! leaf in O(log n); joining two lists costs O(log n + EDGE). None of these
//! copies a tree node another value still holds, so a list grown from a
//! stored one shares every node of it: what history stores for the grown
//! list is its ends and the nodes that differ (`trace.md`, *Lists*). Growing
//! or joining a part first cuts the tree down to it, in O(log n), so only a
//! part kept alive as it is keeps its whole tree alive.
//!
//! A [`Dict`] keeps its entries and a [`Set`] its members in key order in
//! the same kind of tree, and inserting or removing copies only the path to
//! the element. Looking up costs logarithmic time.
//!
//! None of this is observable: `data.md` leaves a representation to the
//! implementation, and two equal values behave equally in every operation.

use std::cmp::Ordering;
use std::sync::Arc;

use crate::error::{DataError, StructureError};
use crate::int::Int;
use crate::tree::{self, CHUNK, Keyed, Measure, Member, Node, Tree};
use crate::value::{Meta, Value, compare};

/// The most elements a list keeps at either end, outside its tree.
pub(crate) const EDGE: usize = CHUNK;

/// The elements at one end of a list, outside its tree: at most [`EDGE`],
/// shared between lists until one of them changes its end.
#[derive(Clone, Debug, Default)]
#[expect(
    clippy::rc_buffer,
    reason = "an end grows and shrinks in place through `Arc::make_mut` while no other list holds it"
)]
pub(crate) struct End(Option<Arc<Vec<Value>>>);

impl End {
    fn of(items: Vec<Value>) -> End {
        End((!items.is_empty()).then(|| Arc::new(items)))
    }

    pub(crate) fn as_slice(&self) -> &[Value] {
        self.0.as_deref().map_or(&[], Vec::as_slice)
    }

    pub(crate) fn len(&self) -> usize {
        self.as_slice().len()
    }

    pub(crate) fn is_empty(&self) -> bool {
        self.0.is_none()
    }

    /// What tells these elements apart from every other end alive: 0 for
    /// none.
    fn id(&self) -> usize {
        self.0.as_ref().map_or(0, |items| Arc::as_ptr(items).addr())
    }

    /// The elements, owned: moved out when nothing else holds them.
    fn take(&mut self) -> Vec<Value> {
        self.0.take().map(Arc::unwrap_or_clone).unwrap_or_default()
    }

    /// The elements to change in place, copied first if another list holds
    /// them.
    fn items(&mut self) -> &mut Vec<Value> {
        Arc::make_mut(
            self.0
                .get_or_insert_with(|| Arc::new(Vec::with_capacity(EDGE))),
        )
    }

    /// The elements dropping this end would drop.
    fn unshared(&mut self) -> impl Iterator<Item = &mut Value> {
        self.0.as_mut().and_then(Arc::get_mut).into_iter().flatten()
    }
}

/// Dropping a list drops its ends and the nodes of its tree that nothing else
/// holds, and hands the elements in them to `dismantle` in the value module,
/// so a deep value drops without deep recursion.
impl Drop for List {
    fn drop(&mut self) {
        crate::value::dismantle(self.unshared_parts());
    }
}

/// A list: a finite sequence, in order.
#[derive(Clone, Debug)]
pub struct List {
    /// The elements before the tree's, at most [`EDGE`].
    pub(crate) front: End,
    /// The tree the middle elements lie in, which may hold more: a part of a
    /// list shares the tree of the list it was cut from.
    pub(crate) root: Option<Tree>,
    /// Where in the tree the middle elements start.
    pub(crate) start: usize,
    /// How many elements the list takes from the tree.
    pub(crate) middle: usize,
    /// The elements after the tree's, at most [`EDGE`].
    pub(crate) back: End,
    /// What its elements measure, exactly.
    pub(crate) meta: Meta,
}

impl Default for List {
    fn default() -> Self {
        List::of(End::default(), None, End::default(), Meta::EMPTY)
    }
}

impl List {
    /// Returns the empty list.
    pub fn new() -> Self {
        List::default()
    }

    /// Returns `front`, then all of `tree`'s elements, then `back`, measuring
    /// `meta`. A list of at most [`EDGE`] elements is moved to its back.
    fn of(front: End, tree: Option<Tree>, back: End, meta: Meta) -> List {
        let middle = tree.as_ref().map_or(0, Node::len);
        let mut list = List {
            front,
            root: tree,
            start: 0,
            middle,
            back,
            meta,
        };
        list.settle();
        list
    }

    /// Returns `front`, then the `middle` elements of `root` from `start`,
    /// then `back`, settled and measured exactly.
    fn window(front: End, root: Option<Node>, start: usize, middle: usize, back: End) -> List {
        let mut list = List {
            front,
            root,
            start,
            middle,
            back,
            meta: Meta::EMPTY,
        };
        list.settle();
        list.meta = list.measure();
        list
    }

    /// Keeps a short list in its back, so a list of at most [`EDGE`]
    /// elements has no tree and joining one adds to an end.
    fn settle(&mut self) {
        if self.middle == 0 {
            self.root = None;
            self.start = 0;
            if !self.front.is_empty() && self.front.len() + self.back.len() <= EDGE {
                let mut back = self.front.take();
                back.append(&mut self.back.take());
                self.back = End::of(back);
            }
        } else if self.len() <= EDGE {
            let items: Vec<Value> = self.iter().cloned().collect();
            self.front = End::default();
            self.root = None;
            self.start = 0;
            self.middle = 0;
            self.back = End::of(items);
        }
    }

    /// What the elements measure, exactly: the ends' elements and those of
    /// the window the list takes from its tree, in O(EDGE + log n).
    fn measure(&self) -> Meta {
        let ends = Meta::around(self.front.as_slice().iter().chain(self.back.as_slice()));
        self.root.as_ref().map_or(ends, |root| {
            ends.join(tree::range_measure(root, self.start, self.middle))
        })
    }

    /// Returns what the list is made of: the list is `front`, then the
    /// elements of `tree` it takes, then `back`.
    ///
    /// The front and the back hold at most eight elements each. A list of
    /// more than eight whose ends do not hold all of it has a tree, and
    /// one of at most eight has none and holds everything at its back.
    pub fn parts(&self) -> ListParts<'_> {
        ListParts {
            front: self.front.as_slice(),
            tree: self
                .root
                .as_ref()
                .map(|root| (root, self.start, self.middle)),
            back: self.back.as_slice(),
        }
    }

    /// Returns the whole list as one balanced tree, or `None` when it is
    /// empty: its front, the elements it takes from its tree and its back,
    /// joined. The tree shares every node of the list's own that the cut
    /// and the joins do not pass through, so it costs O(log n) new nodes.
    pub fn tree(&self) -> Option<Node> {
        let middle = self.root.clone().and_then(|root| {
            if self.start == 0 && self.middle == root.len() {
                Some(root)
            } else {
                tree::range(root, self.start, self.middle)
            }
        });
        let end = |items: &[Value]| (!items.is_empty()).then(|| tree::leaf(items.to_vec()));
        [
            end(self.front.as_slice()),
            middle,
            end(self.back.as_slice()),
        ]
        .into_iter()
        .flatten()
        .reduce(tree::join)
    }

    /// Returns the list of `front`, then the `taken` elements of `tree`
    /// that follow its first `skip`, then `back`, sharing `tree`.
    ///
    /// The list's measure is that of its ends and of the window, which the
    /// tree's nodes record, so this costs O(EDGE + log n) whatever the tree
    /// holds, but for a list of at most eight elements, which keeps no tree
    /// and is copied out of it.
    ///
    /// # Errors
    ///
    /// [`StructureError::End`] when an end holds more than eight elements,
    /// and [`StructureError::Window`] when the tree does not hold
    /// `skip + taken` elements.
    pub fn from_parts(
        front: Vec<Value>,
        tree: Option<(Node, usize, usize)>,
        back: Vec<Value>,
    ) -> Result<List, StructureError> {
        if front.len() > EDGE || back.len() > EDGE {
            return Err(StructureError::End);
        }
        let (root, start, middle) = match tree {
            None => (None, 0, 0),
            Some((root, skip, taken)) => {
                let fits = skip.checked_add(taken).is_some_and(|end| end <= root.len());
                if !fits {
                    return Err(StructureError::Window);
                }
                (Some(root), skip, taken)
            }
        };
        Ok(List::window(
            End::of(front),
            root,
            start,
            middle,
            End::of(back),
        ))
    }

    /// What tells this list apart from every other list alive: the ends it
    /// holds, its tree, and the window it takes from that tree.
    pub(crate) fn id(&self) -> [usize; 5] {
        [
            self.front.id(),
            self.root.as_ref().map_or(0, Node::id),
            self.start,
            self.middle,
            self.back.id(),
        ]
    }

    /// Returns how many elements there are.
    pub fn len(&self) -> usize {
        self.front.len() + self.middle + self.back.len()
    }

    /// Returns whether there are none.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns the element at a zero-based position.
    pub fn get(&self, index: usize) -> Option<&Value> {
        if let Some(item) = self.front.as_slice().get(index) {
            return Some(item);
        }
        let index = index - self.front.len();
        if index < self.middle {
            return Some(tree::get(self.root.as_ref()?, self.start + index));
        }
        self.back.as_slice().get(index - self.middle)
    }

    /// Returns the element at a zero-based `Int` position: `None` for a
    /// negative one or one not less than the length (`list.get`).
    pub fn get_int(&self, index: &Int) -> Option<&Value> {
        self.get(index.to_index()?)
    }

    /// Returns the elements, in order.
    pub fn iter(&self) -> impl DoubleEndedIterator<Item = &Value> + ExactSizeIterator {
        self.elements()
    }

    pub(crate) fn elements(&self) -> Elements<'_> {
        Elements {
            front: self.front.as_slice().iter(),
            middle: tree::Iter::new(self.root.as_ref(), self.start, self.middle),
            back: self.back.as_slice().iter(),
        }
    }

    /// Returns the elements of the ends and of the nodes nothing else holds:
    /// what dropping the list would drop.
    pub(crate) fn unshared_parts(&mut self) -> impl Iterator<Item = &mut Value> {
        self.front
            .unshared()
            .chain(self.root.iter_mut().flat_map(tree::unshared))
            .chain(self.back.unshared())
    }

    /// Returns the elements from `start` up to, not including, `end`, sharing
    /// this list's tree, or `None` unless `start ≤ end ≤ length`.
    pub fn slice(&self, start: usize, end: usize) -> Option<List> {
        if start > end || end > self.len() {
            return None;
        }
        let ends = |kept: &End, from: usize, to: usize| -> End {
            let items = kept.as_slice();
            let (from, to) = (from.min(items.len()), to.min(items.len()));
            if from == 0 && to == items.len() {
                kept.clone()
            } else {
                End::of(items[from..to].to_vec())
            }
        };
        let front = ends(&self.front, start, end);
        let in_middle = |at: usize| at.saturating_sub(self.front.len()).min(self.middle);
        let (first, past) = (in_middle(start), in_middle(end));
        let in_back = |at: usize| at.saturating_sub(self.front.len() + self.middle);
        let back = ends(&self.back, in_back(start), in_back(end));
        let root = (past > first).then(|| self.root.clone()).flatten();
        Some(List::window(
            front,
            root,
            self.start + first,
            past - first,
            back,
        ))
    }

    /// Returns `self` with `item` added at the end.
    #[must_use]
    pub fn push_back(mut self, item: Value) -> List {
        self.meta = self.meta.with(&item);
        if self.back.len() == EDGE {
            let full = self.back.take();
            self.add_leaf_at_back(full);
        }
        self.back.items().push(item);
        self
    }

    /// Returns `self` with `item` added at the front.
    #[must_use]
    pub fn push_front(mut self, item: Value) -> List {
        self.meta = self.meta.with(&item);
        if self.front.len() == EDGE {
            let full = self.front.take();
            self.add_leaf_at_front(full);
        } else if self.front.is_empty() && self.middle == 0 && self.back.len() < EDGE {
            self.back.items().insert(0, item);
            return self;
        }
        self.front.items().insert(0, item);
        self
    }

    /// Moves `items`, a full end, into the tree after its elements.
    fn add_leaf_at_back(&mut self, items: Vec<Value>) {
        let leaf = tree::leaf(items);
        let tree = match self.take_tree() {
            Some(tree) => tree::join(tree, leaf),
            None => leaf,
        };
        self.middle = tree.len();
        self.root = Some(tree);
    }

    /// Moves `items`, a full end, into the tree before its elements.
    fn add_leaf_at_front(&mut self, items: Vec<Value>) {
        let leaf = tree::leaf(items);
        let tree = match self.take_tree() {
            Some(tree) => tree::join(leaf, tree),
            None => leaf,
        };
        self.middle = tree.len();
        self.root = Some(tree);
    }

    /// Returns `self + other`, sharing both lists' trees.
    #[must_use]
    pub fn concat(mut self, mut other: List) -> List {
        let meta = self.meta.join(other.meta);
        if other.middle == 0 {
            // Adding a list with no tree: its elements join this back.
            let mut added = other.front.take();
            added.append(&mut other.back.take());
            let mut list = self;
            list.meta = meta;
            for item in added {
                list = list.push_back(item);
            }
            return list;
        }
        if self.middle == 0 {
            let mut added = self.front.take();
            added.append(&mut self.back.take());
            let mut list = other;
            list.meta = meta;
            for item in added.into_iter().rev() {
                list = list.push_front(item);
            }
            return list;
        }
        let front = std::mem::take(&mut self.front);
        let back = std::mem::take(&mut other.back);
        let mut seam = self.back.take();
        seam.append(&mut other.front.take());
        let (left, right) = (self.take_middle(), other.take_middle());
        let left = seam.into_iter().fold(left, tree::push_back);
        List::of(front, Some(tree::concat(left, right)), back, meta)
    }

    /// Returns `items` reordered by `keys`, one key per item, stably: items
    /// whose keys are equal keep their order (`list.sort_by`).
    ///
    /// Returns `None` when there is not exactly one key per item.
    ///
    /// # Errors
    ///
    /// A [`DataError`] when two keys cannot be compared: one is not data, or
    /// the two are of different shapes.
    pub fn sort_by_keys(&self, keys: &[Value]) -> Result<Option<List>, DataError> {
        if keys.len() != self.len() {
            return Ok(None);
        }
        let mut order: Vec<usize> = (0..self.len()).collect();
        let mut failure = None;
        order.sort_by(|&a, &b| {
            compare(&keys[a], &keys[b]).unwrap_or_else(|error| {
                failure = Some(error);
                Ordering::Equal
            })
        });
        if let Some(error) = failure {
            return Err(error);
        }
        let items: Vec<&Value> = self.iter().collect();
        Ok(Some(
            order.into_iter().map(|at| items[at].clone()).collect(),
        ))
    }

    /// The tree [`List::take_tree`] takes from a list with a middle.
    fn take_middle(&mut self) -> Tree {
        self.take_tree().expect("a list with a middle has a tree")
    }

    /// Takes the tree, cut down to exactly this list's middle elements,
    /// leaving the list with no middle; `None` when it has none.
    fn take_tree(&mut self) -> Option<Tree> {
        let root = self.root.take()?;
        let (start, middle) = (self.start, self.middle);
        self.start = 0;
        self.middle = 0;
        if start == 0 && middle == root.len() {
            Some(root)
        } else {
            tree::range(root, start, middle)
        }
    }
}

/// What a [`List`] is made of ([`List::parts`]).
#[derive(Clone, Copy, Debug)]
pub struct ListParts<'a> {
    /// The elements before the tree's: at most eight.
    pub front: &'a [Value],
    /// The tree, how many of its elements to pass over, and how many to
    /// take: present only when the list takes at least one.
    pub tree: Option<(&'a Node, usize, usize)>,
    /// The elements after the tree's: at most eight.
    pub back: &'a [Value],
}

impl FromIterator<Value> for List {
    fn from_iter<I: IntoIterator<Item = Value>>(items: I) -> Self {
        let mut meta = Meta::EMPTY;
        let items: Vec<Value> = items
            .into_iter()
            .inspect(|item| meta = meta.with(item))
            .collect();
        if items.len() <= EDGE {
            return List::of(End::default(), None, End::of(items), meta);
        }
        List::of(End::default(), tree::build(items), End::default(), meta)
    }
}

/// A list's elements, in order and from either end: its front, the middle
/// it takes from its tree, and its back.
#[derive(Clone, Debug)]
pub(crate) struct Elements<'a> {
    front: std::slice::Iter<'a, Value>,
    middle: tree::Iter<'a>,
    back: std::slice::Iter<'a, Value>,
}

impl<'a> Iterator for Elements<'a> {
    type Item = &'a Value;

    #[inline]
    fn next(&mut self) -> Option<&'a Value> {
        self.front
            .next()
            .or_else(|| self.middle.next())
            .or_else(|| self.back.next())
    }

    fn nth(&mut self, mut n: usize) -> Option<&'a Value> {
        let front = self.front.len();
        if n < front {
            return self.front.nth(n);
        }
        self.front.nth(front);
        n -= front;
        let middle = self.middle.len();
        if n < middle {
            return self.middle.nth(n);
        }
        self.middle.nth(middle);
        self.back.nth(n - middle)
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let left = self.front.len() + self.middle.len() + self.back.len();
        (left, Some(left))
    }
}

impl<'a> DoubleEndedIterator for Elements<'a> {
    #[inline]
    fn next_back(&mut self) -> Option<&'a Value> {
        self.back
            .next_back()
            .or_else(|| self.middle.next_back())
            .or_else(|| self.front.next_back())
    }

    fn nth_back(&mut self, mut n: usize) -> Option<&'a Value> {
        let back = self.back.len();
        if n < back {
            return self.back.nth_back(n);
        }
        self.back.nth_back(back);
        n -= back;
        let middle = self.middle.len();
        if n < middle {
            return self.middle.nth_back(n);
        }
        self.middle.nth_back(middle);
        self.front.nth_back(n - middle)
    }
}

impl ExactSizeIterator for Elements<'_> {}

/// Which of several items with one key [`sort_unique`] keeps.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Keep {
    /// The first written, as a set does.
    First,
    /// The last written, as a dictionary literal does.
    Last,
}

/// Sorts `items` stably by `key_of`, then keeps one item per key: the first
/// or the last written, as `keep` says.
fn sort_unique<T>(
    mut items: Vec<T>,
    key_of: impl Fn(&T) -> &Value,
    keep: Keep,
) -> Result<Vec<T>, DataError> {
    let keep_last = keep == Keep::Last;
    let mut failure = None;
    items.sort_by(|a, b| {
        compare(key_of(a), key_of(b)).unwrap_or_else(|error| {
            failure = Some(error);
            Ordering::Equal
        })
    });
    if let Some(error) = failure {
        return Err(error);
    }
    if keep_last {
        items.reverse();
    }
    // Equal keys are adjacent, and every comparison above succeeded, so
    // these cannot fail; the stable sort put the first-written first, and the
    // reversal put the last-written first, which is the one `dedup` keeps.
    items.dedup_by(|later, earlier| compare(key_of(later), key_of(earlier)) == Ok(Ordering::Equal));
    if keep_last {
        items.reverse();
    }
    Ok(items)
}

/// A tree of elements kept in ascending key order, distinct by key: what a
/// [`Dict`] and a [`Set`] each are, over their own element.
///
/// Looking up, inserting or removing a key costs O(log n) comparisons and
/// steps: the way down compares the key with the first key of each right
/// subtree it passes. Inserting or removing copies only the path to the
/// element, so one made from a stored one shares every other node of it.
#[derive(Clone, Debug)]
struct Ordered<E: Keyed> {
    root: Option<Tree<E>>,
}

impl<E: Keyed> Default for Ordered<E> {
    fn default() -> Self {
        Ordered { root: None }
    }
}

impl<E: Keyed> Ordered<E> {
    /// Returns the tree of `items`, sorted by key and keeping one item per
    /// key, the first or the last written as `keep` says.
    fn of(items: Vec<E>, keep: Keep) -> Result<Self, DataError> {
        let items = sort_unique(items, Keyed::sort_key, keep)?;
        Ok(Ordered {
            root: tree::build(items),
        })
    }

    /// Returns the tree `root`, whose keys must ascend and be distinct; a
    /// debug build checks that.
    fn from_tree(root: Option<Node<E>>) -> Self {
        let ordered = Ordered { root };
        debug_assert!(
            ordered
                .iter()
                .zip(ordered.iter().skip(1))
                .all(|(earlier, later)| {
                    compare(earlier.sort_key(), later.sort_key()) == Ok(Ordering::Less)
                }),
            "keys ascend"
        );
        ordered
    }

    fn len(&self) -> usize {
        self.root.as_ref().map_or(0, Node::len)
    }

    fn is_empty(&self) -> bool {
        self.root.is_none()
    }

    fn iter(&self) -> tree::Iter<'_, E> {
        tree::Iter::new(self.root.as_ref(), 0, self.len())
    }

    /// The element at `index` in order, if there is one.
    fn get(&self, index: usize) -> Option<&E> {
        let root = self.root.as_ref()?;
        (index < root.len()).then(|| tree::get(root, index))
    }

    /// What the elements measure, exactly, as the root records it.
    fn meta(&self) -> Meta {
        self.root.as_ref().map_or(Meta::EMPTY, Node::measure)
    }

    fn id(&self) -> usize {
        self.root.as_ref().map_or(0, Node::id)
    }

    /// Finds `key`: its position and element when present, and otherwise
    /// where it would go.
    fn find(&self, key: &Value) -> Result<tree::Found<'_, E>, DataError> {
        match &self.root {
            Some(root) => tree::find(root, key),
            None => Ok(Err(0)),
        }
    }

    /// Returns `self` with `item`; of it and an element with its key, the
    /// one `keep` says: the element held, or `item`, written last.
    fn insert(mut self, item: E, keep: Keep) -> Result<Self, DataError> {
        let found = self.find(item.sort_key())?.map(|(at, _)| at);
        self.root = Some(match (self.root.take(), found, keep) {
            (Some(root), Ok(at), Keep::Last) => tree::replace(root, at, item),
            (Some(root), Ok(_), Keep::First) => root,
            (Some(root), Err(at), _) => tree::insert(root, at, item),
            (None, _, _) => tree::leaf(vec![item]),
        });
        Ok(self)
    }

    /// Returns `self` without the element whose key is `key`.
    fn remove(mut self, key: &Value) -> Result<Self, DataError> {
        if let Ok((at, _)) = self.find(key)? {
            self.root = self.root.take().and_then(|root| tree::remove(root, at));
        }
        Ok(self)
    }

    /// The elements of the nodes nothing else holds: what dropping the tree
    /// would drop.
    fn unshared(&mut self) -> impl Iterator<Item = &mut E> {
        self.root.iter_mut().flat_map(tree::unshared)
    }
}

impl Drop for Dict {
    fn drop(&mut self) {
        crate::value::dismantle(self.unshared_parts());
    }
}

/// A dictionary: keys mapped to values, sorted by key.
///
/// Its entries lie in a balanced tree of chunks, as a list's elements do, in
/// key order, and every branch keeps the key of its first entry. Looking up,
/// inserting or removing a key costs O(log n) comparisons and steps.
#[derive(Clone, Debug, Default)]
pub struct Dict {
    entries: Ordered<(Value, Value)>,
}

impl Dict {
    /// Returns the empty dictionary.
    pub fn new() -> Self {
        Dict::default()
    }

    /// Returns the dictionary of `entries`, where a later entry with a key
    /// equal to an earlier one's wins (the dictionary literal's rule).
    ///
    /// # Errors
    ///
    /// A [`DataError`] when two keys cannot be compared.
    pub fn from_entries(
        entries: impl IntoIterator<Item = (Value, Value)>,
    ) -> Result<Dict, DataError> {
        Ok(Dict {
            entries: Ordered::of(entries.into_iter().collect(), Keep::Last)?,
        })
    }

    /// Returns how many entries there are.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Returns whether there are none.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    pub(crate) fn entries(&self) -> tree::Iter<'_, (Value, Value)> {
        self.entries.iter()
    }

    /// The entry at `index` in key order, if there is one.
    pub(crate) fn entry(&self, index: usize) -> Option<&(Value, Value)> {
        self.entries.get(index)
    }

    /// What its keys and values measure, exactly.
    pub(crate) fn meta(&self) -> Meta {
        self.entries.meta()
    }

    /// Returns the keys and values of the nodes nothing else holds: what
    /// dropping the dictionary would drop.
    pub(crate) fn unshared_parts(&mut self) -> impl Iterator<Item = &mut Value> {
        self.entries
            .unshared()
            .flat_map(|(key, value)| [key, value])
    }

    /// Returns the entries, in key order.
    pub fn iter(&self) -> impl ExactSizeIterator<Item = (&Value, &Value)> {
        self.entries().map(|(key, value)| (key, value))
    }

    /// Returns the keys, in key order.
    pub fn keys(&self) -> impl ExactSizeIterator<Item = &Value> {
        self.entries().map(|(key, _)| key)
    }

    /// Returns the values, in key order.
    pub fn values(&self) -> impl ExactSizeIterator<Item = &Value> {
        self.entries().map(|(_, value)| value)
    }

    /// Returns the value at `key`.
    ///
    /// # Errors
    ///
    /// A [`DataError`] when `key` cannot be compared with the keys held.
    pub fn get(&self, key: &Value) -> Result<Option<&Value>, DataError> {
        Ok(self.entries.find(key)?.ok().map(|(_, (_, value))| value))
    }

    /// Returns the tree the entries lie in, in ascending key order, or
    /// `None` when there are none.
    pub fn root(&self) -> Option<&Node<(Value, Value)>> {
        self.entries.root.as_ref()
    }

    /// Returns the dictionary whose entries are those of `root`, sharing it.
    ///
    /// The keys must ascend across the whole tree and be distinct, as those
    /// of [`Dict::root`] do; the caller checks that, as reading history
    /// does, and a debug build checks it again. This costs constant time.
    pub fn from_tree(root: Option<Node<(Value, Value)>>) -> Dict {
        Dict {
            entries: Ordered::from_tree(root),
        }
    }

    /// What tells this dictionary apart from every other alive: its tree.
    pub(crate) fn id(&self) -> usize {
        self.entries.id()
    }

    /// Returns `self` with `key` mapped to `value`, replacing any earlier
    /// value.
    ///
    /// # Errors
    ///
    /// A [`DataError`] when `key` cannot be compared with the keys held.
    pub fn insert(mut self, key: Value, value: Value) -> Result<Dict, DataError> {
        self.entries = std::mem::take(&mut self.entries).insert((key, value), Keep::Last)?;
        Ok(self)
    }

    /// Returns `self` without `key`.
    ///
    /// # Errors
    ///
    /// A [`DataError`] when `key` cannot be compared with the keys held.
    pub fn remove(mut self, key: &Value) -> Result<Dict, DataError> {
        self.entries = std::mem::take(&mut self.entries).remove(key)?;
        Ok(self)
    }
}

impl Drop for Set {
    fn drop(&mut self) {
        crate::value::dismantle(self.unshared_parts());
    }
}

/// A set: distinct values, sorted.
///
/// Its members lie in a balanced tree in ascending order, so looking one up,
/// inserting or removing one costs O(log n), and a set made from a stored one
/// shares every node the change does not touch.
#[derive(Clone, Debug, Default)]
pub struct Set {
    members: Ordered<Member>,
}

impl Set {
    /// Returns the set of `items`' distinct elements (`set.from`).
    ///
    /// # Errors
    ///
    /// A [`DataError`] when two elements cannot be compared.
    pub fn from_items(items: impl IntoIterator<Item = Value>) -> Result<Set, DataError> {
        Ok(Set {
            members: Ordered::of(items.into_iter().map(Member::new).collect(), Keep::First)?,
        })
    }

    /// Returns how many elements there are.
    pub fn len(&self) -> usize {
        self.members.len()
    }

    /// Returns whether there are none.
    pub fn is_empty(&self) -> bool {
        self.members.is_empty()
    }

    /// Returns the elements, in order.
    pub fn iter(&self) -> impl ExactSizeIterator<Item = &Value> {
        self.members.iter().map(Member::value)
    }

    pub(crate) fn members(&self) -> tree::Iter<'_, Member> {
        self.members.iter()
    }

    /// The element at `index` in order, if there is one.
    pub(crate) fn member(&self, index: usize) -> Option<&Value> {
        self.members.get(index).map(Member::value)
    }

    /// What its elements measure, exactly.
    pub(crate) fn meta(&self) -> Meta {
        self.members.meta()
    }

    /// Returns the elements of the nodes nothing else holds: what dropping
    /// the set would drop.
    pub(crate) fn unshared_parts(&mut self) -> impl Iterator<Item = &mut Value> {
        self.members.unshared().map(Member::value_mut)
    }

    /// Returns the tree the members lie in, in ascending order, or `None`
    /// when there are none.
    pub fn root(&self) -> Option<&Node<Member>> {
        self.members.root.as_ref()
    }

    /// Returns the set whose members are those of `root`, sharing it.
    ///
    /// The members must ascend across the whole tree and be distinct, as
    /// those of [`Set::root`] do; the caller checks that, as reading history
    /// does, and a debug build checks it again.
    pub fn from_tree(root: Option<Node<Member>>) -> Set {
        Set {
            members: Ordered::from_tree(root),
        }
    }

    /// What tells this set apart from every other alive: its tree.
    pub(crate) fn id(&self) -> usize {
        self.members.id()
    }

    /// Returns whether `item` is an element.
    ///
    /// # Errors
    ///
    /// A [`DataError`] when `item` cannot be compared with the elements.
    pub fn contains(&self, item: &Value) -> Result<bool, DataError> {
        Ok(self.members.find(item)?.is_ok())
    }

    /// Returns `self` with `item` among its elements; `self` itself when
    /// it already is one.
    ///
    /// # Errors
    ///
    /// A [`DataError`] when `item` cannot be compared with the elements.
    pub fn insert(mut self, item: Value) -> Result<Set, DataError> {
        self.members = std::mem::take(&mut self.members).insert(Member::new(item), Keep::First)?;
        Ok(self)
    }

    /// Returns `self` without `item`.
    ///
    /// # Errors
    ///
    /// A [`DataError`] when `item` cannot be compared with the elements.
    pub fn remove(mut self, item: &Value) -> Result<Set, DataError> {
        self.members = std::mem::take(&mut self.members).remove(item)?;
        Ok(self)
    }
}