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

mod common;

use common::*;
use flow_value::{Bytes, Int, Text, Value};

fn slice(text: &str, start: i64, end: i64) -> Option<String> {
    Text::new(text)
        .slice(&Int::from(start), &Int::from(end))
        .map(|part| part.as_str().to_owned())
}

#[test]
fn text_is_counted_in_code_points_not_bytes() {
    assert_eq!(Text::new("abc").len(), 3);
    assert_eq!(Text::new("héllo").len(), 5);
    assert_eq!(Text::new("日本語").len(), 3);
    assert_eq!(Text::new("👋🏽").len(), 2, "a grapheme of two code points");
    assert_eq!(Text::from("e\u{301}".to_owned()).len(), 2);
    assert_eq!(Text::new("").len(), 0);
    assert!(Text::new("").is_empty());
    assert!(!Text::new("a").is_empty());
}

#[test]
fn slicing_counts_code_points_so_every_cut_leaves_valid_text() {
    assert_eq!(slice("héllo", 1, 3).as_deref(), Some("él"));
    assert_eq!(slice("日本語", 1, 2).as_deref(), Some("本"));
    assert_eq!(slice("日本語", 0, 3).as_deref(), Some("日本語"));
    assert_eq!(slice("日本語", 3, 3).as_deref(), Some(""));
    assert_eq!(slice("a日b", 2, 3).as_deref(), Some("b"));
    assert_eq!(slice("abc", 1, 3).as_deref(), Some("bc"));
    assert_eq!(slice("abc", 0, 0).as_deref(), Some(""));
    assert_eq!(
        Text::new("日本語")
            .slice(&Int::from(1), &Int::from(3))
            .unwrap()
            .len(),
        2
    );
}

#[test]
fn a_slice_outside_the_text_is_none() {
    assert_eq!(slice("abc", 2, 1), None, "start after end");
    assert_eq!(slice("abc", 0, 4), None, "end past the length");
    assert_eq!(
        slice("日本語", 0, 4),
        None,
        "end past the length in code points"
    );
    assert_eq!(slice("abc", -1, 2), None, "a negative start");
    assert_eq!(slice("abc", 0, -1), None, "a negative end");
}

#[test]
fn nothing_is_normalized_implicitly() {
    let composed = Value::text("caf\u{e9}");
    let decomposed = Value::text("cafe\u{301}");
    assert!(!same(&composed, &decomposed));
    assert_eq!(Text::new("cafe\u{301}").as_str(), "cafe\u{301}");
}

#[test]
fn text_orders_lexicographically_by_code_point_with_a_proper_prefix_first() {
    let ascending = ["", "A", "Z", "a", "ab", "abc", "b", "é", "日", "\u{1F600}"];
    for (at, left) in ascending.iter().enumerate() {
        for (other, right) in ascending.iter().enumerate() {
            assert_eq!(
                order(&Value::text(left), &Value::text(right)),
                at.cmp(&other),
                "{left:?} against {right:?}"
            );
        }
    }
    // U+FFFF is three bytes and U+10000 four, and code-point order puts the
    // second after the first.
    assert!(order(&Value::text("\u{ffff}"), &Value::text("\u{10000}")).is_lt());
}

#[test]
fn joining_texts_keeps_every_code_point_in_order() {
    let joined = Text::new("日本語").concat(&Text::new("!"));
    assert_eq!(joined.as_str(), "日本語!");
    assert_eq!(joined.len(), 4);
    assert_eq!(
        joined.slice(&Int::from(3), &Int::from(4)).unwrap().as_str(),
        "!"
    );
}

#[test]
fn code_points_split_text_into_one_code_point_texts() {
    let parts = Text::new("a日👋").code_points();
    let spelled: Vec<&str> = parts.iter().map(Text::as_str).collect();
    assert_eq!(spelled, ["a", "日", "👋"]);
    assert!(parts.iter().all(|part| part.len() == 1));
}

#[test]
fn text_to_bytes_is_its_utf8_encoding() {
    assert_eq!(Text::new("é!").to_bytes().as_slice(), &[0xc3, 0xa9, b'!']);
}

#[test]
fn text_shows_itself_for_display_and_debug() {
    assert_eq!(Text::new("a\"b").to_string(), "a\"b");
    assert_eq!(format!("{:?}", Text::new("a\"b")), "\"a\\\"b\"");
}

