Skip to main content

flow_value/
text.rs

1//! `Text` and `Bytes` (`data.md`, *Text* and *Bytes*).
2
3use std::fmt;
4use std::sync::{Arc, LazyLock, OnceLock};
5
6use regex_syntax::hir::{Class, HirKind};
7use unicode_normalization::UnicodeNormalization;
8use unicode_segmentation::UnicodeSegmentation;
9
10use crate::error::StructureError;
11use crate::int::Int;
12use crate::tree::{self, Along, Measure, Node, Shape};
13
14/// The Unicode version normalization, case mapping and grapheme segmentation
15/// use (`data.md`, *Text*).
16///
17/// Every table comes from a crate pinned exactly in the workspace manifest —
18/// `unicode-normalization`, `unicode-segmentation`, `unicode-case-mapping`, and
19/// `regex-syntax` for the `Cased` and `Case_Ignorable` properties — and none
20/// from the Rust toolchain, whose `char` methods follow whatever Unicode the
21/// compiler shipped with. A test holds each crate to this one version, so
22/// changing it is a change of std, never a drift between builds.
23pub const UNICODE_VERSION: (u8, u8, u8) = (16, 0, 0);
24
25/// GREEK CAPITAL LETTER SIGMA, the one code point whose default lowercase
26/// mapping reads its context.
27const CAPITAL_SIGMA: char = '\u{3a3}';
28
29/// GREEK SMALL LETTER FINAL SIGMA, what [`CAPITAL_SIGMA`] lowercases to where
30/// the `Final_Sigma` condition holds.
31const FINAL_SIGMA: char = '\u{3c2}';
32
33/// The code points with Unicode's `Cased` property.
34static CASED: LazyLock<Vec<(char, char)>> = LazyLock::new(|| property("Cased"));
35
36/// The code points with Unicode's `Case_Ignorable` property.
37static CASE_IGNORABLE: LazyLock<Vec<(char, char)>> = LazyLock::new(|| property("Case_Ignorable"));
38
39/// Returns the ranges of the binary Unicode property `name`, from
40/// `regex-syntax`'s tables.
41fn property(name: &str) -> Vec<(char, char)> {
42    let class = regex_syntax::Parser::new()
43        .parse(&format!(r"\p{{{name}}}"))
44        .map(regex_syntax::hir::Hir::into_kind);
45    match class {
46        Ok(HirKind::Class(Class::Unicode(class))) => class
47            .ranges()
48            .iter()
49            .map(|range| (range.start(), range.end()))
50            .collect(),
51        _ => unreachable!("regex-syntax knows the binary property {name}"),
52    }
53}
54
55/// Returns whether `code_point` lies in one of `ranges`, which are sorted and
56/// disjoint.
57fn has(ranges: &[(char, char)], code_point: char) -> bool {
58    ranges
59        .binary_search_by(|&(start, end)| {
60            if end < code_point {
61                std::cmp::Ordering::Less
62            } else if start > code_point {
63                std::cmp::Ordering::Greater
64            } else {
65                std::cmp::Ordering::Equal
66            }
67        })
68        .is_ok()
69}
70
71/// Returns whether a cased letter, then any case-ignorable code points, lead
72/// up to the end of `before`, the `Final_Sigma` condition's first half
73/// (Unicode, ch. 3, *Default Case Conversion*, table 3-17).
74fn after_a_cased_letter(before: &str) -> bool {
75    for code_point in before.chars().rev() {
76        if has(&CASED, code_point) {
77            return true;
78        }
79        if !has(&CASE_IGNORABLE, code_point) {
80            return false;
81        }
82    }
83    false
84}
85
86/// Returns whether any case-ignorable code points, then a cased letter, open
87/// `after`; `Final_Sigma` requires that this not hold.
88fn before_a_cased_letter(after: &str) -> bool {
89    for code_point in after.chars() {
90        if has(&CASED, code_point) {
91            return true;
92        }
93        if !has(&CASE_IGNORABLE, code_point) {
94            return false;
95        }
96    }
97    false
98}
99
100/// Appends `code_point`'s full case mapping, `mapped`: the code points before
101/// the first zero, or `code_point` itself when there are none.
102fn push_mapped(out: &mut String, code_point: char, mapped: &[u32]) {
103    if mapped[0] == 0 {
104        out.push(code_point);
105    } else {
106        out.extend(
107            mapped
108                .iter()
109                .take_while(|&&unit| unit != 0)
110                .filter_map(|&unit| char::from_u32(unit)),
111        );
112    }
113}
114
115/// A finite sequence of Unicode code points, stored as UTF-8.
116///
117/// Length, indexing and slicing count code points. Nothing is normalized:
118/// a `Text` is exactly the code points that built it, and equality and order
119/// compare code points. UTF-8 preserves code-point order under byte
120/// comparison, so comparing the bytes is `data.md`'s lexicographic order by
121/// code point, with a proper prefix first.
122///
123/// A text is a balanced tree of **runs**, each a window onto a shared block
124/// of UTF-8, kept in the tree every list, dictionary and set keeps its
125/// elements in, each leaf one run and each node recording how many bytes
126/// and code points lie below it. Joining two texts copies neither unless
127/// both are short, and cutting a part out of one shares every block and
128/// node it keeps, so a text made from others shares what they have in
129/// common, in memory and in what history stores for it (`data.md`,
130/// *Sharing*; `trace.md`, *Texts*). For a text of `n` runs:
131///
132/// - finding a code-point position walks down the tree, then through one
133///   run, in O(log n + STRIDE): a run whose every code point is ASCII is
134///   indexed in constant time, and another through a table of every
135///   `STRIDE`th code point's place, made the first time the run is indexed;
136/// - finding a byte position costs O(log n);
137/// - joining texts whose trees are `h₁` and `h₂` high costs
138///   O(|h₁ − h₂| + 1), copying at most 64 bytes, and so `k` joins
139///   O(k log n);
140/// - [`Text::as_str`] joins the runs of a text of more than one once, in
141///   O(bytes), and keeps the result where every copy of the value finds
142///   it, so code that needs one contiguous string pays for it once.
143#[derive(Clone, Default)]
144pub struct Text {
145    root: Option<Node<Run>>,
146    /// The joined UTF-8 of a text of more than one run, made the first time
147    /// it is asked for and shared by every copy of the text; `None` for a
148    /// text of one run or none, whose UTF-8 is its run's.
149    flat: Option<Arc<OnceLock<Arc<str>>>>,
150}
151
152/// The bytes of a shared block from one offset up to another, both between
153/// characters: one leaf of a text's tree.
154#[derive(Clone, Debug)]
155pub struct Run {
156    block: Block,
157    from: usize,
158    to: usize,
159    /// How many code points the run holds.
160    length: usize,
161    /// Where every [`STRIDE`]th code point starts, made the first time a
162    /// run that is not all ASCII is indexed and shared by the runs cut from
163    /// it.
164    places: OnceLock<Places>,
165}
166
167/// Where every [`STRIDE`]th code point of a run starts, in bytes from the
168/// start of its block, from the run's first code point on, and where a run
169/// cut from it starts among them.
170#[derive(Clone, Debug)]
171struct Places {
172    starts: Arc<[usize]>,
173    /// How many code points lie between the first the table counts from
174    /// and the run's start.
175    first: usize,
176}
177
178/// What a run of text, or a tree of them, measures: its bytes and its code
179/// points.
180#[derive(Clone, Copy, PartialEq, Eq, Debug)]
181pub struct Span {
182    bytes: usize,
183    length: usize,
184}
185
186impl Measure for Span {
187    const EMPTY: Span = Span {
188        bytes: 0,
189        length: 0,
190    };
191
192    fn join(self, other: Span) -> Span {
193        Span {
194            bytes: self.bytes + other.bytes,
195            length: self.length + other.length,
196        }
197    }
198}
199
200/// The most bytes two texts, or the runs where they meet, may hold together
201/// for joining them to copy them into one run instead of joining them: a
202/// short text is cheaper to copy than to point at.
203const SHORT: usize = 64;
204
205/// How many code points apart the places a run that is not all ASCII
206/// remembers lie: finding a code point walks at most this many from the
207/// nearest.
208const STRIDE: usize = 64;
209
210#[cfg(test)]
211thread_local! {
212    /// How many code points finding positions in runs has walked over on
213    /// this thread, so a test can bound the work slicing does.
214    pub(crate) static WALKED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
215}
216
217/// Counts `count` code points walked over, in tests.
218fn walked(count: usize) {
219    #[cfg(test)]
220    WALKED.with(|walked| walked.set(walked.get() + count));
221    #[cfg(not(test))]
222    let _ = count;
223}
224
225impl Run {
226    /// Returns the run of `block`'s bytes from `from` up to `to`, which fall
227    /// between characters and hold `length` code points.
228    fn new(block: Block, from: usize, to: usize, length: usize) -> Run {
229        Run {
230            block,
231            from,
232            to,
233            length,
234            places: OnceLock::new(),
235        }
236    }
237
238    /// Returns the run of all of `utf8`.
239    fn whole(utf8: Arc<str>) -> Run {
240        let length = utf8.chars().count();
241        let to = utf8.len();
242        Run::new(Block(utf8), 0, to, length)
243    }
244
245    /// Returns the block the run is a window onto.
246    pub fn block(&self) -> &Block {
247        &self.block
248    }
249
250    /// Returns where the run begins in its block, in bytes.
251    pub fn from(&self) -> usize {
252        self.from
253    }
254
255    /// Returns where the run ends in its block, in bytes.
256    pub fn to(&self) -> usize {
257        self.to
258    }
259
260    /// Returns the run's UTF-8.
261    pub fn as_str(&self) -> &str {
262        &self.block.0[self.from..self.to]
263    }
264
265    /// Returns what the run measures.
266    pub(crate) fn span(&self) -> Span {
267        Span {
268            bytes: self.to - self.from,
269            length: self.length,
270        }
271    }
272
273    /// Returns the run of this run's bytes from `from` up to `to`, offsets
274    /// from its start between characters, which hold `length` code points
275    /// after `skipped` of this run's; it shares this run's places.
276    fn piece(&self, from: usize, to: usize, skipped: usize, length: usize) -> Run {
277        let places = self.places.get().map(|places| Places {
278            starts: Arc::clone(&places.starts),
279            first: places.first + skipped,
280        });
281        Run {
282            block: self.block.clone(),
283            from: self.from + from,
284            to: self.from + to,
285            length,
286            places: places.map_or_else(OnceLock::new, OnceLock::from),
287        }
288    }
289
290    /// Returns where code point `position` starts, in bytes from the run's
291    /// start; the run's byte length when `position` is its length.
292    fn offset(&self, position: usize) -> usize {
293        let text = self.as_str();
294        if self.length == text.len() {
295            return position;
296        }
297        let places = self.places.get_or_init(|| {
298            walked(self.length);
299            Places {
300                starts: text
301                    .char_indices()
302                    .step_by(STRIDE)
303                    .map(|(at, _)| self.from + at)
304                    .collect(),
305                first: 0,
306            }
307        });
308        let at = places.first + position;
309        let Some(&near) = places.starts.get(at / STRIDE) else {
310            return text.len();
311        };
312        walked(at % STRIDE);
313        let block = self.block.as_str();
314        block[near..]
315            .char_indices()
316            .nth(at % STRIDE)
317            .map_or(self.to, |(found, _)| near + found)
318            - self.from
319    }
320}
321
322/// Counting a text's positions in bytes: a cut must fall between
323/// characters.
324struct ByByte;
325
326impl Along<Run> for ByByte {
327    fn node(&self, tree: &Node<Run>) -> usize {
328        tree.measure().bytes
329    }
330
331    fn item(&self, run: &Run) -> usize {
332        run.span().bytes
333    }
334
335    fn cut(&self, run: &Run, at: usize) -> Option<(Run, Run)> {
336        let length = run.as_str().get(..at)?.chars().count();
337        Some((
338            run.piece(0, at, 0, length),
339            run.piece(at, run.span().bytes, length, run.length - length),
340        ))
341    }
342}
343
344/// Counting a text's positions in code points.
345struct ByCodePoint;
346
347impl Along<Run> for ByCodePoint {
348    fn node(&self, tree: &Node<Run>) -> usize {
349        tree.measure().length
350    }
351
352    fn item(&self, run: &Run) -> usize {
353        run.span().length
354    }
355
356    fn cut(&self, run: &Run, at: usize) -> Option<(Run, Run)> {
357        let middle = run.offset(at);
358        Some((
359            run.piece(0, middle, 0, at),
360            run.piece(middle, run.span().bytes, at, run.length - at),
361        ))
362    }
363}
364
365impl Text {
366    /// Returns the text holding exactly `code_points`.
367    pub fn new(code_points: &str) -> Self {
368        Text::whole(Arc::from(code_points))
369    }
370
371    /// Returns the text of all of `utf8`.
372    fn whole(utf8: Arc<str>) -> Self {
373        Text::of_run(Run::whole(utf8))
374    }
375
376    /// Returns the text of `run`, or the empty text when it holds nothing.
377    fn of_run(run: Run) -> Self {
378        Text::of((run.from < run.to).then(|| tree::leaf(vec![run])))
379    }
380
381    /// Returns the text of the runs below `root`.
382    fn of(root: Option<Node<Run>>) -> Self {
383        let flat = root
384            .as_ref()
385            .is_some_and(|root| root.len() > 1)
386            .then(|| Arc::new(OnceLock::new()));
387        Text { root, flat }
388    }
389
390    /// Returns the tree of the text's runs, or `None` when it holds none.
391    pub fn root(&self) -> Option<&Node<Run>> {
392        self.root.as_ref()
393    }
394
395    /// Returns the text's one run, when it is made of exactly one.
396    pub fn run(&self) -> Option<&Run> {
397        match self.root.as_ref()?.shape() {
398            Shape::Leaf([run]) => Some(run),
399            Shape::Leaf(_) | Shape::Branch(..) => None,
400        }
401    }
402
403    /// Returns what the text measures.
404    fn span(&self) -> Span {
405        self.root.as_ref().map_or(Span::EMPTY, Node::measure)
406    }
407
408    /// Returns the text's UTF-8.
409    pub fn as_str(&self) -> &str {
410        match (&self.flat, self.run()) {
411            (Some(flat), _) => self.flat(flat),
412            (None, Some(run)) => run.as_str(),
413            (None, None) => "",
414        }
415    }
416
417    /// The UTF-8 of the text's runs joined, made once into `flat`.
418    fn flat<'a>(&self, flat: &'a OnceLock<Arc<str>>) -> &'a Arc<str> {
419        flat.get_or_init(|| Arc::from(self.blocks().collect::<String>()))
420    }
421
422    /// Returns the text's UTF-8 as a shared string: the block itself when the
423    /// text is a whole block, and otherwise its UTF-8, made once when the
424    /// text has more than one run.
425    pub fn to_shared(&self) -> Arc<str> {
426        match (&self.flat, self.run()) {
427            (Some(flat), _) => Arc::clone(self.flat(flat)),
428            (None, Some(run)) if run.from == 0 && run.to == run.block.len() => {
429                Arc::clone(&run.block.0)
430            }
431            (None, Some(run)) => Arc::from(run.as_str()),
432            (None, None) => Arc::from(""),
433        }
434    }
435
436    /// Returns the blocks of UTF-8 the text is made of, in order.
437    pub fn blocks(&self) -> impl Iterator<Item = &str> {
438        let count = self.root.as_ref().map_or(0, Node::len);
439        tree::Iter::new(self.root.as_ref(), 0, count).map(Run::as_str)
440    }
441
442    /// Returns how many code points the text holds.
443    pub fn len(&self) -> usize {
444        self.span().length
445    }
446
447    /// Returns whether the text holds none.
448    pub fn is_empty(&self) -> bool {
449        self.root.is_none()
450    }
451
452    /// Returns how many bytes the text's UTF-8 takes.
453    pub fn byte_len(&self) -> usize {
454        self.span().bytes
455    }
456
457    /// Returns the run of `block`'s bytes from `from` up to `to`, sharing
458    /// the block.
459    ///
460    /// Counting the run's code points costs time linear in its length.
461    ///
462    /// # Errors
463    ///
464    /// [`StructureError::Run`] unless `from ≤ to ≤ block.len()` and both
465    /// fall between characters.
466    pub fn of_block(block: Block, from: usize, to: usize) -> Result<Text, StructureError> {
467        let length = block
468            .0
469            .get(from..to)
470            .ok_or(StructureError::Run)?
471            .chars()
472            .count();
473        Ok(Text::of_run(Run::new(block, from, to, length)))
474    }
475
476    /// Returns `left`'s code points, then `right`'s, keeping both texts as
477    /// they are, however short.
478    ///
479    /// [`Text::concat`] copies two short texts into one run; this never
480    /// copies, so a text rebuilt from history shares every run and node it
481    /// was rebuilt from. An empty half is no part of the tree, so joining one
482    /// returns the other. The two trees are joined as [`Node::branch`] joins
483    /// any two, keeping the result balanced.
484    pub fn join_shared(left: Text, right: Text) -> Text {
485        match (left.root, right.root) {
486            (Some(left), Some(right)) => Text::of(Some(Node::branch(left, right))),
487            (left, right) => Text::of(left.or(right)),
488        }
489    }
490
491    /// Returns the bytes of the text from `from` up to `to`, sharing every
492    /// block and node it keeps.
493    ///
494    /// # Errors
495    ///
496    /// [`StructureError::Run`] unless `from ≤ to ≤` the text's byte length
497    /// and both fall between characters.
498    pub fn byte_window(&self, from: usize, to: usize) -> Result<Text, StructureError> {
499        if from > to || to > self.byte_len() {
500            return Err(StructureError::Run);
501        }
502        self.part(from, to, &ByByte).ok_or(StructureError::Run)
503    }
504
505    /// What tells this text apart from every other text alive: its tree's
506    /// root, and 0 for the empty text.
507    pub(crate) fn id(&self) -> usize {
508        self.root.as_ref().map_or(0, Node::id)
509    }
510
511    /// Returns `self + other`, sharing both.
512    ///
513    /// Two trees of at most 64 bytes together that the join meets,
514    /// the two texts themselves or a subtree of the higher and the lower
515    /// where it lands, are copied into one run; the rest of either is shared.
516    #[must_use]
517    pub fn concat(&self, other: &Text) -> Text {
518        let (Some(left), Some(right)) = (&self.root, &other.root) else {
519            return if other.is_empty() {
520                self.clone()
521            } else {
522                other.clone()
523            };
524        };
525        let short = |left: &Node<Run>, right: &Node<Run>| {
526            (left.measure().bytes + right.measure().bytes <= SHORT).then(|| {
527                let copied = format!("{}{}", Text::from(left.clone()), Text::from(right.clone()));
528                tree::leaf(vec![Run::whole(Arc::from(copied))])
529            })
530        };
531        Text::of(Some(tree::join_with(left.clone(), right.clone(), &short)))
532    }
533
534    /// Returns the code points from `start` up to, not including, `end`, or
535    /// `None` when `0 ≤ start ≤ end ≤ length` does not hold.
536    pub fn slice(&self, start: &Int, end: &Int) -> Option<Text> {
537        let start = start.to_index()?;
538        let end = end.to_index()?;
539        if start > end || end > self.len() {
540            return None;
541        }
542        self.part(start, end, &ByCodePoint)
543    }
544
545    /// Returns what lies from position `start` up to `end`, counted `along`
546    /// the text and within it, sharing every block and node it keeps; or
547    /// `None` when a run cannot be cut at either.
548    fn part(&self, start: usize, end: usize, along: &impl Along<Run>) -> Option<Text> {
549        let Some(root) = &self.root else {
550            return Some(Text::default());
551        };
552        if start == 0 && end == along.node(root) {
553            return Some(self.clone());
554        }
555        let (_, rest) = tree::cut(root.clone(), start, along)?;
556        let Some(rest) = rest else {
557            return Some(Text::default());
558        };
559        Some(Text::of(tree::cut(rest, end - start, along)?.0))
560    }
561
562    /// Returns the code-point index of the first occurrence of `needle` at or
563    /// after code point `from`, or `None` when there is none or `from` lies
564    /// past the end. The empty text occurs at every index up to the length.
565    pub fn find_from(&self, needle: &Text, from: &Int) -> Option<usize> {
566        let from = from.to_index()?;
567        if from > self.len() {
568            return None;
569        }
570        // A text keeps its joined UTF-8 once made, so finding again in the
571        // same text, as `split` does, searches the same string.
572        let start = self.part(0, from, &ByCodePoint)?.byte_len();
573        let rest = &self.as_str()[start..];
574        let at = rest.find(needle.as_str())?;
575        Some(from + rest[..at].chars().count())
576    }
577
578    /// Returns each code point as a one-code-point text, in order.
579    pub fn code_points(&self) -> Vec<Text> {
580        self.blocks()
581            .flat_map(str::chars)
582            .map(|code_point| Text::new(code_point.encode_utf8(&mut [0; 4])))
583            .collect()
584    }
585
586    /// Returns each extended grapheme cluster, in order (`text.graphemes`).
587    pub fn graphemes(&self) -> Vec<Text> {
588        self.as_str().graphemes(true).map(Text::new).collect()
589    }
590
591    /// Returns the text in Unicode normalization form C (`text.normalize`).
592    #[must_use]
593    pub fn normalize(&self) -> Text {
594        Text::from(self.blocks().flat_map(str::chars).nfc().collect::<String>())
595    }
596
597    /// Returns the text under Unicode's default, locale-independent full
598    /// lowercase mapping, with its one conditional rule, `Final_Sigma`: a
599    /// capital sigma that ends a word lowercases to the final form
600    /// (`text.lowercase`).
601    #[must_use]
602    pub fn lowercase(&self) -> Text {
603        let utf8 = self.as_str();
604        let mut out = String::with_capacity(utf8.len());
605        for (at, code_point) in utf8.char_indices() {
606            if code_point == CAPITAL_SIGMA
607                && after_a_cased_letter(&utf8[..at])
608                && !before_a_cased_letter(&utf8[at + CAPITAL_SIGMA.len_utf8()..])
609            {
610                out.push(FINAL_SIGMA);
611            } else {
612                push_mapped(
613                    &mut out,
614                    code_point,
615                    &unicode_case_mapping::to_lowercase(code_point),
616                );
617            }
618        }
619        Text::from(out)
620    }
621
622    /// Returns the text under Unicode's default, locale-independent full
623    /// uppercase mapping, which has no conditional rule (`text.uppercase`).
624    #[must_use]
625    pub fn uppercase(&self) -> Text {
626        let mut out = String::with_capacity(self.byte_len());
627        for code_point in self.blocks().flat_map(str::chars) {
628            push_mapped(
629                &mut out,
630                code_point,
631                &unicode_case_mapping::to_uppercase(code_point),
632            );
633        }
634        Text::from(out)
635    }
636
637    /// Returns the block a run is a window onto, for tests.
638    #[cfg(test)]
639    pub(crate) fn block_of(&self) -> Option<&Arc<str>> {
640        self.run().map(|run| &run.block.0)
641    }
642
643    /// Returns the text's UTF-8 encoding.
644    pub fn to_bytes(&self) -> Bytes {
645        Bytes::new(self.as_str().as_bytes())
646    }
647}
648
649/// A block of UTF-8 that runs of text are windows onto, shared between
650/// them.
651#[derive(Clone, Debug)]
652pub struct Block(Arc<str>);
653
654impl Block {
655    /// Returns the block of `utf8`.
656    pub fn new(utf8: Arc<str>) -> Block {
657        Block(utf8)
658    }
659
660    /// Returns what tells this block apart from every other block alive:
661    /// two handles answer alike exactly when they share one block. The
662    /// answer means something only while a handle to it is kept.
663    pub fn id(&self) -> usize {
664        Arc::as_ptr(&self.0).cast::<u8>().addr()
665    }
666
667    /// Returns the block's UTF-8.
668    pub fn as_str(&self) -> &str {
669        &self.0
670    }
671
672    /// Returns how many bytes the block holds.
673    pub fn len(&self) -> usize {
674        self.0.len()
675    }
676
677    /// Returns whether the block holds none.
678    pub fn is_empty(&self) -> bool {
679        self.0.is_empty()
680    }
681}
682
683impl PartialEq for Text {
684    fn eq(&self, other: &Text) -> bool {
685        self.id() == other.id()
686            || (self.byte_len() == other.byte_len() && self.as_str() == other.as_str())
687    }
688}
689
690impl Eq for Text {}
691
692impl PartialOrd for Text {
693    fn partial_cmp(&self, other: &Text) -> Option<std::cmp::Ordering> {
694        Some(self.cmp(other))
695    }
696}
697
698impl Ord for Text {
699    fn cmp(&self, other: &Text) -> std::cmp::Ordering {
700        if self.id() == other.id() {
701            return std::cmp::Ordering::Equal;
702        }
703        self.as_str().cmp(other.as_str())
704    }
705}
706
707impl From<String> for Text {
708    fn from(code_points: String) -> Self {
709        Text::whole(Arc::from(code_points))
710    }
711}
712
713impl From<Node<Run>> for Text {
714    fn from(root: Node<Run>) -> Self {
715        Text::of(Some(root))
716    }
717}
718
719impl fmt::Display for Text {
720    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
721        self.blocks().try_for_each(|block| f.write_str(block))
722    }
723}
724
725impl fmt::Debug for Text {
726    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
727        fmt::Debug::fmt(self.as_str(), f)
728    }
729}
730
731/// A finite sequence of bytes: raw, unnormalized, ordered lexicographically by
732/// unsigned byte value with a proper prefix first.
733#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
734pub struct Bytes(Arc<[u8]>);
735
736impl Bytes {
737    /// Returns the bytes `contents` holds.
738    pub fn new(contents: &[u8]) -> Self {
739        Bytes(Arc::from(contents))
740    }
741
742    /// Returns the bytes.
743    pub fn as_slice(&self) -> &[u8] {
744        &self.0
745    }
746
747    /// What tells these bytes apart from every other bytes value alive.
748    pub(crate) fn id(&self) -> usize {
749        Arc::as_ptr(&self.0).cast::<u8>().addr()
750    }
751
752    /// Returns how many bytes there are.
753    pub fn len(&self) -> usize {
754        self.0.len()
755    }
756
757    /// Returns whether there are none.
758    pub fn is_empty(&self) -> bool {
759        self.0.is_empty()
760    }
761
762    /// Returns the text these bytes encode as UTF-8, or `None` when they are
763    /// not valid UTF-8. No replacement character is ever substituted.
764    pub fn to_text(&self) -> Option<Text> {
765        std::str::from_utf8(&self.0).ok().map(Text::new)
766    }
767
768    /// Returns the bytes in standard base64 with padding, which is also their
769    /// text form.
770    pub fn to_base64(&self) -> String {
771        const ALPHABET: &[u8; 64] =
772            b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
773        let mut out = String::with_capacity(self.0.len().div_ceil(3) * 4);
774        for chunk in self.0.chunks(3) {
775            let first = chunk[0];
776            let second = chunk.get(1).copied();
777            let third = chunk.get(2).copied();
778            // The three bytes occupy disjoint bits, so adding places them.
779            let group = (u32::from(first) << 16)
780                + (u32::from(second.unwrap_or(0)) << 8)
781                + u32::from(third.unwrap_or(0));
782            let sextet = |shift: u32| {
783                char::from(ALPHABET[usize::from(((group >> shift) & 0x3f).to_le_bytes()[0])])
784            };
785            out.push(sextet(18));
786            out.push(sextet(12));
787            out.push(second.map_or('=', |_| sextet(6)));
788            out.push(third.map_or('=', |_| sextet(0)));
789        }
790        out
791    }
792}
793
794impl From<Vec<u8>> for Bytes {
795    fn from(contents: Vec<u8>) -> Self {
796        Bytes(Arc::from(contents))
797    }
798}
799
800impl fmt::Debug for Bytes {
801    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
802        write!(f, "bytes({})", self.to_base64())
803    }
804}