#![allow(missing_docs, clippy::unwrap_used, clippy::expect_used)] use std::collections::BTreeMap;
use std::marker::PhantomData;
use indexmap::IndexMap;
use oxblade::shape::{
Direction, EnumTag, FieldDesc, Presence, TupleElement, TypeDesc, TypeRegistry,
};
use oxblade::{Html, Shape, Shared, Text, View, view};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
fn resolve<'a>(
mut desc: &'a TypeDesc,
registry: &'a TypeRegistry,
direction: Direction,
) -> &'a TypeDesc {
while let TypeDesc::Ref(name) = desc {
desc = ®istry.get(name, direction).unwrap().ty;
}
desc
}
fn fields<T: Shape>(direction: Direction) -> Vec<FieldDesc> {
let mut registry = TypeRegistry::default();
let desc = T::describe(&mut registry, direction);
let TypeDesc::Struct(fields) = resolve(&desc, ®istry, direction) else {
panic!("expected a struct");
};
fields.clone()
}
fn matches_output(desc: &TypeDesc, json: &Value, registry: &TypeRegistry) -> bool {
match resolve(desc, registry, Direction::Serialize) {
TypeDesc::Null => json.is_null(),
TypeDesc::Bool => json.is_boolean(),
TypeDesc::Int => json.is_i64() || json.is_u64(),
TypeDesc::Float => json.is_f64(),
TypeDesc::String | TypeDesc::Html | TypeDesc::Date => json.is_string(),
TypeDesc::Text => json.is_null() || json.is_string() || json.is_number(),
TypeDesc::Literal(value) => json.as_str() == Some(value),
TypeDesc::Option(inner) => json.is_null() || matches_output(inner, json, registry),
TypeDesc::List { element, length } => json.as_array().is_some_and(|values| {
length.is_none_or(|length| length == values.len())
&& values
.iter()
.all(|value| matches_output(element, value, registry))
}),
TypeDesc::Tuple(elements) => json
.as_array()
.is_some_and(|values| matches_tuple(elements, values, registry)),
TypeDesc::Map { key, value } => json.as_object().is_some_and(|entries| {
entries.iter().all(|(name, item)| {
matches_key(key, name, registry) && matches_output(value, item, registry)
})
}),
TypeDesc::Struct(fields) => json.as_object().is_some_and(|object| {
let mut leftovers = object.clone();
for field in fields.iter().filter(|field| !field.flatten) {
match leftovers.shift_remove(field.name) {
Some(value) if matches_output(&field.ty, &value, registry) => {}
None if field.presence == Presence::Absent => {}
_ => return false,
}
}
for field in fields.iter().filter(|field| field.flatten) {
match resolve(&field.ty, registry, Direction::Serialize) {
TypeDesc::Struct(nested) => {
let part: serde_json::Map<String, Value> = nested
.iter()
.filter_map(|field| leftovers.shift_remove_entry(field.name))
.collect();
if !matches_output(&field.ty, &Value::Object(part), registry) {
return false;
}
}
_ => return matches_output(&field.ty, &Value::Object(leftovers), registry),
}
}
leftovers.is_empty()
}),
TypeDesc::Enum(desc) => desc.variants.iter().any(|variant| {
let payload_matches = |value: &Value| {
variant.payload.as_ref().map_or_else(
|| Value::is_null(value),
|payload| matches_output(payload, value, registry),
)
};
if variant.untagged || desc.tag == EnumTag::Untagged {
return payload_matches(json);
}
match desc.tag {
EnumTag::External if variant.payload.is_none() => {
json.as_str() == Some(variant.name)
}
EnumTag::External => json.as_object().is_some_and(|object| {
object.len() == 1 && object.get(variant.name).is_some_and(payload_matches)
}),
EnumTag::Internal { tag } => json.as_object().is_some_and(|object| {
let mut rest = object.clone();
let tag_matches = rest.shift_remove(tag).as_ref().and_then(Value::as_str)
== Some(variant.name);
tag_matches
&& if variant.payload.is_none() {
rest.is_empty()
} else {
payload_matches(&Value::Object(rest))
}
}),
EnumTag::Adjacent { tag, content } => json.as_object().is_some_and(|object| {
object.get(tag).and_then(Value::as_str) == Some(variant.name)
&& if variant.payload.is_none() {
object.len() == 1
} else {
object.len() == 2 && object.get(content).is_some_and(payload_matches)
}
}),
EnumTag::Untagged => unreachable!(),
}
}),
TypeDesc::Union(types) => types
.iter()
.any(|desc| matches_output(desc, json, registry)),
TypeDesc::Any => true,
TypeDesc::Display { ty, .. } => matches_output(ty, json, registry),
TypeDesc::Ref(_) => unreachable!(),
}
}
fn matches_key(desc: &TypeDesc, name: &str, registry: &TypeRegistry) -> bool {
match resolve(desc, registry, Direction::Serialize) {
TypeDesc::Int => name.parse::<i128>().is_ok(),
_ => matches_output(desc, &json!(name), registry),
}
}
fn matches_tuple(elements: &[TupleElement], values: &[Value], registry: &TypeRegistry) -> bool {
let Some((element, remaining)) = elements.split_first() else {
return values.is_empty();
};
values.split_first().is_some_and(|(value, rest)| {
matches_output(&element.ty, value, registry) && matches_tuple(remaining, rest, registry)
}) || (element.omittable && matches_tuple(remaining, values, registry))
}
fn output<T: Shape + Serialize>(data: T, expected: Value) {
let json = serde_json::to_value(data).unwrap();
assert_eq!(json, expected);
let mut registry = TypeRegistry::default();
let shape = T::serialize_shape(&mut registry);
assert!(
matches_output(&shape, &json, ®istry),
"{json} did not match {shape:?} with {registry:#?}"
);
}
#[derive(Debug, Default, PartialEq, Serialize, Deserialize, Shape)]
struct Name {
visible_name: String,
}
#[derive(Debug, PartialEq, Serialize, Deserialize, Shape)]
#[serde(rename_all(serialize = "camelCase", deserialize = "kebab-case"))]
struct Directional {
first_name: String,
#[serde(
rename(serialize = "out", deserialize = "in"),
alias = "older",
alias = "oldest"
)]
directional_name: String,
#[serde(skip)]
skipped: u32,
#[serde(skip_serializing)]
only_input: u32,
#[serde(skip_deserializing)]
only_output: u32,
#[serde(skip_serializing_if = "Option::is_none")]
maybe_omitted: Option<u32>,
nullable_value: Option<u32>,
#[serde(default = "forty_two")]
default_value: u32,
#[serde(flatten)]
name: Name,
}
fn forty_two() -> u32 {
42
}
#[test]
fn directional_names_omissions_aliases_defaults_and_flatten_follow_serde() {
let data: Directional = serde_json::from_value(json!({
"first-name": "Ada", "older": "one", "only-input": 3, "visible_name": "Visible"
}))
.unwrap();
assert_eq!(data.directional_name, "one");
assert_eq!(data.default_value, 42);
assert_eq!(data.only_input, 3);
output(
data,
json!({
"firstName": "Ada", "out": "one", "onlyOutput": 0, "nullableValue": null,
"defaultValue": 42, "visible_name": "Visible"
}),
);
let output_fields = fields::<Directional>(Direction::Serialize);
assert_eq!(
output_fields
.iter()
.map(|field| (field.name, field.presence))
.collect::<Vec<_>>(),
[
("firstName", Presence::Required),
("out", Presence::Required),
("onlyOutput", Presence::Required),
("maybeOmitted", Presence::Absent),
("nullableValue", Presence::Nullable),
("defaultValue", Presence::Required),
("name", Presence::Required),
]
);
assert!(output_fields.last().unwrap().flatten);
assert!(output_fields.iter().all(|field| field.aliases.is_empty()));
let input_fields = fields::<Directional>(Direction::Deserialize);
assert_eq!(
input_fields
.iter()
.map(|field| (field.name, field.presence))
.collect::<Vec<_>>(),
[
("first-name", Presence::Required),
("in", Presence::Required),
("only-input", Presence::Required),
("maybe-omitted", Presence::Absent),
("nullable-value", Presence::Absent),
("default-value", Presence::Absent),
("name", Presence::Required),
]
);
assert_eq!(input_fields[1].aliases, ["older", "oldest"]);
assert!(input_fields.last().unwrap().flatten);
}
macro_rules! rename_case {
($test:ident, $style:literal, $field:literal, $variant:literal) => {
#[test]
fn $test() {
#[derive(Serialize, Deserialize, Shape)]
#[serde(rename_all = $style)]
struct Record { big_name: u8 }
#[derive(Serialize, Deserialize, Shape)]
#[serde(rename_all = $style)]
enum Choice { BigName }
let value = json!({$field: 2});
output(serde_json::from_value::<Record>(value.clone()).unwrap(), value);
let value = json!($variant);
output(serde_json::from_value::<Choice>(value.clone()).unwrap(), value);
}
};
}
rename_case!(lower, "lowercase", "big_name", "bigname");
rename_case!(upper, "UPPERCASE", "BIG_NAME", "BIGNAME");
rename_case!(pascal, "PascalCase", "BigName", "BigName");
rename_case!(camel, "camelCase", "bigName", "bigName");
rename_case!(snake, "snake_case", "big_name", "big_name");
rename_case!(
screaming_snake,
"SCREAMING_SNAKE_CASE",
"BIG_NAME",
"BIG_NAME"
);
rename_case!(kebab, "kebab-case", "big-name", "big-name");
rename_case!(
screaming_kebab,
"SCREAMING-KEBAB-CASE",
"BIG-NAME",
"BIG-NAME"
);
#[derive(Serialize, Deserialize, Shape)]
#[serde(transparent)]
struct Transparent<'a> {
value: &'a str,
marker: PhantomData<u8>,
}
#[derive(Default, Debug, PartialEq, Serialize, Deserialize, Shape)]
#[serde(default)]
struct Defaults {
a: i32,
b: String,
}
#[derive(Serialize, Deserialize, Shape)]
#[serde(tag = "record", rename = "tagged")]
struct TaggedStruct {
num: u8,
}
#[test]
fn transparent_container_default_and_tagged_struct() {
output(
serde_json::from_str::<Transparent<'_>>("\"hello\"").unwrap(),
json!("hello"),
);
assert_eq!(
serde_json::from_value::<Defaults>(json!({})).unwrap(),
Defaults::default()
);
assert!(
fields::<Defaults>(Direction::Deserialize)
.iter()
.all(|field| field.presence == Presence::Absent)
);
assert_eq!(
fields::<TaggedStruct>(Direction::Serialize)[0].ty,
TypeDesc::Literal("tagged")
);
assert_eq!(fields::<TaggedStruct>(Direction::Deserialize).len(), 1);
output(
serde_json::from_value::<TaggedStruct>(json!({"num": 4})).unwrap(),
json!({"record": "tagged", "num": 4}),
);
}
mod as_text {
pub fn serialize<S: serde::Serializer>(value: &u32, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(value)
}
pub fn deserialize<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<u32, D::Error> {
use serde::Deserialize;
String::deserialize(deserializer)?
.parse()
.map_err(serde::de::Error::custom)
}
}
#[derive(Serialize, Deserialize, Shape)]
struct Custom {
#[serde(with = "as_text")]
opaque: u32,
#[serde(with = "as_text")]
#[shape(as = String, display = "money")]
annotated: u32,
#[serde(serialize_with = "as_text::serialize")]
only_serialize: u32,
#[serde(deserialize_with = "as_text::deserialize")]
only_deserialize: u32,
}
#[derive(Clone, Serialize, Deserialize, Shape)]
#[serde(from = "String", into = "String")]
#[shape(as = String)]
struct Converted(String);
impl From<String> for Converted {
fn from(value: String) -> Self {
Self(value)
}
}
impl From<Converted> for String {
fn from(value: Converted) -> Self {
value.0
}
}
#[test]
fn custom_adapters_are_directional_and_can_be_annotated() {
use TypeDesc::{Any, Display, Int, String};
let serialized = fields::<Custom>(Direction::Serialize);
let deserialized = fields::<Custom>(Direction::Deserialize);
let display = Display {
name: "money",
ty: Box::new(String),
};
assert_eq!(
serialized
.into_iter()
.map(|field| field.ty)
.collect::<Vec<_>>(),
[Any, display.clone(), Any, Int]
);
assert_eq!(
deserialized
.into_iter()
.map(|field| field.ty)
.collect::<Vec<_>>(),
[Any, display, Int, Any]
);
output(
serde_json::from_value::<Custom>(json!({
"opaque": "3", "annotated": "4", "only_serialize": 5, "only_deserialize": "6"
}))
.unwrap(),
json!({
"opaque": "3", "annotated": "4", "only_serialize": "5", "only_deserialize": 6
}),
);
output(
serde_json::from_value::<Converted>(json!("wire")).unwrap(),
json!("wire"),
);
}
#[derive(Debug, PartialEq, Serialize, Deserialize, Shape)]
enum External {
#[serde(
rename(serialize = "Ready", deserialize = "ready"),
alias = "legacy-ready"
)]
Ready,
Pair(bool, u8),
#[serde(rename_all = "camelCase")]
Object {
field_name: String,
},
#[serde(skip)]
Hidden,
#[serde(skip_serializing)]
Input,
#[serde(skip_deserializing)]
Output,
Dropped(#[serde(skip)] u8),
#[serde(untagged)]
Fallback(u32),
}
#[derive(Serialize, Deserialize, Shape)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum Internal {
Blank,
OneItem { open: bool },
Wrapped(Name),
}
#[derive(Serialize, Deserialize, Shape)]
#[serde(tag = "kind", content = "data", rename_all_fields = "camelCase")]
enum Adjacent {
Blank,
Scalar(u32),
Named { by_name: String },
Maybe(Option<u32>),
}
#[derive(Serialize, Deserialize, Shape)]
#[serde(untagged)]
enum Untagged {
Scalar(u32),
List(Vec<u32>),
Null,
}
#[test]
fn enums_match_all_serde_tags_and_member_shapes() {
assert_eq!(
serde_json::from_value::<External>(json!("legacy-ready")).unwrap(),
External::Ready
);
assert_eq!(
serde_json::from_value::<External>(json!("Input")).unwrap(),
External::Input
);
assert!(serde_json::to_value(External::Hidden).is_err());
assert!(serde_json::from_value::<External>(json!("Output")).is_err());
let mut registry = TypeRegistry::default();
let input = External::deserialize_shape(&mut registry);
let TypeDesc::Enum(input) = resolve(&input, ®istry, Direction::Deserialize) else {
panic!("expected enum")
};
assert_eq!(
input
.variants
.iter()
.map(|variant| variant.name)
.collect::<Vec<_>>(),
["ready", "Pair", "Object", "Input", "Dropped", "Fallback"]
);
assert_eq!(input.variants[0].aliases, ["legacy-ready"]);
output(External::Ready, json!("Ready"));
output(External::Pair(true, 3), json!({"Pair": [true, 3]}));
output(
External::Object {
field_name: "test".into(),
},
json!({"Object": {"fieldName": "test"}}),
);
output(External::Dropped(2), json!("Dropped"));
output(External::Output, json!("Output"));
output(External::Fallback(9), json!(9));
output(Internal::Blank, json!({"kind": "blank"}));
output(
Internal::OneItem { open: true },
json!({"kind": "one_item", "open": true}),
);
output(
Internal::Wrapped(Name {
visible_name: "nested".into(),
}),
json!({"kind": "wrapped", "visible_name": "nested"}),
);
let input = Adjacent::deserialize_shape(&mut registry);
let TypeDesc::Enum(input) = resolve(&input, ®istry, Direction::Deserialize) else {
panic!("expected enum")
};
assert!(
input
.variants
.iter()
.find(|variant| variant.name == "Maybe")
.unwrap()
.payload_omittable
);
let missing = serde_json::from_value::<Adjacent>(json!({"kind": "Maybe"})).unwrap();
output(missing, json!({"kind": "Maybe", "data": null}));
output(Adjacent::Blank, json!({"kind": "Blank"}));
output(Adjacent::Scalar(2), json!({"kind": "Scalar", "data": 2}));
output(
Adjacent::Named {
by_name: "Ada".into(),
},
json!({"kind": "Named", "data": {"byName": "Ada"}}),
);
output(Untagged::Scalar(2), json!(2));
output(Untagged::List(vec![3]), json!([3]));
output(Untagged::Null, json!(null));
}
#[derive(Serialize, Deserialize, Shape)]
struct ConditionalTuple(
String,
#[serde(default, skip_serializing_if = "Option::is_none")] Option<u32>,
);
#[derive(Serialize, Deserialize, Shape)]
struct WrappedOption(Option<u32>);
#[derive(Serialize, Deserialize, Shape)]
struct RecordWithOption {
nullable: WrappedOption,
optional: Option<u32>,
#[serde(flatten)]
extra: IndexMap<String, u32>,
}
#[test]
fn nullable_newtypes_still_require_the_key_and_flattened_maps_keep_their_types() {
let absent = json!({"dynamic": 1});
assert!(serde_json::from_value::<RecordWithOption>(absent).is_err());
let expected = json!({"nullable": null, "optional": null, "dynamic": 1});
let data = serde_json::from_value::<RecordWithOption>(expected.clone()).unwrap();
output(data, expected);
let input = fields::<RecordWithOption>(Direction::Deserialize);
assert_eq!(input[0].presence, Presence::Nullable);
assert_eq!(input[1].presence, Presence::Absent);
assert!(input[2].flatten);
assert_eq!(
input[2].ty,
TypeDesc::Map {
key: Box::new(TypeDesc::String),
value: Box::new(TypeDesc::Int)
},
);
}
#[derive(Serialize, Shape)]
struct Node<T> {
data: T,
child: Option<Box<Node<T>>>,
}
#[derive(Serialize, Shape)]
struct Collections {
first: IndexMap<u32, bool>,
second: BTreeMap<String, Vec<Option<u32>>>,
tuple: (u8, &'static str),
fixed: [u8; 2],
unknown: Value,
}
#[test]
fn recursive_generic_and_std_shapes_follow_json() {
let data = Node {
data: "root",
child: Some(Box::new(Node {
data: "leaf",
child: None,
})),
};
output(
data,
json!({"data": "root", "child": {"data": "leaf", "child": null}}),
);
let mut registry = TypeRegistry::default();
let TypeDesc::Ref(root) = Node::<u8>::serialize_shape(&mut registry) else {
panic!("expected a reference")
};
let TypeDesc::Struct(fields) = ®istry.get(root, Direction::Serialize).unwrap().ty else {
panic!("expected a struct")
};
assert_eq!(
fields[1].ty,
TypeDesc::Option(Box::new(TypeDesc::Ref(root)))
);
Node::<String>::serialize_shape(&mut registry);
assert_eq!(registry.iter().count(), 2);
let data = Collections {
first: [(2, true), (1, false)].into_iter().collect(),
second: [("a".into(), vec![Some(3), None])].into_iter().collect(),
tuple: (1, "two"),
fixed: [5, 6],
unknown: json!({"dynamic": []}),
};
assert_eq!(
serde_json::to_string(&data.first).unwrap(),
r#"{"2":true,"1":false}"#
);
output(
data,
json!({
"first": {"2": true, "1": false}, "second": {"a": [3, null]}, "tuple": [1, "two"],
"fixed": [5, 6], "unknown": {"dynamic": []}
}),
);
output(
serde_json::from_value::<ConditionalTuple>(json!(["one"])).unwrap(),
json!(["one"]),
);
output(ConditionalTuple("one".into(), Some(4)), json!(["one", 4]));
}
#[derive(Serialize, Shape, View)]
#[view("places.show")]
struct City<'a> {
title: &'a str,
fragments: Vec<Html>,
}
#[derive(Serialize, Shape, Shared)]
struct SharedFacts {
logged_in: bool,
}
#[test]
fn inventory_registers_views_shared_models_and_named_types() {
let template = view(City {
title: "Lagos",
fragments: vec![Html::new("<b>hi</b>")],
});
assert_eq!(template.name, "places.show");
let registered = oxblade::shape::view_models()
.find(|view| view.name == template.name)
.unwrap();
assert!(registered.source.file.ends_with("wp05_shape.rs"));
assert!(registered.source.line > 0 && registered.source.column > 0);
let mut registry = TypeRegistry::default();
let desc = (registered.describe)(&mut registry);
assert_eq!(desc, City::serialize_shape(&mut registry));
output(
template.model,
json!({"title": "Lagos", "fragments": ["<b>hi</b>"]}),
);
let shared = oxblade::shape::shared_models()
.find(|model| (model.type_name)().ends_with("::SharedFacts"))
.unwrap();
(shared.describe)(&mut registry);
registry.register_linked(Direction::Deserialize);
assert!(
registry
.iter()
.any(|(_, direction, entry)| direction == Direction::Deserialize
&& entry.name == "TaggedStruct")
);
assert!(
registry
.iter()
.any(|(_, direction, entry)| direction == Direction::Serialize
&& entry.name == "SharedFacts")
);
assert_eq!(
City {
title: "Paris",
fragments: vec![]
}
.into_view()
.name,
"places.show"
);
}
#[test]
fn text_and_trust_have_distinct_shapes() {
for value in [
json!("47%"),
json!(42),
json!(u64::MAX),
json!(1.5),
json!(null),
] {
let text = serde_json::from_value::<Text>(value.clone()).unwrap();
output(text, value);
}
assert!(serde_json::from_value::<Text>(json!(true)).is_err());
assert_eq!(Text::Empty.to_string(), "");
assert_eq!(Text::Int(7).to_string(), "7");
assert_eq!(
Html::deserialize_shape(&mut TypeRegistry::default()),
TypeDesc::Union(vec![])
);
}
#[cfg(feature = "jiff")]
#[test]
fn jiff_v1_dates_serialize_as_dates() {
let date: jiff::civil::Date = "2026-12-04".parse().unwrap();
assert_eq!(
jiff::civil::Date::serialize_shape(&mut TypeRegistry::default()),
TypeDesc::Date
);
output(date, json!("2026-12-04"));
}
#[cfg(feature = "ulid")]
#[test]
fn ulid_serializes_as_a_string() {
let id = "01ARZ3NDEKTSV4RRFFQ69G5FAV";
output(id.parse::<ulid::Ulid>().unwrap(), json!(id));
}
#[cfg(feature = "uuid")]
#[test]
fn uuid_serializes_as_a_string() {
let id = "a1a1a1a1-9876-1234-beef-0123456789ab";
output(id.parse::<uuid::Uuid>().unwrap(), json!(id));
}
#[cfg(feature = "rust_decimal")]
#[test]
fn decimal_serializes_as_text_and_accepts_numbers() {
output(
"3.40".parse::<rust_decimal::Decimal>().unwrap(),
json!("3.40"),
);
assert_eq!(
serde_json::from_value::<rust_decimal::Decimal>(json!(3.4))
.unwrap()
.to_string(),
"3.4"
);
assert_eq!(
rust_decimal::Decimal::deserialize_shape(&mut TypeRegistry::default()),
TypeDesc::Union(vec![TypeDesc::String, TypeDesc::Int, TypeDesc::Float])
);
}