#![allow(
unreachable_pub,
reason = "public native boundary fixtures inside a private test module"
)]
use std::collections::{BTreeMap, BTreeSet};
use flow_abi::primitives::Reader;
use flow_abi::{Catalog, Limits, Mode};
use flow_toolkit::{Encoded, Flow, Int, Shaped};
use flow_types::{Body, DeclId, Type};
use flow_types::{Constructor, EnumShape, Payload};
use crate::test_types::{catalog, newtype, record};
#[derive(Flow, Clone, PartialEq, Eq, Debug)]
pub struct Container<T: Ord> {
pub items: BTreeSet<T>,
pub fixed: Int,
}
#[derive(Flow, Clone, PartialEq, Eq, Debug)]
pub enum Choice<T> {
Empty,
One(T),
Pair(T, Int),
Named { value: T, fixed: Int },
}
#[derive(Flow, Clone, PartialEq, Eq, Debug)]
pub struct Chain<T> {
pub head: T,
pub next: Option<Box<Chain<T>>>,
}
#[derive(Flow, Clone, Debug)]
#[flow(std = "code.Bundle")]
pub struct Bundle(pub Encoded);
const CONTAINER: DeclId = DeclId(0);
const CHOICE: DeclId = DeclId(1);
const CHAIN: DeclId = DeclId(2);
const ORDER: DeclId = DeclId(3);
fn fixtures() -> Catalog {
let param = Type::Param(0);
let choice = flow_types::Decl {
body: Body::Enum(
EnumShape::new(
"Choice",
[
Constructor::new("Empty", Payload::None),
Constructor::new("One", Payload::Positional(1)),
Constructor::new("Pair", Payload::Positional(2)),
Constructor::new("Named", Payload::named(["value", "fixed"])),
],
),
vec![
vec![],
vec![param.clone()],
vec![param.clone(), Type::Int],
vec![param.clone(), Type::Int],
],
),
..record("Choice", &[], &["T"])
};
catalog(vec![
record(
"Container",
&[("items", Type::set(param.clone())), ("fixed", Type::Int)],
&["T"],
),
choice,
record(
"Chain",
&[
("head", param.clone()),
("next", Type::option(Type::Named(CHAIN, vec![param]))),
],
&["T"],
),
newtype("OrderId", Type::Text, &[]),
])
}
fn bytes(catalog: &Catalog, ty: &Type, json: &str) -> Vec<u8> {
let json = flow_abi::parse(json, &Limits::default()).expect("JSON");
let value = flow_abi::decode(catalog, ty, &json, Mode::Rebuild, &Limits::default())
.expect("the JSON form decodes at its type");
let mut out = Vec::new();
flow_abi::write_value(&mut out, catalog, ty, &value).expect("it encodes");
out
}
fn form(catalog: &Catalog, ty: &Type, bytes: &[u8]) -> String {
let value =
flow_abi::decode_bytes(catalog, ty, bytes, Mode::Rebuild, &Limits::default()).unwrap();
flow_abi::encode(catalog, ty, &value)
.expect("a JSON form")
.canonical()
}
fn read_bytes<T: Shaped>(catalog: &Catalog, ty: &Type, held: &[u8]) -> Option<T> {
let mut reader = Reader::new(held);
let value = flow_abi::read_shaped(&mut reader, catalog, ty, Mode::Rebuild, &Limits::default());
value.ok().filter(|_| reader.is_empty())
}
fn read<T: Shaped>(catalog: &Catalog, ty: &Type, json: &str) -> T {
read_bytes(catalog, ty, &bytes(catalog, ty, json)).expect("it is one of the Rust type's")
}
fn write<T: Shaped>(catalog: &Catalog, ty: &Type, value: &T) -> Option<Vec<u8>> {
let mut out = Vec::new();
flow_abi::write_shaped(&mut out, catalog, ty, value).ok()?;
Some(out)
}
fn written<T: Shaped>(catalog: &Catalog, ty: &Type, value: &T) -> String {
let out = write(catalog, ty, value).expect("it writes at its type");
form(catalog, ty, &out)
}
fn round_trip<T: Shaped>(catalog: &Catalog, ty: &Type, json: &str) -> String {
written(catalog, ty, &read::<T>(catalog, ty, json))
}
fn crossings() -> Vec<(Type, &'static str)> {
vec![
(Type::Unit, "[]"),
(Type::Bool, "true"),
(Type::Int, "-7"),
(Type::Text, r#""é""#),
(Type::Decimal, "1.5"),
(Type::Bytes, r#""AAE=""#),
(Type::Duration, r#""PT1S""#),
(Type::Instant, r#""2026-01-01T00:00:00Z""#),
(Type::Json, r#"{"a":[1,2.5,null,true,"x"]}"#),
(Type::list(Type::Int), "[3,1]"),
(Type::set(Type::Int), "[1,2]"),
(Type::dict(Type::Text, Type::Int), r#"{"a":1}"#),
(Type::Tuple(vec![Type::Int, Type::Text]), r#"[1,"a"]"#),
(Type::option(Type::Int), r#"{"Some":4}"#),
(Type::Named(ORDER, vec![]), r#""o-1""#),
(
Type::Named(CONTAINER, vec![Type::Text]),
r#"{"fixed":3,"items":["a","b"]}"#,
),
(Type::Named(CHOICE, vec![Type::Int]), r#"{"Pair":[1,2]}"#),
(
Type::Named(CHAIN, vec![Type::Named(ORDER, vec![])]),
r#"{"head":"a","next":{"head":"b"}}"#,
),
]
}
#[test]
fn an_encoded_value_crosses_unchanged_at_every_type() {
let types = fixtures();
for (ty, json) in crossings() {
let held = bytes(&types, &ty, json);
let encoded = read::<Encoded>(&types, &ty, json);
assert_eq!(write(&types, &ty, &encoded), Some(held.clone()), "{json}");
assert_eq!(
Encoded::new(&types, &ty, held.clone())
.ok()
.and_then(|made| write(&types, &ty, &made)),
Some(held),
"{json}"
);
}
}
#[test]
fn an_encoded_value_is_written_only_at_a_type_its_bytes_are_a_value_of() {
let types = fixtures();
let text = read::<Encoded>(&types, &Type::Text, r#""1""#);
assert!(write(&types, &Type::Int, &text).is_none());
let three = read::<Encoded>(&types, &Type::list(Type::Int), "[1,2,3]");
assert!(write(&types, &Type::Tuple(vec![Type::Int; 3]), &three).is_none());
assert!(Encoded::new(&types, &Type::Int, bytes(&types, &Type::Text, r#""1""#)).is_err());
let mut cut = bytes(&types, &Type::list(Type::Int), "[1,2]");
cut.pop();
assert!(Encoded::new(&types, &Type::list(Type::Int), cut).is_err());
}
#[test]
fn encoded_values_are_equal_when_they_are_one_value() {
let types = fixtures();
let one = read::<Encoded>(&types, &Type::Int, "7");
assert_eq!(one, read::<Encoded>(&types, &Type::Int, "7"));
assert_ne!(one, read::<Encoded>(&types, &Type::Int, "8"));
let ints = Type::set(Type::Int);
let read = read::<BTreeSet<Encoded>>(&types, &ints, "[1,2,3]");
assert_eq!(read.len(), 3);
let mut doubled = read;
doubled.insert(one.clone());
doubled.insert(one);
assert_eq!(written(&types, &ints, &doubled), "[1,2,3,7]");
}
#[test]
fn an_encoded_value_shows_only_its_length() {
let types = fixtures();
let held = read::<Encoded>(&types, &Type::Text, r#""secret""#);
assert_eq!(format!("{held:?}"), "Encoded(7 bytes)");
}
#[test]
fn a_derived_generic_type_reads_its_type_parameter_at_the_calls_concrete_type() {
let types = fixtures();
let container = Type::Named(CONTAINER, vec![Type::Int]);
let read = read::<Container<Int>>(&types, &container, r#"{"items":[9,2],"fixed":1}"#);
assert_eq!(
read,
Container {
items: BTreeSet::from([Int::from(2), Int::from(9)]),
fixed: Int::from(1)
}
);
assert_eq!(
written(&types, &container, &read),
r#"{"fixed":1,"items":[2,9]}"#
);
let numbers = Type::Named(CONTAINER, vec![Type::Int]);
assert_eq!(
round_trip::<Container<Encoded>>(&types, &numbers, r#"{"items":[10,2,300],"fixed":1}"#),
r#"{"fixed":1,"items":[2,10,300]}"#,
"a set of encoded values is written in Flow's order, not their bytes'"
);
let choice = Type::Named(CHOICE, vec![Type::Named(ORDER, vec![])]);
for json in [
r#""Empty""#,
r#"{"One":"a"}"#,
r#"{"Pair":["a",2]}"#,
r#"{"Named":{"fixed":3,"value":"b"}}"#,
] {
assert_eq!(round_trip::<Choice<Encoded>>(&types, &choice, json), json);
}
let chain = Type::Named(CHAIN, vec![Type::list(Type::Int)]);
let json = r#"{"head":[1],"next":{"head":[2,3]}}"#;
assert_eq!(round_trip::<Chain<Encoded>>(&types, &chain, json), json);
let nested = Type::list(Type::set(Type::Int));
assert_eq!(
round_trip::<Vec<BTreeSet<Int>>>(&types, &nested, "[[9,2],[1]]"),
"[[2,9],[1]]"
);
let maybe = Type::option(Type::dict(Type::Int, Type::Text));
assert_eq!(
round_trip::<Option<BTreeMap<Int, Encoded>>>(
&types,
&maybe,
r#"{"Some":[[9,"a"],[2,"b"]]}"#
),
r#"{"Some":[[2,"b"],[9,"a"]]}"#
);
}
#[derive(Flow, Clone, Debug)]
pub struct Stamp<T> {
pub at: T,
}
#[derive(Flow, Clone, Debug)]
pub enum Mark<T> {
Placed { at: T },
}
#[test]
fn a_derived_type_reads_a_field_by_any_name_its_declaration_gives() {
let types = catalog(vec![
record("Stamp", &[("at", Type::Param(0))], &["T"]),
flow_types::Decl {
body: Body::Enum(
EnumShape::new("Mark", [Constructor::new("Placed", Payload::named(["at"]))]),
vec![vec![Type::Param(0)]],
),
..record("Mark", &[], &["T"])
},
]);
let stamp = Type::Named(DeclId(0), vec![Type::Int]);
assert_eq!(
round_trip::<Stamp<Encoded>>(&types, &stamp, r#"{"at":4}"#),
r#"{"at":4}"#
);
let mark = Type::Named(DeclId(1), vec![Type::Text]);
let json = r#"{"Placed":{"at":"here"}}"#;
assert_eq!(round_trip::<Mark<Encoded>>(&types, &mark, json), json);
}
#[test]
fn a_derived_type_read_at_another_shape_is_refused() {
let types = fixtures();
let wrong = Type::Named(CHAIN, vec![Type::Int]);
let chain = bytes(&types, &wrong, r#"{"head":1}"#);
assert!(read_bytes::<Container<Int>>(&types, &wrong, &chain).is_none());
let container = Container {
items: BTreeSet::from(["x".to_owned()]),
fixed: Int::from(0),
};
assert!(
write(&types, &Type::Named(CONTAINER, vec![Type::Int]), &container).is_none(),
"a set of text is no set of integers"
);
}
#[test]
fn a_set_or_dictionary_written_from_rust_follows_flows_order() {
let types = fixtures();
let texts = BTreeSet::from(["é".to_owned(), "z".to_owned(), "a".to_owned()]);
assert_eq!(
written(&types, &Type::set(Type::Text), &texts),
r#"["a","z","é"]"#,
"text by code point"
);
let dict = Type::dict(Type::Int, Type::Text);
assert_eq!(
round_trip::<BTreeMap<Int, String>>(&types, &dict, r#"[[10,"ten"],[2,"two"]]"#),
r#"[[2,"two"],[10,"ten"]]"#,
"a dictionary in ascending key order"
);
}
#[test]
fn a_std_value_carried_whole_is_read_and_written_at_its_declaration() {
let types = fixtures();
let order = Type::Named(ORDER, vec![]);
let bundle = read::<Bundle>(&types, &order, r#""b-1""#);
assert_eq!(written(&types, &order, &bundle), r#""b-1""#);
}
#[test]
fn a_tuple_reads_and_writes_each_part_at_its_type() {
let types = fixtures();
let pair = Type::Tuple(vec![Type::Int, Type::Text]);
assert_eq!(
round_trip::<(Int, String)>(&types, &pair, r#"[1,"a"]"#),
r#"[1,"a"]"#
);
let triple = Type::Tuple(vec![Type::Int, Type::Text, Type::Int]);
let three = bytes(&types, &triple, r#"[1,"a",2]"#);
assert!(
read_bytes::<(Int, String)>(&types, &triple, &three).is_none(),
"a pair is not read at a triple"
);
}
#[test]
fn an_option_refuses_a_constructor_it_does_not_have() {
let types = fixtures();
let maybe = Type::option(Type::Int);
let refused = flow_abi::decode_bytes(&types, &maybe, &[2], Mode::Rebuild, &Limits::default())
.expect_err("an Option has two constructors");
assert!(refused.to_string().contains("Option"), "{refused}");
}
#[test]
fn a_result_is_no_value_of_another_type() {
let types = fixtures();
let one = bytes(&types, &Type::Int, "1");
assert!(read_bytes::<Result<Int, String>>(&types, &Type::Int, &one).is_none());
}
#[test]
fn each_native_type_is_named_as_flow_source_names_it() {
use crate::function::Owner;
use flow_abi::contract::TypeRef;
use flow_toolkit::{Decimal, Duration};
let mut types = flow_toolkit::__bridge::Types::default();
assert_eq!(types.form(Decimal::FORM), TypeRef::named("Decimal"));
assert_eq!(
types.form(Duration::FORM),
TypeRef::qualified(Owner::Std("duration"), "Duration")
);
assert_eq!(
types.form(std::path::PathBuf::FORM),
TypeRef::qualified(Owner::Std("path"), "Path")
);
}
#[test]
fn a_native_form_is_held_by_its_std_declaration() {
use flow_toolkit::Url;
use flow_types::{Identity, ModulePath, Segments, Tree};
let path = flow_types::Decl {
identity: Identity {
origin: ModulePath::new(
Tree::Std,
None,
"path".parse::<Segments>().expect("a test path is a path"),
),
version: Some("v1".into()),
name: "Path".into(),
},
..newtype("Path", Type::Text, &[])
};
let types = catalog(vec![path]);
let path = Type::Named(DeclId(0), vec![]);
assert!(write(&types, &path, &std::path::PathBuf::from("a/b")).is_some());
let url = Url::parse("http://example.com/").expect("a URL");
assert!(write(&types, &path, &url).is_none());
}
#[test]
fn a_set_or_dictionary_cut_short_refuses_to_read() {
let types = fixtures();
let set = Type::set(Type::Int);
let mut held = bytes(&types, &set, "[1,2]");
held.pop();
let cut = |ty: &Type, held: &[u8]| {
flow_abi::read_value(
&mut Reader::new(held),
&types,
ty,
Mode::Rebuild,
&Limits::default(),
)
.is_err()
};
assert!(cut(&set, &held));
let dict = Type::dict(Type::Text, Type::Int);
let mut held = bytes(&types, &dict, r#"{"a":1,"b":2}"#);
held.pop();
assert!(cut(&dict, &held));
}
#[test]
fn a_host_value_crosses_as_its_token() {
let types = catalog(vec![flow_types::Decl {
body: Body::Host,
..record("Handle", &[], &[])
}]);
let handle = Type::Named(DeclId(0), vec![]);
let value = read::<Encoded>(&types, &handle, r#""h-1""#);
assert_eq!(written(&types, &handle, &value), r#""h-1""#);
}
#[test]
fn a_type_parameters_place_holder_has_no_values() {
use flow_toolkit::__bridge::wire::Param;
let types = fixtures();
let unit = bytes(&types, &Type::Unit, "[]");
assert!(read_bytes::<Param<0>>(&types, &Type::Unit, &unit).is_none());
}
#[test]
fn a_tool_problem_is_named_as_std_declares_it() {
let mut named = flow_toolkit::__bridge::Types::default();
assert_eq!(
named.form(flow_toolkit::ToolProblem::FORM),
flow_abi::contract::TypeRef::named("ToolProblem")
);
}