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 dictionary's tree: every operation agrees with an ordered map, and a
//! dictionary made from a held one shares every node but the path it changed.

use super::Draw;
use crate::collection::Dict;
use crate::tree;
use crate::value::Value;
use std::collections::BTreeMap;

fn int(value: usize) -> Value {
    Value::int(i64::try_from(value).expect("a small number"))
}

fn read(dict: &Dict) -> Vec<(i64, i64)> {
    dict.iter()
        .map(|(key, value)| (super::number(key), super::number(value)))
        .collect()
}

fn model_entries(model: &BTreeMap<usize, usize>) -> Vec<(i64, i64)> {
    let wide = |n: usize| i64::try_from(n).expect("a small number");
    model
        .iter()
        .map(|(key, value)| (wide(*key), wide(*value)))
        .collect()
}

fn leaves(dict: &Dict) -> Vec<usize> {
    let mut out = Vec::new();
    if let Some(root) = dict.root() {
        tree::check(root);
        tree::check_keys(root);
        tree::leaves(root, &mut out);
    }
    out
}

#[test]
fn every_dictionary_operation_agrees_with_an_ordered_map() {
    let mut draw = Draw(7);
    let mut dict = Dict::new();
    let mut model = BTreeMap::new();
    let mut held = Vec::new();
    for step in 0..4000 {
        let key = draw.below(600);
        if draw.below(4) == 0 {
            dict = dict.remove(&int(key)).unwrap();
            model.remove(&key);
        } else {
            dict = dict.insert(int(key), int(step)).unwrap();
            model.insert(key, step);
        }
        if step % 97 == 0 {
            held.push((dict.clone(), model.clone()));
        }
        assert_eq!(dict.len(), model.len());
        let probe = draw.below(600);
        assert_eq!(
            dict.get(&int(probe)).unwrap().map(super::number),
            model
                .get(&probe)
                .map(|v| i64::try_from(*v).expect("a small number"))
        );
    }
    assert_eq!(read(&dict), model_entries(&model));
    leaves(&dict);
    for (dict, model) in held {
        assert_eq!(
            read(&dict),
            model_entries(&model),
            "a held dictionary is untouched"
        );
    }
}

#[test]
fn inserting_into_a_held_dictionary_copies_one_path_and_shares_every_other_leaf() {
    let dict = Dict::from_entries((0..400).map(|at| (int(2 * at), int(at)))).unwrap();
    let before = leaves(&dict);
    let grown = dict.clone().insert(int(401), int(0)).unwrap();
    let after = leaves(&grown);
    let new = after.iter().filter(|leaf| !before.contains(leaf)).count();
    assert!(
        new <= 2,
        "only the leaf that took the entry is new, or the two it split into"
    );
    assert!(before.len() + 1 >= after.len());
    assert_ne!(dict.root().unwrap().id(), grown.root().unwrap().id());
    assert_eq!(leaves(&dict), before, "the held dictionary is untouched");
}