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};
5
6use regex_syntax::hir::{Class, HirKind};
7use unicode_normalization::UnicodeNormalization;
8use unicode_segmentation::UnicodeSegmentation;
9
10use crate::int::Int;
11
12/// The Unicode version normalization, case mapping, grapheme segmentation and
13/// a `Regex`'s classes use (`data.md`, *Text*).
14///
15/// Every table comes from a crate pinned exactly in the workspace manifest —
16/// `unicode-normalization`, `unicode-segmentation`, `unicode-case-mapping`, and
17/// `regex-syntax` for the `Cased` and `Case_Ignorable` properties and the
18/// regex classes — and none from the Rust toolchain, whose `char` methods
19/// follow whatever Unicode the compiler shipped with. A test holds each crate
20/// to this one version, so changing it is a change of std, never a drift
21/// between builds.
22pub const UNICODE_VERSION: (u8, u8, u8) = (16, 0, 0);
23
24/// GREEK CAPITAL LETTER SIGMA, the one code point whose default lowercase
25/// mapping reads its context.
26const CAPITAL_SIGMA: char = '\u{3a3}';
27
28/// GREEK SMALL LETTER FINAL SIGMA, what [`CAPITAL_SIGMA`] lowercases to where
29/// the `Final_Sigma` condition holds.
30const FINAL_SIGMA: char = '\u{3c2}';
31
32/// The code points with Unicode's `Cased` property.
33static CASED: LazyLock<Vec<(char, char)>> = LazyLock::new(|| property("Cased"));
34
35/// The code points with Unicode's `Case_Ignorable` property.
36static CASE_IGNORABLE: LazyLock<Vec<(char, char)>> = LazyLock::new(|| property("Case_Ignorable"));
37
38/// Returns the ranges of the binary Unicode property `name`, from the same
39/// `regex-syntax` tables a `Regex`'s `\p{...}` classes read.
40fn property(name: &str) -> Vec<(char, char)> {
41    let class = regex_syntax::Parser::new()
42        .parse(&format!(r"\p{{{name}}}"))
43        .map(regex_syntax::hir::Hir::into_kind);
44    match class {
45        Ok(HirKind::Class(Class::Unicode(class))) => class
46            .ranges()
47            .iter()
48            .map(|range| (range.start(), range.end()))
49            .collect(),
50        _ => unreachable!("regex-syntax knows the binary property {name}"),
51    }
52}
53
54/// Returns whether `code_point` lies in one of `ranges`, which are sorted and
55/// disjoint.
56fn has(ranges: &[(char, char)], code_point: char) -> bool {
57    ranges
58        .binary_search_by(|&(start, end)| {
59            if end < code_point {
60                std::cmp::Ordering::Less
61            } else if start > code_point {
62                std::cmp::Ordering::Greater
63            } else {
64                std::cmp::Ordering::Equal
65            }
66        })
67        .is_ok()
68}
69
70/// Returns whether a cased letter, then any case-ignorable code points, lead
71/// up to the end of `before`, the `Final_Sigma` condition's first half
72/// (Unicode, ch. 3, *Default Case Conversion*, table 3-17).
73fn after_a_cased_letter(before: &str) -> bool {
74    for code_point in before.chars().rev() {
75        if has(&CASED, code_point) {
76            return true;
77        }
78        if !has(&CASE_IGNORABLE, code_point) {
79            return false;
80        }
81    }
82    false
83}
84
85/// Returns whether any case-ignorable code points, then a cased letter, open
86/// `after`; `Final_Sigma` requires that this not hold.
87fn before_a_cased_letter(after: &str) -> bool {
88    for code_point in after.chars() {
89        if has(&CASED, code_point) {
90            return true;
91        }
92        if !has(&CASE_IGNORABLE, code_point) {
93            return false;
94        }
95    }
96    false
97}
98
99/// Appends `code_point`'s full case mapping, `mapped`: the code points before
100/// the first zero, or `code_point` itself when there are none.
101fn push_mapped(out: &mut String, code_point: char, mapped: &[u32]) {
102    if mapped[0] == 0 {
103        out.push(code_point);
104    } else {
105        out.extend(
106            mapped
107                .iter()
108                .take_while(|&&unit| unit != 0)
109                .filter_map(|&unit| char::from_u32(unit)),
110        );
111    }
112}
113
114/// A finite sequence of Unicode code points, stored as UTF-8.
115///
116/// Length, indexing and slicing count code points. Nothing is normalized:
117/// a `Text` is exactly the code points that built it, and equality and order
118/// compare code points. UTF-8 preserves code-point order under byte
119/// comparison, so the derived order over the stored bytes is `data.md`'s
120/// lexicographic order by code point, with a proper prefix first.
121///
122/// The code-point count is taken once, when the text is built. Text whose
123/// every code point is ASCII is indexed in constant time; other text finds a
124/// position by walking it, in time linear in the position.
125#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
126pub struct Text {
127    utf8: Arc<str>,
128    length: usize,
129}
130
131impl Text {
132    /// Returns the text holding exactly `code_points`.
133    pub fn new(code_points: &str) -> Self {
134        Text {
135            utf8: Arc::from(code_points),
136            length: code_points.chars().count(),
137        }
138    }
139
140    /// Returns the text's UTF-8.
141    pub fn as_str(&self) -> &str {
142        &self.utf8
143    }
144
145    /// Returns how many code points the text holds.
146    pub fn len(&self) -> usize {
147        self.length
148    }
149
150    /// Returns whether the text holds none.
151    pub fn is_empty(&self) -> bool {
152        self.length == 0
153    }
154
155    /// Returns `self ++ other`.
156    #[must_use]
157    pub fn concat(&self, other: &Text) -> Text {
158        let mut joined = String::from(&*self.utf8);
159        joined.push_str(&other.utf8);
160        Text {
161            utf8: Arc::from(joined),
162            length: self.length + other.length,
163        }
164    }
165
166    /// Returns the code points from `start` up to, not including, `end`, or
167    /// `None` when `0 ≤ start ≤ end ≤ length` does not hold.
168    pub fn slice(&self, start: &Int, end: &Int) -> Option<Text> {
169        let start = start.to_index()?;
170        let end = end.to_index()?;
171        if start > end || end > self.length {
172            return None;
173        }
174        let from = self.byte_offset(start);
175        let to = self.byte_offset(end);
176        Some(Text {
177            utf8: Arc::from(&self.utf8[from..to]),
178            length: end - start,
179        })
180    }
181
182    /// Returns each code point as a one-code-point text, in order.
183    pub fn code_points(&self) -> Vec<Text> {
184        let mut buffer = [0; 4];
185        self.utf8
186            .chars()
187            .map(|code_point| Text {
188                utf8: Arc::from(&*code_point.encode_utf8(&mut buffer)),
189                length: 1,
190            })
191            .collect()
192    }
193
194    /// Returns each extended grapheme cluster, in order (`text.graphemes`).
195    pub fn graphemes(&self) -> Vec<Text> {
196        self.utf8.graphemes(true).map(Text::new).collect()
197    }
198
199    /// Returns the text in Unicode normalization form C (`text.normalize`).
200    #[must_use]
201    pub fn normalize(&self) -> Text {
202        Text::from(self.utf8.nfc().collect::<String>())
203    }
204
205    /// Returns the text under Unicode's default, locale-independent full
206    /// lowercase mapping, with its one conditional rule, `Final_Sigma`: a
207    /// capital sigma that ends a word lowercases to the final form
208    /// (`text.lowercase`).
209    #[must_use]
210    pub fn lowercase(&self) -> Text {
211        let mut out = String::with_capacity(self.utf8.len());
212        for (at, code_point) in self.utf8.char_indices() {
213            if code_point == CAPITAL_SIGMA
214                && after_a_cased_letter(&self.utf8[..at])
215                && !before_a_cased_letter(&self.utf8[at + CAPITAL_SIGMA.len_utf8()..])
216            {
217                out.push(FINAL_SIGMA);
218            } else {
219                push_mapped(
220                    &mut out,
221                    code_point,
222                    &unicode_case_mapping::to_lowercase(code_point),
223                );
224            }
225        }
226        Text::from(out)
227    }
228
229    /// Returns the text under Unicode's default, locale-independent full
230    /// uppercase mapping, which has no conditional rule (`text.uppercase`).
231    #[must_use]
232    pub fn uppercase(&self) -> Text {
233        let mut out = String::with_capacity(self.utf8.len());
234        for code_point in self.utf8.chars() {
235            push_mapped(
236                &mut out,
237                code_point,
238                &unicode_case_mapping::to_uppercase(code_point),
239            );
240        }
241        Text::from(out)
242    }
243
244    /// Returns how many bytes the text's UTF-8 takes.
245    pub fn byte_len(&self) -> usize {
246        self.utf8.len()
247    }
248
249    /// Returns the text's UTF-8 encoding.
250    pub fn to_bytes(&self) -> Bytes {
251        Bytes::new(self.utf8.as_bytes())
252    }
253
254    /// Returns the byte offset of the code point at `position`, where
255    /// `position ≤ length`.
256    fn byte_offset(&self, position: usize) -> usize {
257        if self.length == self.utf8.len() {
258            // Every code point is one byte.
259            return position;
260        }
261        self.utf8
262            .char_indices()
263            .nth(position)
264            .map_or(self.utf8.len(), |(offset, _)| offset)
265    }
266}
267
268impl From<String> for Text {
269    fn from(code_points: String) -> Self {
270        let length = code_points.chars().count();
271        Text {
272            utf8: Arc::from(code_points),
273            length,
274        }
275    }
276}
277
278impl fmt::Display for Text {
279    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280        f.write_str(&self.utf8)
281    }
282}
283
284impl fmt::Debug for Text {
285    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
286        fmt::Debug::fmt(&*self.utf8, f)
287    }
288}
289
290/// A finite sequence of bytes: raw, unnormalized, ordered lexicographically by
291/// unsigned byte value with a proper prefix first.
292#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
293pub struct Bytes(Arc<[u8]>);
294
295impl Bytes {
296    /// Returns the bytes `contents` holds.
297    pub fn new(contents: &[u8]) -> Self {
298        Bytes(Arc::from(contents))
299    }
300
301    /// Returns the bytes.
302    pub fn as_slice(&self) -> &[u8] {
303        &self.0
304    }
305
306    /// Returns how many bytes there are.
307    pub fn len(&self) -> usize {
308        self.0.len()
309    }
310
311    /// Returns whether there are none.
312    pub fn is_empty(&self) -> bool {
313        self.0.is_empty()
314    }
315
316    /// Returns the text these bytes encode as UTF-8, or `None` when they are
317    /// not valid UTF-8. No replacement character is ever substituted.
318    pub fn to_text(&self) -> Option<Text> {
319        std::str::from_utf8(&self.0).ok().map(Text::new)
320    }
321
322    /// Returns the bytes in standard base64 with padding, which is also their
323    /// text form.
324    pub fn to_base64(&self) -> String {
325        const ALPHABET: &[u8; 64] =
326            b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
327        let mut out = String::with_capacity(self.0.len().div_ceil(3) * 4);
328        for chunk in self.0.chunks(3) {
329            let first = chunk[0];
330            let second = chunk.get(1).copied();
331            let third = chunk.get(2).copied();
332            // The three bytes occupy disjoint bits, so adding places them.
333            let group = (u32::from(first) << 16)
334                + (u32::from(second.unwrap_or(0)) << 8)
335                + u32::from(third.unwrap_or(0));
336            let sextet = |shift: u32| char::from(ALPHABET[((group >> shift) & 0x3f) as usize]);
337            out.push(sextet(18));
338            out.push(sextet(12));
339            out.push(second.map_or('=', |_| sextet(6)));
340            out.push(third.map_or('=', |_| sextet(0)));
341        }
342        out
343    }
344}
345
346impl From<Vec<u8>> for Bytes {
347    fn from(contents: Vec<u8>) -> Self {
348        Bytes(Arc::from(contents))
349    }
350}
351
352impl fmt::Debug for Bytes {
353    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
354        write!(f, "bytes({})", self.to_base64())
355    }
356}