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
//! `Text` and `Bytes` (`data.md`, *Text* and *Bytes*).

use std::fmt;
use std::sync::{Arc, LazyLock, OnceLock};

use regex_syntax::hir::{Class, HirKind};
use unicode_normalization::UnicodeNormalization;
use unicode_segmentation::UnicodeSegmentation;

use crate::error::StructureError;
use crate::int::Int;
use crate::tree::{self, Along, Measure, Node, Shape};

/// The Unicode version normalization, case mapping and grapheme segmentation
/// use (`data.md`, *Text*).
///
/// Every table comes from a crate pinned exactly in the workspace manifest —
/// `unicode-normalization`, `unicode-segmentation`, `unicode-case-mapping`, and
/// `regex-syntax` for the `Cased` and `Case_Ignorable` properties — and none
/// from the Rust toolchain, whose `char` methods follow whatever Unicode the
/// compiler shipped with. A test holds each crate to this one version, so
/// changing it is a change of std, never a drift between builds.
pub const UNICODE_VERSION: (u8, u8, u8) = (16, 0, 0);

/// GREEK CAPITAL LETTER SIGMA, the one code point whose default lowercase
/// mapping reads its context.
const CAPITAL_SIGMA: char = '\u{3a3}';

/// GREEK SMALL LETTER FINAL SIGMA, what [`CAPITAL_SIGMA`] lowercases to where
/// the `Final_Sigma` condition holds.
const FINAL_SIGMA: char = '\u{3c2}';

/// The code points with Unicode's `Cased` property.
static CASED: LazyLock<Vec<(char, char)>> = LazyLock::new(|| property("Cased"));

/// The code points with Unicode's `Case_Ignorable` property.
static CASE_IGNORABLE: LazyLock<Vec<(char, char)>> = LazyLock::new(|| property("Case_Ignorable"));

/// Returns the ranges of the binary Unicode property `name`, from
/// `regex-syntax`'s tables.
fn property(name: &str) -> Vec<(char, char)> {
    let class = regex_syntax::Parser::new()
        .parse(&format!(r"\p{{{name}}}"))
        .map(regex_syntax::hir::Hir::into_kind);
    match class {
        Ok(HirKind::Class(Class::Unicode(class))) => class
            .ranges()
            .iter()
            .map(|range| (range.start(), range.end()))
            .collect(),
        _ => unreachable!("regex-syntax knows the binary property {name}"),
    }
}

/// Returns whether `code_point` lies in one of `ranges`, which are sorted and
/// disjoint.
fn has(ranges: &[(char, char)], code_point: char) -> bool {
    ranges
        .binary_search_by(|&(start, end)| {
            if end < code_point {
                std::cmp::Ordering::Less
            } else if start > code_point {
                std::cmp::Ordering::Greater
            } else {
                std::cmp::Ordering::Equal
            }
        })
        .is_ok()
}

/// Returns whether a cased letter, then any case-ignorable code points, lead
/// up to the end of `before`, the `Final_Sigma` condition's first half
/// (Unicode, ch. 3, *Default Case Conversion*, table 3-17).
fn after_a_cased_letter(before: &str) -> bool {
    for code_point in before.chars().rev() {
        if has(&CASED, code_point) {
            return true;
        }
        if !has(&CASE_IGNORABLE, code_point) {
            return false;
        }
    }
    false
}

/// Returns whether any case-ignorable code points, then a cased letter, open
/// `after`; `Final_Sigma` requires that this not hold.
fn before_a_cased_letter(after: &str) -> bool {
    for code_point in after.chars() {
        if has(&CASED, code_point) {
            return true;
        }
        if !has(&CASE_IGNORABLE, code_point) {
            return false;
        }
    }
    false
}

/// Appends `code_point`'s full case mapping, `mapped`: the code points before
/// the first zero, or `code_point` itself when there are none.
fn push_mapped(out: &mut String, code_point: char, mapped: &[u32]) {
    if mapped[0] == 0 {
        out.push(code_point);
    } else {
        out.extend(
            mapped
                .iter()
                .take_while(|&&unit| unit != 0)
                .filter_map(|&unit| char::from_u32(unit)),
        );
    }
}