#[test]
fn bytes_to_text_is_none_exactly_when_the_bytes_are_not_utf8() {
    assert_eq!(Bytes::new(&[0xc3, 0xa9]).to_text().unwrap().as_str(), "é");
    assert_eq!(Bytes::new(&[0xc3]).to_text(), None);
    assert_eq!(Bytes::new(&[0xff, b'a']).to_text(), None);
    assert_eq!(Bytes::new(&[]).to_text().unwrap().as_str(), "");
}

#[test]
fn bytes_count_and_order_by_unsigned_byte_with_a_proper_prefix_first() {
    assert_eq!(Bytes::new(&[1, 2, 3]).len(), 3);
    assert!(Bytes::new(&[]).is_empty());
    assert!(!Bytes::from(vec![0]).is_empty());
    let ascending = [
        vec![],
        vec![0],
        vec![0, 0],
        vec![1],
        vec![0x7f],
        vec![0x80],
        vec![0xff],
    ];
    for (at, left) in ascending.iter().enumerate() {
        for (other, right) in ascending.iter().enumerate() {
            assert_eq!(
                order(
                    &Value::Bytes(Bytes::new(left)),
                    &Value::Bytes(Bytes::new(right))
                ),
                at.cmp(&other),
                "{left:?} against {right:?}"
            );
        }
    }
}

#[test]
fn bytes_print_as_standard_base64_with_padding() {
    let base64 = |raw: &[u8]| Bytes::new(raw).to_base64();
    assert_eq!(base64(b""), "");
    assert_eq!(base64(b"f"), "Zg==");
    assert_eq!(base64(b"fo"), "Zm8=");
    assert_eq!(base64(b"foo"), "Zm9v");
    assert_eq!(base64(b"foob"), "Zm9vYg==");
    assert_eq!(base64(b"fooba"), "Zm9vYmE=");
    assert_eq!(base64(b"foobar"), "Zm9vYmFy");
    assert_eq!(base64(&[0xfb, 0xff, 0xbf]), "+/+/");
    assert_eq!(base64(&[0, 0x10, 0x83]), "ABCD");
    assert_eq!(format!("{:?}", Bytes::new(b"fo")), "bytes(Zm8=)");
}

#[test]
fn normalize_composes_to_form_c_so_canonical_equivalents_become_equal() {
    let normalized = |text: &str| Text::new(text).normalize().as_str().to_owned();
    assert_eq!(normalized("cafe\u{301}"), "caf\u{e9}");
    assert_eq!(normalized("caf\u{e9}"), "caf\u{e9}");
    // Canonical reordering puts the dot below before the dot above, and then
    // both compose with the `s`.
    assert_eq!(normalized("s\u{307}\u{323}"), "\u{1e69}");
    // A composition exclusion stays decomposed, and a singleton maps away.
    assert_eq!(normalized("\u{958}"), "\u{915}\u{93c}");
    assert_eq!(normalized("\u{212b}"), "\u{c5}");
    assert_eq!(Text::new("e\u{301}").normalize().len(), 1);
}

#[test]
fn case_mapping_is_unicodes_default_full_mapping_with_no_locale() {
    let lower = |text: &str| Text::new(text).lowercase().as_str().to_owned();
    let upper = |text: &str| Text::new(text).uppercase().as_str().to_owned();
    assert_eq!(lower("ÀBC Δ"), "àbc δ");
    assert_eq!(upper("àbc δ"), "ÀBC Δ");
    // Full mappings change the length: ß uppercases to two code points.
    assert_eq!(upper("straße"), "STRASSE");
    assert_eq!(Text::new("ß").uppercase().len(), 2);
    // Final sigma is the one context the default mapping reads.
    assert_eq!(lower("ΟΔΟΣ ΟΔΟΣ"), "οδος οδος");
    // No locale: a dotted capital I lowercases the same everywhere, and a
    // dotless i uppercases to the plain capital.
    assert_eq!(lower("I\u{130}"), "ii\u{307}");
    assert_eq!(upper("\u{131}"), "I");
}

