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
//! A text's runs and joins: every join and cut agrees with a plain string,
//! joins stay balanced, and joining or cutting shares the blocks it keeps.

use std::sync::Arc;

use super::Draw;
use crate::int::Int;
use crate::text::{Text, WALKED};
use crate::tree::{self, Node};

fn index(at: usize) -> Int {
    Int::from(i64::try_from(at).expect("a small number"))
}

/// A piece of text with some multi-byte code points, so positions and bytes
/// differ.
fn piece(draw: &mut Draw) -> String {
    let alphabet = ["a", "é", "z", "日", " ", "Σ", "🙂"];
    (0..draw.below(90))
        .map(|_| alphabet[draw.below(alphabet.len())])
        .collect()
}

#[test]
fn joining_and_cutting_agree_with_a_plain_string() {
    let mut draw = Draw(11);
    let mut pool: Vec<(Text, String)> = Vec::new();
    for _ in 0..3000 {
        let made = match draw.below(3) {
            0 if !pool.is_empty() => {
                let (a, b) = (draw.below(pool.len()), draw.below(pool.len()));
                (
                    pool[a].0.concat(&pool[b].0),
                    format!("{}{}", pool[a].1, pool[b].1),
                )
            }
            1 if !pool.is_empty() => {
                let (text, plain) = &pool[draw.below(pool.len())];
                let count = plain.chars().count();
                let start = draw.below(count + 1);
                let end = start + draw.below(count - start + 1);
                let part: String = plain.chars().skip(start).take(end - start).collect();
                (text.slice(&index(start), &index(end)).unwrap(), part)
            }
            _ => {
                let plain = piece(&mut draw);
                (Text::new(&plain), plain)
            }
        };
        assert_eq!(made.0.len(), made.1.chars().count());
        assert_eq!(made.0.byte_len(), made.1.len());
        assert_eq!(made.0.blocks().collect::<String>(), made.1);
        assert_eq!(made.0.as_str(), made.1);
        if let Some(root) = made.0.root() {
            tree::check(root);
        }
        let log2 = (made.0.byte_len() + 2).bit_width();
        assert!(
            made.0.root().map_or(0, Node::height) <= usize::try_from(log2 * 3 / 2 + 1).unwrap(),
            "the joins stay balanced"
        );
        if pool.len() < 200 {
            pool.push(made);
        } else {
            let at = draw.below(pool.len());
            pool[at] = made;
        }
    }
    for (a, b) in pool.iter().zip(pool.iter().skip(1)) {
        assert_eq!(a.0 == b.0, a.1 == b.1);
        assert_eq!(a.0.cmp(&b.0), a.1.cmp(&b.1));
    }
}

#[test]
fn growing_a_text_one_piece_at_a_time_copies_no_long_piece() {
    let piece = "x".repeat(500);
    let mut text = Text::new("");
    for _ in 0..1000 {
        text = text.concat(&Text::new(&piece));
    }
    assert_eq!(text.byte_len(), 500 * 1000);
    let blocks: Vec<&str> = text.blocks().collect();
    assert_eq!(blocks.len(), 1000, "every piece is still its own block");
    assert!(
        text.root().map_or(0, Node::height) <= 15,
        "the joins stay balanced"
    );
}

#[test]
fn every_copy_of_a_text_shares_the_string_made_for_it() {
    let text = Text::new(&"a".repeat(100)).concat(&Text::new(&"b".repeat(100)));
    let copy = text.clone();
    assert_eq!(copy.as_str().as_ptr(), text.as_str().as_ptr());
}

#[test]
fn a_part_of_a_run_shares_the_run() {
    let text = Text::new(&"é".repeat(400));
    let part = text.slice(&index(10), &index(300)).unwrap();
    assert_eq!(part.len(), 290);
    assert!(
        Arc::ptr_eq(text.block_of().unwrap(), part.block_of().unwrap()),
        "the part points into the run"
    );
}

#[test]
fn slicing_a_long_text_that_is_not_ascii_walks_a_bounded_stretch_per_cut() {
    // Finding a position once walked from the start of its run, so cutting a
    // long document into its lines took time quadratic in its length.
    let length = 50_000;
    let text = Text::new(&"é日a".repeat(length / 3));
    let length = text.len();
    WALKED.with(|walked| walked.set(0));
    for start in 0..length {
        let part = text.slice(&index(start), &index(start + 1)).unwrap();
        assert_eq!(part.len(), 1);
    }
    let walked = WALKED.with(std::cell::Cell::get);
    // Once over the whole run to remember its places, then at most a stride
    // from the nearest for each end of each cut.
    assert!(
        walked <= length + 2 * 64 * length,
        "walked {walked} code points for {length} cuts"
    );
}

#[test]
fn cutting_and_finding_in_long_texts_agree_with_a_plain_string() {
    let mut draw = Draw(29);
    let alphabet = ["a", "é", "日", "|", "🙂", "ab"];
    for _ in 0..40 {
        let plain: String = (0..draw.below(700))
            .map(|_| alphabet[draw.below(alphabet.len())])
            .collect();
        let half = plain
            .char_indices()
            .nth(draw.below(plain.chars().count() + 1));
        // Half the cases are one run, half a join of two.
        let text = match half {
            Some((at, _)) if draw.below(2) == 0 => {
                Text::new(&plain[..at]).concat(&Text::new(&plain[at..]))
            }
            _ => Text::new(&plain),
        };
        let chars: Vec<char> = plain.chars().collect();
        let count = chars.len();
        for _ in 0..30 {
            let start = draw.below(count + 1);
            let end = start + draw.below(count - start + 1);
            let part: String = chars[start..end].iter().collect();
            assert_eq!(
                text.slice(&index(start), &index(end)).unwrap().as_str(),
                part
            );
            let needle: String = match draw.below(3) {
                0 => String::new(),
                1 => part.chars().take(3).collect(),
                _ => alphabet[draw.below(alphabet.len())].to_owned(),
            };
            let from = draw.below(count + 2);
            let expected = (from..=count).find(|&at| {
                chars[at..]
                    .iter()
                    .collect::<String>()
                    .starts_with(needle.as_str())
            });
            assert_eq!(
                text.find_from(&Text::new(&needle), &index(from)),
                expected,
                "{needle:?} from {from} in {plain:?}"
            );
        }
    }
}