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
//! The text form interpolation inserts (`types.md`, *Equality, ordering and
//! text*, and each built-in type's form in `data.md`).

mod common;

use common::*;
use flow_types::{Constructor, EnumShape, Payload};
use flow_value::{
    Bytes, Dict, Duration, Instant, Int, Set, Value, Variant, interpolate, interpolate_within,
    text_form, text_form_within,
};

fn shown(value: &Value) -> String {
    text_form(value).expect("data")
}

#[test]
fn interpolating_text_inserts_its_own_code_points() {
    assert_eq!(
        interpolate(&Value::text("a \"quoted\" ${x}"))
            .unwrap()
            .as_str(),
        "a \"quoted\" ${x}"
    );
}

#[test]
fn interpolating_any_other_data_value_inserts_its_text_form() {
    assert_eq!(interpolate(&Value::int(-42)).unwrap().as_str(), "-42");
    assert_eq!(
        interpolate(&some(Value::text("a"))).unwrap().as_str(),
        "Some(\"a\")"
    );
    assert_eq!(interpolate(&Value::int(7)).unwrap().len(), 1);
}

#[test]
fn numbers_print_as_plain_decimal_digits() {
    assert_eq!(shown(&Value::int(-42)), "-42");
    assert_eq!(
        shown(&Value::Int(int("123456789012345678901234567890"))),
        "123456789012345678901234567890"
    );
    assert_eq!(shown(&decimal_value("1.50")), "1.5");
    assert_eq!(shown(&decimal_value("2.0")), "2");
    assert_eq!(shown(&decimal_value("-0.05")), "-0.05");
}

#[test]
fn booleans_and_unit_print_as_their_literals() {
    assert_eq!(shown(&Value::Bool(true)), "true");
    assert_eq!(shown(&Value::Bool(false)), "false");
    assert_eq!(shown(&Value::Unit), "()");
}

