use std::convert::TryFrom;
use typeshaper::{RequiredError, typeshaper, typex};
#[typeshaper]
#[derive(Debug, Clone, PartialEq)]
pub struct WithOptionFields {
pub maybe_name: Option<String>, pub count: u32,
}
typex!(
#[derive(Debug, Clone, PartialEq)]
WithOptionFieldsPartial = WithOptionFields?
);
#[test]
fn issue2_partial_preserves_existing_option_fields() {
let original = WithOptionFields {
maybe_name: Some("alice".into()),
count: 10,
};
let partial = WithOptionFieldsPartial::from(original);
assert_eq!(partial.maybe_name, Some("alice".to_string()));
assert_eq!(partial.count, Some(10));
}
#[test]
fn issue2_partial_none_stays_none() {
let original = WithOptionFields { maybe_name: None, count: 0 };
let partial = WithOptionFieldsPartial::from(original);
assert_eq!(partial.maybe_name, None); assert_eq!(partial.count, Some(0));
}
#[typeshaper]
#[derive(Debug, Clone, PartialEq)]
pub struct Simple { pub x: u32, pub y: u32 }
typex!(#[derive(Debug, Clone, PartialEq)] SimpleDraft = Simple?);
typex!(#[derive(Debug, Clone, PartialEq)] SimpleDraft2 = SimpleDraft?);
#[test]
fn issue2_partial_is_idempotent_on_partial_derived_type() {
let draft = SimpleDraft { x: Some(1), y: Some(2) };
let draft2 = SimpleDraft2::from(draft);
assert_eq!(draft2.x, Some(1));
assert_eq!(draft2.y, Some(2));
}
#[typeshaper]
#[derive(Debug, Clone, PartialEq)]
pub struct MixedOptional {
pub id: u64, pub name: Option<String>, }
typex!(#[derive(Debug, Clone, PartialEq)] MixedRequired = MixedOptional!);
#[test]
fn issue2_required_unwraps_option_fields_keeps_plain_fields() {
let mixed = MixedOptional { id: 42, name: Some("bob".into()) };
let required = MixedRequired::try_from(mixed).expect("name is Some");
assert_eq!(required.id, 42); assert_eq!(required.name, "bob"); }
#[test]
fn issue2_required_on_mixed_type_errors_when_option_field_is_none() {
let mixed = MixedOptional { id: 99, name: None };
let err = MixedRequired::try_from(mixed).unwrap_err();
assert_eq!(err, RequiredError::new("name"));
}
#[typeshaper]
#[derive(Debug, Clone, PartialEq)]
pub struct LeftStruct {
pub id: u64,
pub name: String,
pub score: u32,
}
#[typeshaper]
#[derive(Debug, Clone, PartialEq)]
pub struct RightStruct {
pub id: String, pub extra: bool,
}
typex!(
#[derive(Debug, Clone, PartialEq)]
DiffResult = LeftStruct % RightStruct
);
#[test]
fn issue3_diff_keeps_field_when_types_differ() {
let result = DiffResult { id: 99, name: "alice".into(), score: 42 };
assert_eq!(result.id, 99);
assert_eq!(result.name, "alice");
assert_eq!(result.score, 42);
}
#[typeshaper]
#[derive(Debug, Clone, PartialEq)]
pub struct RightSameType {
pub id: u64, }
typex!(
#[derive(Debug, Clone, PartialEq)]
DiffSameType = LeftStruct % RightSameType
);
#[test]
fn issue3_diff_excludes_field_when_name_and_type_both_match() {
let result = DiffSameType { name: "bob".into(), score: 7 };
assert_eq!(result.name, "bob");
assert_eq!(result.score, 7);
}