use std::borrow::Cow;
use flow_abi_testing::catalog as common;
use common::*;
use flow_abi::primitives::{
Reader, write_biguint, write_int, write_signed, write_text, write_uint,
};
use flow_abi::{
Crc32c, DATA_VERSION, DataVersion, DecodeErrorKind, Form, Limits, Mode, Scalar, crc32c,
decode_bytes, decode_text, encode_bytes, form, read_scalar, read_value, write_scalar,
};
use flow_testing::on_a_small_stack;
use flow_types::Type;
use flow_value::{BigInt, Value, equal};
use num_bigint::BigUint;
#[track_caller]
fn bin(ty: &Type, value: &Value) -> Vec<u8> {
let catalog = catalog();
let bytes = encode_bytes(&catalog, ty, value).expect("the value encodes");
let back = decode_bytes(&catalog, ty, &bytes, Mode::Reply, &Limits::LANGUAGE)
.expect("its encoding decodes");
assert!(
same(&catalog, ty, value, &back),
"{value:?} came back as {back:?}"
);
bytes
}
#[track_caller]
fn refused_within(ty: &Type, bytes: &[u8], limits: &Limits) -> (String, String, DecodeErrorKind) {
match decode_bytes(&catalog(), ty, bytes, Mode::Reply, limits) {
Ok(value) => panic!("{bytes:?} decoded to {value:?}"),
Err(error) => (error.path.to_string(), error.problem, error.kind),
}
}
#[track_caller]
fn refused(ty: &Type, bytes: &[u8]) -> (String, String, DecodeErrorKind) {
refused_within(ty, bytes, &Limits::LANGUAGE)
}
#[track_caller]
fn eq(a: &Value, b: &Value) -> bool {
equal(a, b).expect("data")
}
fn uint(value: u64) -> Vec<u8> {
let mut out = Vec::new();
write_uint(&mut out, value);
out
}
fn signed(value: &str) -> Vec<u8> {
let mut out = Vec::new();
write_int(&mut out, &value.parse::<BigInt>().expect("digits"));
out
}
#[test]
fn a_number_is_seven_bits_to_a_byte_least_significant_first() {
assert_eq!(uint(0), [0x00]);
assert_eq!(uint(1), [0x01]);
assert_eq!(uint(63), [0x3f]);
assert_eq!(uint(64), [0x40]);
assert_eq!(uint(127), [0x7f]);
assert_eq!(uint(128), [0x80, 0x01]);
assert_eq!(uint(300), [0xac, 0x02]);
assert_eq!(uint(16_384), [0x80, 0x80, 0x01]);
assert_eq!(
uint(u64::MAX),
[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01]
);
}
#[test]
fn a_number_of_any_size_is_written_the_same_way() {
let big = |value: BigUint| {
let mut out = Vec::new();
write_biguint(&mut out, &value);
out
};
assert_eq!(big(BigUint::from(0u32)), [0x00]);
assert_eq!(big(BigUint::from(128u32)), [0x80, 0x01]);
assert_eq!(big(BigUint::from(u64::MAX)), uint(u64::MAX));
assert_eq!(
big(BigUint::from(1u32) << 64u32),
[0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x02]
);
}
#[test]
fn a_signed_number_is_twice_itself_or_twice_its_magnitude_less_one() {
assert_eq!(signed("0"), [0x00]);
assert_eq!(signed("-1"), [0x01]);
assert_eq!(signed("1"), [0x02]);
assert_eq!(signed("-2"), [0x03]);
assert_eq!(signed("63"), [0x7e]);
assert_eq!(signed("-64"), [0x7f]);
assert_eq!(signed("64"), [0x80, 0x01]);
assert_eq!(signed("-65"), [0x81, 0x01]);
assert_eq!(signed("9223372036854775807"), uint(u64::MAX - 1));
assert_eq!(signed("-9223372036854775808"), uint(u64::MAX));
let mut small = Vec::new();
write_signed(&mut small, i64::MIN);
assert_eq!(small, signed("-9223372036854775808"));
}
#[test]
fn a_text_is_its_length_in_bytes_then_its_utf8() {
let text = |value: &str| {
let mut out = Vec::new();
write_text(&mut out, value);
out
};
assert_eq!(text(""), [0]);
assert_eq!(text("hi"), [2, b'h', b'i']);
assert_eq!(text("é"), [2, 0xc3, 0xa9]);
}
#[test]
fn a_reader_reads_back_each_number_and_text_and_says_where_it_is() {
let mut bytes = uint(300);
bytes.extend(signed("-65"));
write_text(&mut bytes, "日本");
let mut reader = Reader::new(&bytes);
assert_eq!(reader.uint().unwrap(), 300);
assert_eq!(reader.position(), 2);
assert_eq!(reader.signed().unwrap(), -65);
assert_eq!(reader.text(&Limits::LANGUAGE).unwrap(), "日本");
assert!(reader.is_empty());
assert_eq!(reader.remaining(), 0);
}
#[test]
fn a_number_in_more_bytes_than_it_needs_is_refused() {
let problem = |bytes: &[u8]| Reader::new(bytes).uint().unwrap_err().problem;
assert!(problem(&[0x80, 0x00]).contains("more bytes than it needs"));
assert!(problem(&[0x81, 0x80, 0x00]).contains("more bytes than it needs"));
let big = |bytes: &[u8]| Reader::new(bytes).biguint(4096).unwrap_err().problem;
assert!(big(&[0x80, 0x00]).contains("more bytes than it needs"));
let (_, problem, kind) = refused(&Type::Int, &[0x80, 0x00]);
assert!(problem.contains("more bytes than it needs"), "{problem}");
assert_eq!(kind, DecodeErrorKind::Syntax { at: 0 });
let (_, problem, _) = refused(&Type::Text, &[0x81, 0x00, b'a']);
assert!(problem.contains("more bytes than it needs"), "{problem}");
}
#[test]
fn a_number_past_64_bits_where_one_must_fit_is_refused() {
let problem = Reader::new(&[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02])
.uint()
.unwrap_err()
.problem;
assert!(problem.contains("larger than 64 bits"), "{problem}");
let mut bytes = vec![0x02];
bytes.extend([0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03]);
let (_, problem, _) = refused(&Type::Decimal, &bytes);
assert!(problem.contains("larger than 64 bits"), "{problem}");
}
#[test]
fn bytes_that_end_early_are_refused() {
let (_, problem, kind) = refused(&Type::Text, &[3, b'a']);
assert!(problem.contains("ends before its value does"), "{problem}");
assert_eq!(kind, DecodeErrorKind::Syntax { at: 1 });
assert!(refused(&Type::Int, &[0x80]).1.contains("ends before"));
assert!(refused(&Type::Bool, &[]).1.contains("ends before"));
assert!(refused(&Type::Decimal, &[2]).1.contains("ends before"));
}
#[test]
fn bytes_left_over_after_the_value_are_refused() {
let (path, problem, _) = refused(&Type::Int, &[2, 0]);
assert_eq!(path, "");
assert!(
problem.contains("ends at byte 1, before the 2 bytes given do"),
"{problem}"
);
assert!(refused(&Type::Unit, &[0]).1.contains("ends at byte 0"));
}
#[test]
fn a_text_that_is_not_utf8_is_refused() {
let (_, problem, _) = refused(&Type::Text, &[1, 0xff]);
assert!(problem.contains("not UTF-8"), "{problem}");
assert!(
refused(&Type::Text, &[3, 0xed, 0xa0, 0x80])
.1
.contains("not UTF-8")
);
}
#[test]
fn unit_is_nothing() {
assert!(
bin(&Type::Unit, &Value::Unit).is_empty(),
"Unit takes no bytes"
);
}
#[test]
fn a_bool_is_one_byte_zero_or_one() {
assert_eq!(bin(&Type::Bool, &Value::Bool(false)), [0]);
assert_eq!(bin(&Type::Bool, &Value::Bool(true)), [1]);
let (_, problem, _) = refused(&Type::Bool, &[2]);
assert!(problem.contains("0 or 1"), "{problem}");
}
#[test]
fn an_int_is_a_signed_number_exact_at_any_size() {
assert_eq!(bin(&Type::Int, &int("0")), [0]);
assert_eq!(bin(&Type::Int, &int("300")), [0xd8, 0x04]);
assert_eq!(bin(&Type::Int, &int("-1")), [1]);
let huge = "123456789012345678901234567890123456789012345678901234567890";
assert_eq!(bin(&Type::Int, &int(huge)), signed(huge));
assert_eq!(
bin(&Type::Int, &int(&format!("-{huge}"))),
signed(&format!("-{huge}"))
);
}
#[test]
fn a_decimal_is_its_coefficient_then_its_exponent() {
assert_eq!(bin(&Type::Decimal, &dec("1.5")), [30, 1]);
assert_eq!(bin(&Type::Decimal, &dec("1.50")), [30, 1]);
assert_eq!(bin(&Type::Decimal, &dec("-0.001")), [1, 5]);
assert_eq!(bin(&Type::Decimal, &dec("100")), [2, 4]);
assert_eq!(bin(&Type::Decimal, &dec("0.0")), [0, 0]);
}
#[test]
fn a_decimal_that_is_not_normalized_is_refused() {
let (_, problem, _) = refused(&Type::Decimal, &[20, 0]);
assert!(problem.contains("not normalized"), "{problem}");
assert!(
refused(&Type::Decimal, &[0, 2])
.1
.contains("not normalized")
);
assert!(
refused(&Type::Decimal, &[59, 1])
.1
.contains("not normalized")
);
}
#[test]
fn text_is_a_text() {
assert_eq!(bin(&Type::Text, &text("")), [0]);
assert_eq!(bin(&Type::Text, &text("hi")), [2, b'h', b'i']);
assert_eq!(bin(&Type::Text, &text("é")), [2, 0xc3, 0xa9]);
}
#[test]
fn bytes_are_their_length_then_the_bytes() {
assert_eq!(bin(&Type::Bytes, &bytes(&[])), [0]);
assert_eq!(bin(&Type::Bytes, &bytes(&[0, 255])), [2, 0, 255]);
assert_eq!(bin(&Type::Bytes, &bytes(&[0xff])), [1, 0xff]);
}
#[test]
fn a_duration_is_a_decimal_of_its_seconds() {
assert_eq!(bin(&Type::Duration, &duration("90")), [18, 2]);
assert_eq!(bin(&Type::Duration, &duration("0.25")), [50, 3]);
assert_eq!(bin(&Type::Duration, &duration("-5")), [9, 0]);
assert_eq!(bin(&Type::Duration, &duration("0")), [0, 0]);
}
#[test]
fn an_instant_is_a_decimal_of_its_seconds_after_the_epoch() {
assert_eq!(bin(&Type::Instant, &instant("0")), [0, 0]);
assert_eq!(bin(&Type::Instant, &instant("1.5")), [30, 1]);
assert_eq!(bin(&Type::Instant, &instant("-1")), [1, 0]);
let before_year_zero = bin(&Type::Instant, &instant("-62167305600"));
let mut expected = signed("-621673056");
expected.extend(signed("2"));
assert_eq!(before_year_zero, expected);
}
#[test]
fn a_list_is_its_count_then_its_elements_in_list_order() {
let ty = Type::list(Type::Int);
assert_eq!(
bin(&ty, &Value::list([int("3"), int("1"), int("2")])),
[3, 6, 2, 4]
);
assert_eq!(bin(&ty, &Value::list([])), [0]);
}
#[test]
fn a_set_is_its_count_then_its_elements_ascending_without_repeats() {
let ty = Type::set(Type::Text);
assert_eq!(
bin(&ty, &set(vec![text("b"), text("a"), text("b")])),
[2, 1, b'a', 1, b'b']
);
assert_eq!(bin(&ty, &set(vec![])), [0]);
}
#[test]
fn a_set_out_of_order_or_with_a_repeat_is_refused() {
let ty = Type::set(Type::Int);
let (path, problem, _) = refused(&ty, &[2, 4, 2]);
assert_eq!(path, "");
assert!(
problem.contains("element 1 out of ascending order"),
"{problem}"
);
let (_, problem, kind) = refused(&ty, &[2, 2, 2]);
assert!(problem.contains("repeats element 0"), "{problem}");
assert_eq!(kind, DecodeErrorKind::Duplicate);
}
#[test]
fn a_dict_is_its_count_then_each_key_and_value_ascending_by_key() {
let ty = Type::dict(Type::Int, Type::Text);
let entries = dict(vec![(int("10"), text("ten")), (int("-1"), text("m"))]);
assert_eq!(bin(&ty, &entries), [2, 1, 1, b'm', 20, 3, b't', b'e', b'n']);
let ty = Type::dict(Type::Text, Type::Int);
let entries = dict(vec![(text("b"), int("2")), (text("a"), int("1"))]);
assert_eq!(bin(&ty, &entries), [2, 1, b'a', 2, 1, b'b', 4]);
assert_eq!(bin(&ty, &dict(vec![])), [0]);
}
#[test]
fn a_dict_out_of_key_order_or_with_a_repeated_key_is_refused() {
let ty = Type::dict(Type::Int, Type::Int);
let (_, problem, _) = refused(&ty, &[2, 4, 0, 2, 0]);
assert!(
problem.contains("key 1 out of ascending order"),
"{problem}"
);
let (_, problem, kind) = refused(&ty, &[2, 2, 0, 2, 2]);
assert!(problem.contains("repeats key 0"), "{problem}");
assert_eq!(kind, DecodeErrorKind::Duplicate);
}
#[test]
fn a_tuple_is_its_parts_in_order() {
let ty = Type::Tuple(vec![Type::Int, Type::Text, Type::Unit]);
assert_eq!(
bin(&ty, &Value::tuple([int("1"), text("a"), Value::Unit])),
[2, 1, b'a']
);
}
#[test]
fn a_record_is_its_fields_in_declaration_order() {
let catalog = catalog();
let step = rec(&catalog, STEP, vec![text("ada"), Value::Bool(true)]);
assert_eq!(bin(&named(STEP), &step), [3, b'a', b'd', b'a', 1]);
let plan = rec(&catalog, PLAN, vec![Value::list([]), none(), text("t")]);
assert_eq!(bin(&named(PLAN), &plan), [0, 0, 1, b't']);
}
#[test]
fn a_records_private_fields_are_written_like_any_other() {
let catalog = catalog();
let plan = rec(&catalog, PLAN, vec![Value::list([]), none(), text("t")]);
let approved = rec(&catalog, APPROVED, vec![plan]);
let bytes = encode_bytes(&catalog, &named(APPROVED), &approved).unwrap();
assert_eq!(bytes, [0, 0, 1, b't']);
let back = decode_bytes(
&catalog,
&named(APPROVED),
&bytes,
Mode::Rebuild,
&Limits::LANGUAGE,
)
.expect("rebuilt");
assert!(same(&catalog, &named(APPROVED), &approved, &back));
}
#[test]
fn an_enum_is_its_constructors_number_then_its_payloads_parts() {
let catalog = catalog();
let status = |index, payload| ctor(&catalog, STATUS, index, payload);
assert_eq!(bin(&named(STATUS), &status(0, vec![])), [0]);
assert_eq!(
bin(&named(STATUS), &status(1, vec![text("x")])),
[1, 1, b'x']
);
assert_eq!(
bin(&named(STATUS), &status(2, vec![int("1"), text("a")])),
[2, 2, 1, b'a']
);
assert_eq!(
bin(&named(STATUS), &status(3, vec![int("3"), some(text("r"))])),
[3, 6, 1, 1, b'r']
);
let leaf = ctor(&catalog, TREE, 0, vec![int("1")]);
let node = ctor(&catalog, TREE, 1, vec![Value::list([leaf])]);
assert_eq!(bin(&tree(Type::Int), &node), [1, 1, 0, 2]);
}
#[test]
fn a_constructor_number_the_enum_does_not_have_is_refused() {
let (_, problem, _) = refused(&named(STATUS), &[4]);
assert!(
problem.contains(
"names constructor 4, which github.com/acme/plans@v1.2.0/plans.Status does not have"
),
"{problem}"
);
assert!(
refused(&Type::option(Type::Int), &[2])
.1
.contains("constructor 2")
);
}
#[test]
fn an_option_is_an_ordinary_enum() {
let ty = Type::option(Type::Int);
assert_eq!(bin(&ty, &none()), [0]);
assert_eq!(bin(&ty, &some(int("5"))), [1, 10]);
let nested = Type::option(Type::option(Type::Int));
assert_eq!(bin(&nested, &some(none())), [1, 0]);
}
#[test]
fn a_json_value_is_an_ordinary_enum_too() {
assert_eq!(bin(&Type::Json, &raw(0, vec![])), [0]);
assert_eq!(bin(&Type::Json, &raw(1, vec![Value::Bool(true)])), [1, 1]);
assert_eq!(bin(&Type::Json, &raw(2, vec![dec("1.5")])), [2, 30, 1]);
assert_eq!(bin(&Type::Json, &raw(3, vec![text("a")])), [3, 1, b'a']);
assert_eq!(
bin(&Type::Json, &raw(4, vec![Value::list([raw(0, vec![])])])),
[4, 1, 0]
);
assert_eq!(
bin(
&Type::Json,
&raw(5, vec![dict(vec![(text("k"), raw(0, vec![]))])])
),
[5, 1, 1, b'k', 0]
);
}
#[test]
fn a_host_type_value_is_the_hosts_token_as_a_text() {
assert_eq!(bin(&named(PAGE), &host("p-1")), [3, b'p', b'-', b'1']);
assert_eq!(
bin(&Type::list(named(PAGE)), &Value::list([host("a")])),
[1, 1, b'a']
);
}
#[test]
fn functions_and_tasks_have_no_encoding() {
let catalog = catalog();
let callback = rec(&catalog, CALLBACK, vec![Value::Unit]);
let error = encode_bytes(&catalog, &named(CALLBACK), &callback).unwrap_err();
assert_eq!(error.path, "run");
assert!(error.problem.contains("no encoding"), "{}", error.problem);
let task = Type::Task(Box::new(Type::Int));
assert!(encode_bytes(&catalog, &task, &Value::Unit).is_err());
let function = Type::Function {
params: vec![],
result: Box::new(Type::Unit),
};
assert!(encode_bytes(&catalog, &function, &Value::Unit).is_err());
}
#[test]
fn a_value_that_does_not_have_its_type_is_not_encoded() {
let catalog = catalog();
let error =
encode_bytes(&catalog, &Type::list(Type::Int), &Value::list([text("a")])).unwrap_err();
assert_eq!(error.path, "[0]");
assert_eq!(error.problem, "is not a value of Int");
}
#[test]
fn a_refusal_names_the_place_in_the_value() {
let catalog = catalog();
let mut bytes = Vec::new();
bytes.extend([1, 1, b'a', 2]);
let error = decode_bytes(
&catalog,
&named(PLAN),
&bytes,
Mode::Reply,
&Limits::LANGUAGE,
)
.unwrap_err();
assert_eq!(error.path, "steps[0].done");
let error = decode_bytes(
&catalog,
&named(STATUS),
&[3, 6, 1, 1, 0xff],
Mode::Reply,
&Limits::LANGUAGE,
)
.unwrap_err();
assert_eq!(error.path, "Arrived.reply.Some[0]");
}
#[test]
fn decoding_judges_the_type_before_reading_a_byte() {
let catalog = catalog();
let problem = |ty: &Type, mode| {
decode_bytes(&catalog, ty, &[], mode, &Limits::LANGUAGE)
.unwrap_err()
.problem
};
assert!(problem(&named(PAGE), Mode::Reply).contains("ends before"));
assert!(!problem(&named(PAGE), Mode::Input).contains("ends before"));
assert!(!problem(&named(APPROVED), Mode::Reply).contains("ends before"));
assert!(problem(&named(APPROVED), Mode::Rebuild).contains("ends before"));
}
#[test]
fn never_has_no_values_to_decode() {
let (_, problem, _) = refused(&Type::Never, &[]);
assert!(problem.contains("no values"), "{problem}");
}
#[test]
fn a_value_as_deep_as_the_limit_decodes_without_a_native_frame_per_level() {
let catalog = catalog();
let (ty, text) = deepest_trees();
let value = decode_text(&catalog, &ty, &text, Mode::Reply, &Limits::LANGUAGE)
.expect("within the limits");
let deepest = encode_bytes(&catalog, &ty, &value).expect("the value encodes");
let deeper = [&[1][..], &deepest].concat();
let deeper_ty = Type::list(ty.clone());
on_a_small_stack(|| {
assert!(decode_bytes(&catalog, &ty, &deepest, Mode::Reply, &Limits::LANGUAGE).is_ok());
let error = decode_bytes(
&catalog,
&deeper_ty,
&deeper,
Mode::Reply,
&Limits::LANGUAGE,
)
.expect_err("one level too deep");
assert_eq!(error.kind, DecodeErrorKind::TooLarge);
assert_eq!(error.problem, "nests deeper than 256 levels");
});
}
#[test]
fn a_value_nested_past_the_depth_limit_is_refused_as_a_limit() {
let limits = Limits {
depth: 2,
..Limits::LANGUAGE
};
let ty = Type::list(Type::list(Type::list(Type::Int)));
let (path, problem, kind) = refused_within(&ty, &[1, 1, 1, 0], &limits);
assert_eq!(kind, DecodeErrorKind::TooLarge);
assert_eq!(path, "[0][0]");
assert!(problem.contains("deeper than 2 levels"), "{problem}");
let two_deep = decode_bytes(
&catalog(),
&Type::list(Type::list(Type::Int)),
&[1, 1, 0],
Mode::Reply,
&limits,
);
assert!(two_deep.is_ok());
}
#[test]
fn an_int_past_the_size_limit_is_refused_as_a_limit() {
let limits = Limits {
int_bits: 8,
..Limits::LANGUAGE
};
let decode = |bytes: &[u8]| decode_bytes(&catalog(), &Type::Int, bytes, Mode::Reply, &limits);
assert!(eq(&decode(&signed("255")).unwrap(), &int("255")));
assert!(eq(&decode(&signed("-255")).unwrap(), &int("-255")));
let (_, problem, kind) = refused_within(&Type::Int, &signed("256"), &limits);
assert_eq!(kind, DecodeErrorKind::TooLarge);
assert!(problem.contains("larger than 8 bits"), "{problem}");
let mut long = vec![0xff; 1000];
long.push(0x01);
assert_eq!(
refused_within(&Type::Int, &long, &limits).2,
DecodeErrorKind::TooLarge
);
let mut decimal = signed("257");
decimal.push(0);
assert_eq!(
refused_within(&Type::Decimal, &decimal, &limits).2,
DecodeErrorKind::TooLarge
);
}
#[test]
fn a_text_or_bytes_past_the_size_limit_is_refused_as_a_limit() {
let limits = Limits {
text_bytes: 2,
..Limits::LANGUAGE
};
let (_, problem, kind) = refused_within(&Type::Text, &[3, b'a', b'b', b'c'], &limits);
assert_eq!(kind, DecodeErrorKind::TooLarge);
assert!(problem.contains("longer than 2 bytes"), "{problem}");
assert_eq!(
refused_within(&Type::Bytes, &[3, 1, 2, 3], &limits).2,
DecodeErrorKind::TooLarge
);
assert_eq!(
refused_within(&named(PAGE), &[3, b'a', b'b', b'c'], &limits).2,
DecodeErrorKind::TooLarge
);
}
#[test]
fn a_count_the_bytes_left_cannot_hold_is_refused_before_anything_is_built() {
let (_, problem, kind) = refused(&Type::list(Type::Int), &[0xff, 0xff, 0xff, 0x7f, 0]);
assert_eq!(kind, DecodeErrorKind::Mismatch);
assert!(
problem.contains("more than the 1 bytes left can"),
"{problem}"
);
let limits = Limits {
text_bytes: 3,
..Limits::LANGUAGE
};
let units = decode_bytes(
&catalog(),
&Type::list(Type::Unit),
&[3],
Mode::Reply,
&limits,
)
.expect("three units");
assert!(eq(
&units,
&Value::list([Value::Unit, Value::Unit, Value::Unit])
));
assert_eq!(
refused_within(&Type::list(Type::Unit), &[4], &limits).2,
DecodeErrorKind::TooLarge
);
}
#[test]
fn a_value_inside_a_larger_message_leaves_the_reader_just_past_it() {
let catalog = catalog();
let mut bytes = encode_bytes(&catalog, &Type::Text, &text("ab")).unwrap();
bytes.extend(encode_bytes(&catalog, &Type::Int, &int("-3")).unwrap());
let mut reader = Reader::new(&bytes);
let first = read_value(
&mut reader,
&catalog,
&Type::Text,
Mode::Reply,
&Limits::LANGUAGE,
);
assert!(eq(&first.unwrap(), &text("ab")));
assert_eq!(reader.position(), 3);
let second = read_value(
&mut reader,
&catalog,
&Type::Int,
Mode::Reply,
&Limits::LANGUAGE,
);
assert!(eq(&second.unwrap(), &int("-3")));
assert!(reader.is_empty());
}
#[test]
fn every_value_round_trips_through_its_one_encoding() {
let catalog = catalog();
let mut draw = Draw::new(0x0b1a_51de);
for ty in kinds() {
for _ in 0..200 {
let value = value(&catalog, &ty, &mut draw, 3);
let bytes = encode_bytes(&catalog, &ty, &value).expect("encodes");
let back = decode_bytes(&catalog, &ty, &bytes, Mode::Reply, &Limits::LANGUAGE)
.unwrap_or_else(|error| panic!("{ty:?} {value:?}: {error}"));
assert!(
same(&catalog, &ty, &value, &back),
"{ty:?}: {value:?} / {back:?}"
);
assert_eq!(
encode_bytes(&catalog, &ty, &back).unwrap(),
bytes,
"one encoding for {value:?}"
);
}
}
}
#[test]
fn equal_values_have_one_encoding_and_different_values_different_ones() {
let catalog = catalog();
let mut draw = Draw::new(7);
for ty in kinds() {
let values: Vec<Value> = (0..60)
.map(|_| value(&catalog, &ty, &mut draw, 2))
.collect();
for a in &values {
for b in &values {
let same_value = same(&catalog, &ty, a, b);
let same_bytes = encode_bytes(&catalog, &ty, a).unwrap()
== encode_bytes(&catalog, &ty, b).unwrap();
assert_eq!(same_value, same_bytes, "{ty:?}: {a:?} and {b:?}");
}
}
}
}
#[test]
fn no_cut_short_encoding_is_a_value() {
let catalog = catalog();
let mut draw = Draw::new(11);
for ty in kinds() {
for _ in 0..40 {
let value = value(&catalog, &ty, &mut draw, 3);
let bytes = encode_bytes(&catalog, &ty, &value).unwrap();
for end in 0..bytes.len() {
assert!(
decode_bytes(&catalog, &ty, &bytes[..end], Mode::Reply, &Limits::LANGUAGE)
.is_err(),
"{ty:?}: {:?} of {bytes:?}",
&bytes[..end]
);
}
}
}
}
#[test]
fn a_scalar_is_written_and_read_as_a_part_alone() {
let cases = [
(Scalar::Unit, Value::Unit, vec![]),
(Scalar::Bool, Value::Bool(true), vec![1]),
(Scalar::Int, int("-65"), vec![0x81, 0x01]),
(Scalar::Decimal, dec("1.5"), vec![30, 1]),
(Scalar::Duration, duration("90"), vec![18, 2]),
(Scalar::Instant, instant("1.5"), vec![30, 1]),
];
for (scalar, value, expected) in cases {
let mut out = Vec::new();
write_scalar(&mut out, scalar, &value).expect("a value of the scalar");
assert_eq!(out, expected, "{scalar:?}");
let mut reader = Reader::new(&out);
let back = read_scalar(&mut reader, scalar, &Limits::LANGUAGE).expect("reads back");
assert!(eq(&back, &value), "{scalar:?}");
assert!(reader.is_empty());
}
let error = write_scalar(&mut Vec::new(), Scalar::Int, &text("a")).unwrap_err();
assert_eq!(error.problem, "is not a value of Int");
}
#[test]
fn a_types_form_looks_up_its_declaration_with_its_arguments_in_place() {
let catalog = catalog();
let boxed = Type::Named(BOXED, vec![Type::list(Type::Int)]);
let Form::Record(record) = form(&catalog, &boxed) else {
panic!("Boxed is a record")
};
assert_eq!(record.shape.fields().collect::<Vec<_>>(), ["value"]);
assert_eq!(record.fields, [Type::list(Type::Int)]);
let tree_of_text = tree(Type::Text);
let Form::Enum(tree_form) = form(&catalog, &tree_of_text) else {
panic!("Tree is an enum")
};
assert_eq!(tree_form.parts(0), Some(vec![Cow::Owned(Type::Text)]));
assert_eq!(
tree_form.parts(1),
Some(vec![Cow::Owned(Type::list(tree(Type::Text)))])
);
assert_eq!(tree_form.parts(2), None);
let option_of_int = Type::option(Type::Int);
let Form::Enum(option) = form(&catalog, &option_of_int) else {
panic!("Option is an enum")
};
assert_eq!(option.parts(0), Some(vec![]));
assert_eq!(option.parts(1), Some(vec![Cow::Owned(Type::Int)]));
let json_type = Type::Json;
let Form::Enum(json) = form(&catalog, &json_type) else {
panic!("json.Value is an enum")
};
assert_eq!(
json.parts(4),
Some(vec![Cow::Owned(Type::list(Type::Json))])
);
assert_eq!(
json.parts(5),
Some(vec![Cow::Owned(Type::dict(Type::Text, Type::Json))])
);
assert!(matches!(
form(&catalog, &Type::Int),
Form::Scalar(Scalar::Int)
));
assert!(matches!(form(&catalog, &named(PAGE)), Form::Host));
assert!(matches!(form(&catalog, &Type::Param(0)), Form::NoEncoding));
}
#[test]
fn crc32c_matches_the_castagnoli_check_values() {
assert_eq!(crc32c(b""), 0);
assert_eq!(crc32c(b"123456789"), 0xe306_9283);
assert_eq!(crc32c(&[0u8; 32]), 0x8a91_36aa);
assert_eq!(crc32c(&[0xffu8; 32]), 0x62a8_ab43);
let ascending: Vec<u8> = (0..32).collect();
assert_eq!(crc32c(&ascending), 0x46dd_794e);
}
#[test]
fn crc32c_taken_a_piece_at_a_time_is_the_crc_of_the_whole() {
let mut crc = Crc32c::new();
crc.update(b"1234").update(b"").update(b"56789");
assert_eq!(crc.finish(), crc32c(b"123456789"));
}
#[test]
fn a_long_crc_is_the_crc_taken_a_few_bytes_at_a_time() {
let bytes: Vec<u8> = (0u32..10_007)
.map(|i| i.wrapping_mul(2_654_435_761).to_le_bytes()[3])
.collect();
let mut pieces = Crc32c::new();
for piece in bytes.chunks(7) {
pieces.update(piece);
}
for length in [3 * 1024 - 1, 3 * 1024, 3 * 1024 + 23, bytes.len()] {
let mut short = Crc32c::new();
for piece in bytes[..length].chunks(7) {
short.update(piece);
}
assert_eq!(crc32c(&bytes[..length]), short.finish(), "{length} bytes");
}
assert_eq!(crc32c(&bytes), pieces.finish());
}
#[test]
fn a_crc_over_any_range_follows_from_two_prefixes_taken_from_nothing() {
let bytes: Vec<u8> = (0u32..600)
.map(|i| (i * 131 + 7).to_le_bytes()[0])
.collect();
let prefix = |end: usize| {
let mut raw = Crc32c::raw();
raw.update(&bytes[..end]);
raw
};
for (from, to) in [(0, 0), (0, 600), (5, 5), (17, 300), (299, 600), (1, 2)] {
let head = b"salt then a position";
let mut direct = Crc32c::new();
direct.update(head).update(&bytes[from..to]);
let mut started = Crc32c::new();
started.update(head);
let length = u64::try_from(to - from).expect("a short range");
let range = prefix(to).xor(&prefix(from).zeros(length));
assert_eq!(
started.zeros(length).xor(&range).finish(),
direct.finish(),
"{from}..{to}"
);
}
}
#[test]
fn the_data_version_is_written_major_dot_minor() {
assert_eq!(DATA_VERSION.to_string(), "6.0");
assert_eq!(DataVersion::parse("6.0"), Some(DATA_VERSION));
assert_eq!(
DataVersion::parse("12.0"),
Some(DataVersion {
major: 12,
minor: 0
})
);
for other in ["0", "0.2.1", "00.2", "0.02", "+0.2", "0.-2", "a.b", ""] {
assert_eq!(DataVersion::parse(other), None, "{other}");
}
}
#[test]
fn a_reader_reads_its_own_major_up_to_its_own_minor() {
let version = |major, minor| DataVersion { major, minor };
let ours = version(1, 3);
assert!(ours.reads(&version(1, 0)));
assert!(ours.reads(&version(1, 3)));
assert!(!ours.reads(&version(1, 4)));
assert!(!ours.reads(&version(0, 3)));
assert!(!ours.reads(&version(2, 0)));
}
#[test]
fn a_negative_int_one_past_the_size_limit_is_refused_as_a_limit() {
let limits = Limits {
int_bits: 8,
..Limits::LANGUAGE
};
let (_, problem, kind) = refused_within(&Type::Int, &signed("-256"), &limits);
assert_eq!(kind, DecodeErrorKind::TooLarge);
assert!(problem.contains("larger than 8 bits"), "{problem}");
}
#[test]
fn a_default_crc32c_is_a_new_one() {
let mut crc = Crc32c::default();
crc.update(b"123456789");
assert_eq!(crc.finish(), crc32c(b"123456789"));
}
#[test]
fn a_declaration_with_no_values_has_no_encoding() {
let socket = Type::Named(flow_types::DeclId(0), vec![]);
assert!(matches!(
form(&phantom_catalog(), &socket),
Form::NoEncoding
));
}
#[test]
fn a_form_is_read_as_the_record_enum_or_list_it_is_and_as_nothing_else() {
let catalog = catalog();
let plan = named(PLAN);
let status = named(STATUS);
let list = Type::list(Type::Int);
assert!(form(&catalog, &plan).record().is_some());
assert!(form(&catalog, &status).enumeration().is_some());
assert_eq!(form(&catalog, &list).list(), Some(&Type::Int));
for ty in [&plan, &status, &list] {
let shapes = [
form(&catalog, ty).record().is_some(),
form(&catalog, ty).enumeration().is_some(),
form(&catalog, ty).list().is_some(),
];
assert_eq!(shapes.iter().filter(|shape| **shape).count(), 1, "{ty:?}");
}
}
#[test]
fn a_declared_type_s_arguments_are_its_own_and_another_type_has_none() {
let page = Type::Named(PAGE, vec![Type::Int]);
assert_eq!(page.args(), &[Type::Int]);
assert_eq!(Type::list(Type::Int).args().len(), 0);
}