/// A finite sequence of Unicode code points, stored as UTF-8.
///
/// Length, indexing and slicing count code points. Nothing is normalized:
/// a `Text` is exactly the code points that built it, and equality and order
/// compare code points. UTF-8 preserves code-point order under byte
/// comparison, so comparing the bytes is `data.md`'s lexicographic order by
/// code point, with a proper prefix first.
///
/// A text is a balanced tree of **runs**, each a window onto a shared block
/// of UTF-8, kept in the tree every list, dictionary and set keeps its
/// elements in, each leaf one run and each node recording how many bytes
/// and code points lie below it. Joining two texts copies neither unless
/// both are short, and cutting a part out of one shares every block and
/// node it keeps, so a text made from others shares what they have in
/// common, in memory and in what history stores for it (`data.md`,
/// *Sharing*; `trace.md`, *Texts*). For a text of `n` runs:
///
/// - finding a code-point position walks down the tree, then through one
///   run, in O(log n + STRIDE): a run whose every code point is ASCII is
///   indexed in constant time, and another through a table of every
///   `STRIDE`th code point's place, made the first time the run is indexed;
/// - finding a byte position costs O(log n);
/// - joining texts whose trees are `h₁` and `h₂` high costs
///   O(|h₁ − h₂| + 1), copying at most 64 bytes, and so `k` joins
///   O(k log n);
/// - [`Text::as_str`] joins the runs of a text of more than one once, in
///   O(bytes), and keeps the result where every copy of the value finds
///   it, so code that needs one contiguous string pays for it once.
#[derive(Clone, Default)]
pub struct Text {
    root: Option<Node<Run>>,
    /// The joined UTF-8 of a text of more than one run, made the first time
    /// it is asked for and shared by every copy of the text; `None` for a
    /// text of one run or none, whose UTF-8 is its run's.
    flat: Option<Arc<OnceLock<Arc<str>>>>,
}

/// The bytes of a shared block from one offset up to another, both between
/// characters: one leaf of a text's tree.
#[derive(Clone, Debug)]
pub struct Run {
    block: Block,
    from: usize,
    to: usize,
    /// How many code points the run holds.
    length: usize,
    /// Where every [`STRIDE`]th code point starts, made the first time a
    /// run that is not all ASCII is indexed and shared by the runs cut from
    /// it.
    places: OnceLock<Places>,
}

/// Where every [`STRIDE`]th code point of a run starts, in bytes from the
/// start of its block, from the run's first code point on, and where a run
/// cut from it starts among them.
#[derive(Clone, Debug)]
struct Places {
    starts: Arc<[usize]>,
    /// How many code points lie between the first the table counts from
    /// and the run's start.
    first: usize,
}

/// What a run of text, or a tree of them, measures: its bytes and its code
/// points.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Span {
    bytes: usize,
    length: usize,
}

impl Measure for Span {
    const EMPTY: Span = Span {
        bytes: 0,
        length: 0,
    };

    fn join(self, other: Span) -> Span {
        Span {
            bytes: self.bytes + other.bytes,
            length: self.length + other.length,
        }
    }
}

/// The most bytes two texts, or the runs where they meet, may hold together
/// for joining them to copy them into one run instead of joining them: a
/// short text is cheaper to copy than to point at.
const SHORT: usize = 64;

/// How many code points apart the places a run that is not all ASCII
/// remembers lie: finding a code point walks at most this many from the
/// nearest.
const STRIDE: usize = 64;