#[test]
fn text_inside_another_value_is_written_as_the_literal_that_denotes_it() {
    let inside = |text: &str| shown(&Value::text(text));
    assert_eq!(inside("plain"), "\"plain\"");
    assert_eq!(inside(""), "\"\"");
    assert_eq!(inside("a\"b"), r#""a\"b""#);
    assert_eq!(inside("a\\b"), r#""a\\b""#);
    assert_eq!(inside("line\nnext"), r#""line\nnext""#);
    assert_eq!(inside("tab\there"), r#""tab\there""#);
    assert_eq!(inside("${name}"), r#""\${name}""#);
    assert_eq!(
        inside("$5 {x}"),
        "\"$5 {x}\"",
        "a dollar sign not before a brace is ordinary"
    );
    assert_eq!(inside("end$"), "\"end$\"");
    assert_eq!(
        inside("\r\u{0}\u{1b}\u{1f}\u{7f}"),
        r#""\u{D}\u{0}\u{1B}\u{1F}\u{7F}""#
    );
    assert_eq!(inside(" ~é日\u{80}"), "\" ~é日\u{80}\"");
}

#[test]
fn bytes_print_as_base64_quoted_inside_another_value() {
    let bytes = |raw: &[u8]| Value::Bytes(Bytes::new(raw));
    assert_eq!(interpolate(&bytes(b"foobar")).unwrap().as_str(), "Zm9vYmFy");
    assert_eq!(interpolate(&bytes(b"")).unwrap().as_str(), "");
    assert_eq!(shown(&Value::list([bytes(b"foobar")])), r#"["Zm9vYmFy"]"#);
    assert_eq!(shown(&some(bytes(b""))), r#"Some("")"#);
}

#[test]
fn lists_and_sets_print_their_elements_in_order_between_brackets() {
    assert_eq!(shown(&Value::list([])), "[]");
    assert_eq!(shown(&Value::list([Value::int(1)])), "[1]");
    assert_eq!(
        shown(&Value::list([
            Value::int(1),
            Value::text("b"),
            Value::list([])
        ])),
        "[1, \"b\", []]"
    );
    let set = Set::from_items([Value::int(3), Value::int(1)]).unwrap();
    assert_eq!(shown(&Value::Set(set)), "[1, 3]");
}

#[test]
fn dictionaries_print_as_their_literal_in_key_order() {
    assert_eq!(shown(&Value::Dict(Dict::new())), "[:]");
    let dict = Dict::from_entries([
        (Value::text("beta"), Value::int(5)),
        (Value::text("alpha"), Value::int(3)),
    ])
    .unwrap();
    assert_eq!(shown(&Value::Dict(dict)), "[\"alpha\": 3, \"beta\": 5]");
}

#[test]
fn tuples_print_their_parts_between_parentheses() {
    assert_eq!(
        shown(&Value::tuple([Value::int(1), Value::text("a")])),
        "(1, \"a\")"
    );
}

#[test]
fn records_print_their_name_and_every_field_in_declaration_order() {
    let row = record(
        "Session",
        &[("id", Value::text("s1")), ("token", Value::text("secret"))],
    );
    assert_eq!(shown(&row), "Session { id: \"s1\", token: \"secret\" }");
    assert_eq!(shown(&record("Empty", &[])), "Empty {}");
}

#[test]
fn enum_values_print_their_constructor_and_payload() {
    let shape = EnumShape::new(
        "Outcome",
        [
            Constructor::new("Done", Payload::Positional(1)),
            Constructor::new("Pair", Payload::Positional(2)),
            Constructor::new("StepFailed", Payload::named(["step", "last"])),
            Constructor::new("TimedOut", Payload::None),
            Constructor::new("Nothing", Payload::named([])),
        ],
    );
    let make = |index, payload| {
        Value::Variant(Variant::new(std::sync::Arc::clone(&shape), index, payload).unwrap())
    };
    assert_eq!(shown(&make(0, vec![Value::int(1)])), "Done(1)");
    assert_eq!(
        shown(&make(1, vec![Value::int(1), Value::int(2)])),
        "Pair(1, 2)"
    );
    assert_eq!(
        shown(&make(2, vec![Value::int(3), Value::text("x")])),
        "StepFailed { step: 3, last: \"x\" }"
    );
    assert_eq!(shown(&make(3, vec![])), "TimedOut");
    assert_eq!(shown(&make(4, vec![])), "Nothing {}");
    assert_eq!(shown(&some(none())), "Some(None)");
}

#[test]
fn durations_and_instants_print_in_iso_8601_quoted_inside_another_value() {
    let span = Value::Duration(Duration::from_millis(&Int::from(90_000)));
    let at = Value::Instant(Instant::from_unix_seconds(dec("0")));
    assert_eq!(interpolate(&span).unwrap().as_str(), "PT90S");
    assert_eq!(interpolate(&at).unwrap().as_str(), "1970-01-01T00:00:00Z");
    assert_eq!(
        shown(&Value::list([span, at])),
        r#"["PT90S", "1970-01-01T00:00:00Z"]"#
    );
}

#[test]
fn a_text_form_within_a_byte_bound_is_written_whole_and_beyond_it_is_none() {
    let list = Value::list([Value::text("ab"), Value::int(1)]);
    // `["ab", 1]` is nine bytes.
    assert_eq!(
        text_form_within(&list, 9),
        Ok(Some("[\"ab\", 1]".to_owned()))
    );
    assert_eq!(text_form_within(&list, 8), Ok(None));
    assert_eq!(text_form_within(&Value::text("é"), 3), Ok(None));
    assert_eq!(
        text_form_within(&Value::text("é"), 4),
        Ok(Some("\"é\"".to_owned()))
    );
    // Writing stops at the bound: a list of a million parts is refused early.
    let long = Value::list((0..1_000_000).map(Value::int));
    assert_eq!(text_form_within(&long, 16), Ok(None));
}

#[test]
fn a_text_or_bytes_past_the_bound_is_refused_before_it_is_written() {
    // `"abc"` is five bytes, and `"YWJj"` six.
    assert_eq!(text_form_within(&Value::text("abc"), 4), Ok(None));
    assert_eq!(
        text_form_within(&Value::text("abc"), 5),
        Ok(Some("\"abc\"".to_owned()))
    );
    let bytes = Value::Bytes(flow_value::Bytes::new(b"abc"));
    assert_eq!(text_form_within(&bytes, 5), Ok(None));
    assert_eq!(text_form_within(&bytes, 6), Ok(Some("\"YWJj\"".to_owned())));
}

#[test]
fn a_decimal_whose_text_passes_the_bound_is_refused_before_it_is_written() {
    let power = |exponent: i64| {
        Value::Decimal(flow_value::Decimal::new(1.into(), exponent).expect("a decimal"))
    };
    // `[1, 1000]` is nine bytes: the decimal takes the four left after `[1, `.
    let list = Value::list([Value::int(1), power(3)]);
    assert_eq!(text_form_within(&list, 9), Ok(Some("[1, 1000]".to_owned())));
    assert_eq!(text_form_within(&list, 8), Ok(None));
    // A decimal that just fits its room is written, unbounded or not.
    assert_eq!(text_form_within(&power(3), 4), Ok(Some("1000".to_owned())));
    assert_eq!(text_form(&list), Ok("[1, 1000]".to_owned()));
    // A one with nine quintillion zeros is never written out.
    assert_eq!(text_form_within(&power(i64::MAX), 1 << 20), Ok(None));
    assert_eq!(text_form_within(&power(i64::MIN), 1 << 20), Ok(None));
}

#[test]
fn a_duration_or_instant_whose_text_passes_the_bound_is_refused_before_it_is_written() {
    let seconds = |coefficient: i64, exponent: i64| {
        flow_value::Decimal::new(coefficient.into(), exponent).expect("a decimal")
    };
    let span = |coefficient, exponent| {
        Value::Duration(Duration::from_seconds(seconds(coefficient, exponent)))
    };
    let at = |coefficient, exponent| {
        Value::Instant(Instant::from_unix_seconds(seconds(coefficient, exponent)))
    };
    // Seconds with nine quintillion digits, before or after the point, are
    // never written out, nor is the power of ten an instant's floor needs.
    for exponent in [i64::MAX, i64::MIN + 1] {
        assert_eq!(
            text_form_within(&span(1, exponent), 1 << 20),
            Ok(None),
            "10^{exponent}s"
        );
        assert_eq!(
            text_form_within(&at(1, exponent), 1 << 20),
            Ok(None),
            "10^{exponent}s"
        );
        assert_eq!(
            text_form_within(&at(-1, exponent), 1 << 20),
            Ok(None),
            "-10^{exponent}s"
        );
    }
    // `"PT1000S"` is nine bytes, and is written when they fit; interpolated,
    // it is `PT1000S`, seven bytes.
    assert_eq!(
        text_form_within(&span(1, 3), 9),
        Ok(Some("\"PT1000S\"".to_owned()))
    );
    assert_eq!(text_form_within(&span(1, 3), 8), Ok(None));
    assert_eq!(
        interpolate_within(&span(1, 3), 7).map(|text| text.map(|text| text.as_str().to_owned())),
        Ok(Some("PT1000S".to_owned()))
    );
    assert_eq!(interpolate_within(&span(1, 3), 6), Ok(None));
    // The bound never refuses an instant whose text fits, however its
    // seconds are written.
    for (coefficient, exponent) in [(1, 0), (-1, -9), (123_456_789, 12), (-5, 15), (7, -30)] {
        let instant = at(coefficient, exponent);
        let text = text_form(&instant).expect("an instant is data");
        assert_eq!(
            text_form_within(&instant, text.len()),
            Ok(Some(text.clone())),
            "{text}"
        );
        assert_eq!(
            text_form_within(&instant, text.len() - 1),
            Ok(None),
            "{text}"
        );
    }
}