#[test]
fn graphemes_are_extended_grapheme_clusters() {
    let clusters = |text: &str| -> Vec<String> {
        Text::new(text)
            .graphemes()
            .iter()
            .map(|part| part.as_str().to_owned())
            .collect()
    };
    assert_eq!(clusters("ae\u{301}"), ["a", "e\u{301}"]);
    assert_eq!(clusters("👋🏽!"), ["👋🏽", "!"]);
    assert_eq!(clusters("🇰🇷🇯🇵"), ["🇰🇷", "🇯🇵"]);
    assert_eq!(clusters("👩‍👩‍👧"), ["👩‍👩‍👧"]);
    assert_eq!(clusters("\r\n"), ["\r\n"]);
    // Extended clusters keep a spacing mark with its base.
    assert_eq!(clusters("\u{915}\u{93f}"), ["\u{915}\u{93f}"]);
    assert_eq!(clusters(""), Vec::<String>::new());
    assert_eq!(Text::new("e\u{301}").graphemes()[0].len(), 2);
}

#[test]
fn final_sigma_lowercases_a_capital_sigma_that_ends_a_word() {
    let lower = |text: &str| Text::new(text).lowercase().as_str().to_owned();
    assert_eq!(lower("ΣΑΣ"), "σας");
    assert_eq!(lower("Σ"), "σ", "no cased letter before it");
    assert_eq!(lower("ΑΣ"), "ας");
    assert_eq!(lower("ΑΣΑ"), "ασα", "a cased letter after it");
    assert_eq!(lower("ΑΣ ΑΣ."), "ας ας.");
    assert_eq!(lower(" Σ "), " σ ");
    assert_eq!(lower("1Σ"), "1σ", "a digit is not cased");
    // Case-ignorable code points between are skipped on either side: an
    // apostrophe and a combining accent.
    assert_eq!(lower("Α'Σ"), "α'ς");
    assert_eq!(lower("Α\u{301}Σ"), "α\u{301}ς");
    assert_eq!(lower("ΑΣ'Α"), "ασ'α");
    assert_eq!(lower("ΑΣ'"), "ας'");
    assert_eq!(lower("ΑΣ'1"), "ας'1");
    // A modifier letter is both cased and case-ignorable, so it is the cased
    // letter the rule asks for before the sigma, and after it.
    assert_eq!(lower("\u{2b0}Σ"), "\u{2b0}ς");
    assert_eq!(lower("ΑΣ\u{2b0}"), "ασ\u{2b0}");
}

#[test]
fn case_mapping_does_not_follow_the_toolchains_unicode() {
    // U+A7CE and U+A7CF became a case pair in Unicode 17.0.0. Under std v1's
    // Unicode neither has a mapping, whichever Unicode the compiler carries.
    let lower = |text: &str| Text::new(text).lowercase().as_str().to_owned();
    let upper = |text: &str| Text::new(text).uppercase().as_str().to_owned();
    assert_eq!(lower("\u{a7ce}"), "\u{a7ce}");
    assert_eq!(upper("\u{a7cf}"), "\u{a7cf}");
    // A letter Unicode 16.0.0 added does map.
    assert_eq!(lower("\u{a7cb}"), "\u{264}");
}

fn regex_syntax_knows(age: &str) -> bool {
    regex_syntax::Parser::new()
        .parse(&format!(r"\p{{Age={age}}}"))
        .is_ok()
}

#[test]
fn every_unicode_table_std_reads_has_std_v1s_one_unicode_version() {
    assert_eq!(flow_value::UNICODE_VERSION, (16, 0, 0));
    assert_eq!(
        flow_value::UNICODE_VERSION,
        unicode_normalization::UNICODE_VERSION
    );
    let widen = |(major, minor, update): (u8, u8, u8)| {
        (u64::from(major), u64::from(minor), u64::from(update))
    };
    assert_eq!(
        widen(flow_value::UNICODE_VERSION),
        unicode_segmentation::UNICODE_VERSION
    );
    assert_eq!(
        widen(flow_value::UNICODE_VERSION),
        unicode_case_mapping::UNICODE_VERSION
    );
    // `regex-syntax` names its version only in its tables' headers; the
    // newest age its classes know is that version.
    let (major, minor, _) = flow_value::UNICODE_VERSION;
    assert!(regex_syntax_knows(&format!("{major}.{minor}")));
    assert!(!regex_syntax_knows(&format!("{}.0", major + 1)));
}

#[test]
fn a_texts_byte_length_is_its_utf8_size() {
    assert_eq!(Text::new("aé日👋").byte_len(), 1 + 2 + 3 + 4);
    assert_eq!(Text::new("").byte_len(), 0);
}