#[cfg(test)]
thread_local! {
    /// How many code points finding positions in runs has walked over on
    /// this thread, so a test can bound the work slicing does.
    pub(crate) static WALKED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

/// Counts `count` code points walked over, in tests.
fn walked(count: usize) {
    #[cfg(test)]
    WALKED.with(|walked| walked.set(walked.get() + count));
    #[cfg(not(test))]
    let _ = count;
}

impl Run {
    /// Returns the run of `block`'s bytes from `from` up to `to`, which fall
    /// between characters and hold `length` code points.
    fn new(block: Block, from: usize, to: usize, length: usize) -> Run {
        Run {
            block,
            from,
            to,
            length,
            places: OnceLock::new(),
        }
    }

    /// Returns the run of all of `utf8`.
    fn whole(utf8: Arc<str>) -> Run {
        let length = utf8.chars().count();
        let to = utf8.len();
        Run::new(Block(utf8), 0, to, length)
    }

    /// Returns the block the run is a window onto.
    pub fn block(&self) -> &Block {
        &self.block
    }

    /// Returns where the run begins in its block, in bytes.
    pub fn from(&self) -> usize {
        self.from
    }

    /// Returns where the run ends in its block, in bytes.
    pub fn to(&self) -> usize {
        self.to
    }

    /// Returns the run's UTF-8.
    pub fn as_str(&self) -> &str {
        &self.block.0[self.from..self.to]
    }

    /// Returns what the run measures.
    pub(crate) fn span(&self) -> Span {
        Span {
            bytes: self.to - self.from,
            length: self.length,
        }
    }

    /// Returns the run of this run's bytes from `from` up to `to`, offsets
    /// from its start between characters, which hold `length` code points
    /// after `skipped` of this run's; it shares this run's places.
    fn piece(&self, from: usize, to: usize, skipped: usize, length: usize) -> Run {
        let places = self.places.get().map(|places| Places {
            starts: Arc::clone(&places.starts),
            first: places.first + skipped,
        });
        Run {
            block: self.block.clone(),
            from: self.from + from,
            to: self.from + to,
            length,
            places: places.map_or_else(OnceLock::new, OnceLock::from),
        }
    }

    /// Returns where code point `position` starts, in bytes from the run's
    /// start; the run's byte length when `position` is its length.
    fn offset(&self, position: usize) -> usize {
        let text = self.as_str();
        if self.length == text.len() {
            return position;
        }
        let places = self.places.get_or_init(|| {
            walked(self.length);
            Places {
                starts: text
                    .char_indices()
                    .step_by(STRIDE)
                    .map(|(at, _)| self.from + at)
                    .collect(),
                first: 0,
            }
        });
        let at = places.first + position;
        let Some(&near) = places.starts.get(at / STRIDE) else {
            return text.len();
        };
        walked(at % STRIDE);
        let block = self.block.as_str();
        block[near..]
            .char_indices()
            .nth(at % STRIDE)
            .map_or(self.to, |(found, _)| near + found)
            - self.from
    }
}

/// Counting a text's positions in bytes: a cut must fall between
/// characters.
struct ByByte;

impl Along<Run> for ByByte {
    fn node(&self, tree: &Node<Run>) -> usize {
        tree.measure().bytes
    }

    fn item(&self, run: &Run) -> usize {
        run.span().bytes
    }

    fn cut(&self, run: &Run, at: usize) -> Option<(Run, Run)> {
        let length = run.as_str().get(..at)?.chars().count();
        Some((
            run.piece(0, at, 0, length),
            run.piece(at, run.span().bytes, length, run.length - length),
        ))
    }
}

/// Counting a text's positions in code points.
struct ByCodePoint;

impl Along<Run> for ByCodePoint {
    fn node(&self, tree: &Node<Run>) -> usize {
        tree.measure().length
    }

    fn item(&self, run: &Run) -> usize {
        run.span().length
    }

    fn cut(&self, run: &Run, at: usize) -> Option<(Run, Run)> {
        let middle = run.offset(at);
        Some((
            run.piece(0, middle, 0, at),
            run.piece(middle, run.span().bytes, at, run.length - at),
        ))
    }
}

impl Text {
    /// Returns the text holding exactly `code_points`.
    pub fn new(code_points: &str) -> Self {
        Text::whole(Arc::from(code_points))
    }

    /// Returns the text of all of `utf8`.
    fn whole(utf8: Arc<str>) -> Self {
        Text::of_run(Run::whole(utf8))
    }

    /// Returns the text of `run`, or the empty text when it holds nothing.
    fn of_run(run: Run) -> Self {
        Text::of((run.from < run.to).then(|| tree::leaf(vec![run])))
    }

    /// Returns the text of the runs below `root`.
    fn of(root: Option<Node<Run>>) -> Self {
        let flat = root
            .as_ref()
            .is_some_and(|root| root.len() > 1)
            .then(|| Arc::new(OnceLock::new()));
        Text { root, flat }
    }

    /// Returns the tree of the text's runs, or `None` when it holds none.
    pub fn root(&self) -> Option<&Node<Run>> {
        self.root.as_ref()
    }

    /// Returns the text's one run, when it is made of exactly one.
    pub fn run(&self) -> Option<&Run> {
        match self.root.as_ref()?.shape() {
            Shape::Leaf([run]) => Some(run),
            Shape::Leaf(_) | Shape::Branch(..) => None,
        }
    }

    /// Returns what the text measures.
    fn span(&self) -> Span {
        self.root.as_ref().map_or(Span::EMPTY, Node::measure)
    }

    /// Returns the text's UTF-8.
    pub fn as_str(&self) -> &str {
        match (&self.flat, self.run()) {
            (Some(flat), _) => self.flat(flat),
            (None, Some(run)) => run.as_str(),
            (None, None) => "",
        }
    }

    /// The UTF-8 of the text's runs joined, made once into `flat`.
    fn flat<'a>(&self, flat: &'a OnceLock<Arc<str>>) -> &'a Arc<str> {
        flat.get_or_init(|| Arc::from(self.blocks().collect::<String>()))
    }

    /// Returns the text's UTF-8 as a shared string: the block itself when the
    /// text is a whole block, and otherwise its UTF-8, made once when the
    /// text has more than one run.
    pub fn to_shared(&self) -> Arc<str> {
        match (&self.flat, self.run()) {
            (Some(flat), _) => Arc::clone(self.flat(flat)),
            (None, Some(run)) if run.from == 0 && run.to == run.block.len() => {
                Arc::clone(&run.block.0)
            }
            (None, Some(run)) => Arc::from(run.as_str()),
            (None, None) => Arc::from(""),
        }
    }

    /// Returns the blocks of UTF-8 the text is made of, in order.
    pub fn blocks(&self) -> impl Iterator<Item = &str> {
        let count = self.root.as_ref().map_or(0, Node::len);
        tree::Iter::new(self.root.as_ref(), 0, count).map(Run::as_str)
    }

    /// Returns how many code points the text holds.
    pub fn len(&self) -> usize {
        self.span().length
    }

    /// Returns whether the text holds none.
    pub fn is_empty(&self) -> bool {
        self.root.is_none()
    }

    /// Returns how many bytes the text's UTF-8 takes.
    pub fn byte_len(&self) -> usize {
        self.span().bytes
    }

    /// Returns the run of `block`'s bytes from `from` up to `to`, sharing
    /// the block.
    ///
    /// Counting the run's code points costs time linear in its length.
    ///
    /// # Errors
    ///
    /// [`StructureError::Run`] unless `from ≤ to ≤ block.len()` and both
    /// fall between characters.
    pub fn of_block(block: Block, from: usize, to: usize) -> Result<Text, StructureError> {
        let length = block
            .0
            .get(from..to)
            .ok_or(StructureError::Run)?
            .chars()
            .count();
        Ok(Text::of_run(Run::new(block, from, to, length)))
    }

    /// Returns `left`'s code points, then `right`'s, keeping both texts as
    /// they are, however short.
    ///
    /// [`Text::concat`] copies two short texts into one run; this never
    /// copies, so a text rebuilt from history shares every run and node it
    /// was rebuilt from. An empty half is no part of the tree, so joining one
    /// returns the other. The two trees are joined as [`Node::branch`] joins
    /// any two, keeping the result balanced.
    pub fn join_shared(left: Text, right: Text) -> Text {
        match (left.root, right.root) {
            (Some(left), Some(right)) => Text::of(Some(Node::branch(left, right))),
            (left, right) => Text::of(left.or(right)),
        }
    }

    /// Returns the bytes of the text from `from` up to `to`, sharing every
    /// block and node it keeps.
    ///
    /// # Errors
    ///
    /// [`StructureError::Run`] unless `from ≤ to ≤` the text's byte length
    /// and both fall between characters.
    pub fn byte_window(&self, from: usize, to: usize) -> Result<Text, StructureError> {
        if from > to || to > self.byte_len() {
            return Err(StructureError::Run);
        }
        self.part(from, to, &ByByte).ok_or(StructureError::Run)
    }

    /// What tells this text apart from every other text alive: its tree's
    /// root, and 0 for the empty text.
    pub(crate) fn id(&self) -> usize {
        self.root.as_ref().map_or(0, Node::id)
    }

    /// Returns `self + other`, sharing both.
    ///
    /// Two trees of at most 64 bytes together that the join meets,
    /// the two texts themselves or a subtree of the higher and the lower
    /// where it lands, are copied into one run; the rest of either is shared.
    #[must_use]
    pub fn concat(&self, other: &Text) -> Text {
        let (Some(left), Some(right)) = (&self.root, &other.root) else {
            return if other.is_empty() {
                self.clone()
            } else {
                other.clone()
            };
        };
        let short = |left: &Node<Run>, right: &Node<Run>| {
            (left.measure().bytes + right.measure().bytes <= SHORT).then(|| {
                let copied = format!("{}{}", Text::from(left.clone()), Text::from(right.clone()));
                tree::leaf(vec![Run::whole(Arc::from(copied))])
            })
        };
        Text::of(Some(tree::join_with(left.clone(), right.clone(), &short)))
    }

    /// Returns the code points from `start` up to, not including, `end`, or
    /// `None` when `0 ≤ start ≤ end ≤ length` does not hold.
    pub fn slice(&self, start: &Int, end: &Int) -> Option<Text> {
        let start = start.to_index()?;
        let end = end.to_index()?;
        if start > end || end > self.len() {
            return None;
        }
        self.part(start, end, &ByCodePoint)
    }

    /// Returns what lies from position `start` up to `end`, counted `along`
    /// the text and within it, sharing every block and node it keeps; or
    /// `None` when a run cannot be cut at either.
    fn part(&self, start: usize, end: usize, along: &impl Along<Run>) -> Option<Text> {
        let Some(root) = &self.root else {
            return Some(Text::default());
        };
        if start == 0 && end == along.node(root) {
            return Some(self.clone());
        }
        let (_, rest) = tree::cut(root.clone(), start, along)?;
        let Some(rest) = rest else {
            return Some(Text::default());
        };
        Some(Text::of(tree::cut(rest, end - start, along)?.0))
    }

    /// Returns the code-point index of the first occurrence of `needle` at or
    /// after code point `from`, or `None` when there is none or `from` lies
    /// past the end. The empty text occurs at every index up to the length.
    pub fn find_from(&self, needle: &Text, from: &Int) -> Option<usize> {
        let from = from.to_index()?;
        if from > self.len() {
            return None;
        }
        // A text keeps its joined UTF-8 once made, so finding again in the
        // same text, as `split` does, searches the same string.
        let start = self.part(0, from, &ByCodePoint)?.byte_len();
        let rest = &self.as_str()[start..];
        let at = rest.find(needle.as_str())?;
        Some(from + rest[..at].chars().count())
    }

    /// Returns each code point as a one-code-point text, in order.
    pub fn code_points(&self) -> Vec<Text> {
        self.blocks()
            .flat_map(str::chars)
            .map(|code_point| Text::new(code_point.encode_utf8(&mut [0; 4])))
            .collect()
    }

    /// Returns each extended grapheme cluster, in order (`text.graphemes`).
    pub fn graphemes(&self) -> Vec<Text> {
        self.as_str().graphemes(true).map(Text::new).collect()
    }

    /// Returns the text in Unicode normalization form C (`text.normalize`).
    #[must_use]
    pub fn normalize(&self) -> Text {
        Text::from(self.blocks().flat_map(str::chars).nfc().collect::<String>())
    }

    /// Returns the text under Unicode's default, locale-independent full
    /// lowercase mapping, with its one conditional rule, `Final_Sigma`: a
    /// capital sigma that ends a word lowercases to the final form
    /// (`text.lowercase`).
    #[must_use]
    pub fn lowercase(&self) -> Text {
        let utf8 = self.as_str();
        let mut out = String::with_capacity(utf8.len());
        for (at, code_point) in utf8.char_indices() {
            if code_point == CAPITAL_SIGMA
                && after_a_cased_letter(&utf8[..at])
                && !before_a_cased_letter(&utf8[at + CAPITAL_SIGMA.len_utf8()..])
            {
                out.push(FINAL_SIGMA);
            } else {
                push_mapped(
                    &mut out,
                    code_point,
                    &unicode_case_mapping::to_lowercase(code_point),
                );
            }
        }
        Text::from(out)
    }

    /// Returns the text under Unicode's default, locale-independent full
    /// uppercase mapping, which has no conditional rule (`text.uppercase`).
    #[must_use]
    pub fn uppercase(&self) -> Text {
        let mut out = String::with_capacity(self.byte_len());
        for code_point in self.blocks().flat_map(str::chars) {
            push_mapped(
                &mut out,
                code_point,
                &unicode_case_mapping::to_uppercase(code_point),
            );
        }
        Text::from(out)
    }

    /// Returns the block a run is a window onto, for tests.
    #[cfg(test)]
    pub(crate) fn block_of(&self) -> Option<&Arc<str>> {
        self.run().map(|run| &run.block.0)
    }

    /// Returns the text's UTF-8 encoding.
    pub fn to_bytes(&self) -> Bytes {
        Bytes::new(self.as_str().as_bytes())
    }
}

