flow-lang-value 0.1.0

The Flow runtime value model: data values, their equality, order and text, and the operations std's built-in types declare.
Documentation
//! `Text` and `Bytes` (`data.md`, *Text* and *Bytes*).

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

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

use crate::int::Int;

/// The Unicode version normalization, case mapping, grapheme segmentation and
/// a `Regex`'s classes 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 the
/// regex classes — 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 the same
/// `regex-syntax` tables a `Regex`'s `\p{...}` classes read.
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 the derived order over the stored bytes is `data.md`'s
/// lexicographic order by code point, with a proper prefix first.
///
/// The code-point count is taken once, when the text is built. Text whose
/// every code point is ASCII is indexed in constant time; other text finds a
/// position by walking it, in time linear in the position.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Text {
    utf8: Arc<str>,
    length: usize,
}

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

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

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

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

    /// Returns `self ++ other`.
    #[must_use]
    pub fn concat(&self, other: &Text) -> Text {
        let mut joined = String::from(&*self.utf8);
        joined.push_str(&other.utf8);
        Text {
            utf8: Arc::from(joined),
            length: self.length + other.length,
        }
    }

    /// 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.length {
            return None;
        }
        let from = self.byte_offset(start);
        let to = self.byte_offset(end);
        Some(Text {
            utf8: Arc::from(&self.utf8[from..to]),
            length: end - start,
        })
    }

    /// Returns each code point as a one-code-point text, in order.
    pub fn code_points(&self) -> Vec<Text> {
        let mut buffer = [0; 4];
        self.utf8
            .chars()
            .map(|code_point| Text {
                utf8: Arc::from(&*code_point.encode_utf8(&mut buffer)),
                length: 1,
            })
            .collect()
    }

    /// Returns each extended grapheme cluster, in order (`text.graphemes`).
    pub fn graphemes(&self) -> Vec<Text> {
        self.utf8.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.utf8.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 mut out = String::with_capacity(self.utf8.len());
        for (at, code_point) in self.utf8.char_indices() {
            if code_point == CAPITAL_SIGMA
                && after_a_cased_letter(&self.utf8[..at])
                && !before_a_cased_letter(&self.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.utf8.len());
        for code_point in self.utf8.chars() {
            push_mapped(
                &mut out,
                code_point,
                &unicode_case_mapping::to_uppercase(code_point),
            );
        }
        Text::from(out)
    }

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

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

    /// Returns the byte offset of the code point at `position`, where
    /// `position ≤ length`.
    fn byte_offset(&self, position: usize) -> usize {
        if self.length == self.utf8.len() {
            // Every code point is one byte.
            return position;
        }
        self.utf8
            .char_indices()
            .nth(position)
            .map_or(self.utf8.len(), |(offset, _)| offset)
    }
}

impl From<String> for Text {
    fn from(code_points: String) -> Self {
        let length = code_points.chars().count();
        Text {
            utf8: Arc::from(code_points),
            length,
        }
    }
}

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

impl fmt::Debug for Text {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&*self.utf8, 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
    }

    /// 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[((group >> shift) & 0x3f) as usize]);
            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())
    }
}