/// A block of UTF-8 that runs of text are windows onto, shared between
/// them.
#[derive(Clone, Debug)]
pub struct Block(Arc<str>);

impl Block {
    /// Returns the block of `utf8`.
    pub fn new(utf8: Arc<str>) -> Block {
        Block(utf8)
    }

    /// Returns what tells this block apart from every other block alive:
    /// two handles answer alike exactly when they share one block. The
    /// answer means something only while a handle to it is kept.
    pub fn id(&self) -> usize {
        Arc::as_ptr(&self.0).cast::<u8>().addr()
    }

    /// Returns the block's UTF-8.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Returns how many bytes the block holds.
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns whether the block holds none.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

impl PartialEq for Text {
    fn eq(&self, other: &Text) -> bool {
        self.id() == other.id()
            || (self.byte_len() == other.byte_len() && self.as_str() == other.as_str())
    }
}

impl Eq for Text {}

impl PartialOrd for Text {
    fn partial_cmp(&self, other: &Text) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Text {
    fn cmp(&self, other: &Text) -> std::cmp::Ordering {
        if self.id() == other.id() {
            return std::cmp::Ordering::Equal;
        }
        self.as_str().cmp(other.as_str())
    }
}

impl From<String> for Text {
    fn from(code_points: String) -> Self {
        Text::whole(Arc::from(code_points))
    }
}

impl From<Node<Run>> for Text {
    fn from(root: Node<Run>) -> Self {
        Text::of(Some(root))
    }
}

impl fmt::Display for Text {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.blocks().try_for_each(|block| f.write_str(block))
    }
}

impl fmt::Debug for Text {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self.as_str(), f)
    }
}

/// A finite sequence of bytes: raw, unnormalized, ordered lexicographically by
/// unsigned byte value with a proper prefix first.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Bytes(Arc<[u8]>);

impl Bytes {
    /// Returns the bytes `contents` holds.
    pub fn new(contents: &[u8]) -> Self {
        Bytes(Arc::from(contents))
    }

    /// Returns the bytes.
    pub fn as_slice(&self) -> &[u8] {
        &self.0
    }

    /// What tells these bytes apart from every other bytes value alive.
    pub(crate) fn id(&self) -> usize {
        Arc::as_ptr(&self.0).cast::<u8>().addr()
    }

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

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

    /// Returns the text these bytes encode as UTF-8, or `None` when they are
    /// not valid UTF-8. No replacement character is ever substituted.
    pub fn to_text(&self) -> Option<Text> {
        std::str::from_utf8(&self.0).ok().map(Text::new)
    }

    /// Returns the bytes in standard base64 with padding, which is also their
    /// text form.
    pub fn to_base64(&self) -> String {
        const ALPHABET: &[u8; 64] =
            b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        let mut out = String::with_capacity(self.0.len().div_ceil(3) * 4);
        for chunk in self.0.chunks(3) {
            let first = chunk[0];
            let second = chunk.get(1).copied();
            let third = chunk.get(2).copied();
            // The three bytes occupy disjoint bits, so adding places them.
            let group = (u32::from(first) << 16)
                + (u32::from(second.unwrap_or(0)) << 8)
                + u32::from(third.unwrap_or(0));
            let sextet = |shift: u32| {
                char::from(ALPHABET[usize::from(((group >> shift) & 0x3f).to_le_bytes()[0])])
            };
            out.push(sextet(18));
            out.push(sextet(12));
            out.push(second.map_or('=', |_| sextet(6)));
            out.push(third.map_or('=', |_| sextet(0)));
        }
        out
    }
}

impl From<Vec<u8>> for Bytes {
    fn from(contents: Vec<u8>) -> Self {
        Bytes(Arc::from(contents))
    }
}

impl fmt::Debug for Bytes {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "bytes({})", self.to_base64())
    }
}