| // Copyright 2026 The Fuchsia Authors. All rights reserved. | |
| // Use of this source code is governed by a BSD-style license that can be | |
| // found in the LICENSE file. | |
| //! External integration tests for `#[derive(FxfsSerialization)]`. | |
| //! | |
| //! Living in a separate crate outside `fxfs_serialization` ensures the generated | |
| //! `::fxfs_serialization::...` paths only reference public items and work for downstream callers. | |
| use fxfs_serialization::{ | |
| DeserializeError, FxfsSerialization, Reader, SerializeError, Writer, deserialize_from, | |
| }; | |
| /// Serializes `val`, checks `serialized_size` and `T::fingerprint()`, verifies roundtrip | |
| /// deserialization consumes the entire buffer, and confirms every proper prefix fails with | |
| /// [`DeserializeError::UnexpectedEof`]. Returns the serialized bytes. | |
| fn assert_roundtrip<T: FxfsSerialization + PartialEq + std::fmt::Debug>( | |
| val: &T, | |
| expected_fp: &str, | |
| ) -> Vec<u8> { | |
| let mut buf = Vec::new(); | |
| val.serialize_into(&mut buf).unwrap(); | |
| assert_eq!(val.serialized_size(), buf.len() as u64); | |
| assert_eq!(T::fingerprint(), expected_fp); | |
| let mut slice = buf.as_slice(); | |
| let decoded: T = deserialize_from(&mut slice).unwrap(); | |
| assert_eq!(&decoded, val); | |
| assert!(slice.is_empty()); | |
| for prefix_len in 0..buf.len() { | |
| let mut prefix = &buf[..prefix_len]; | |
| assert_eq!( | |
| deserialize_from::<T, _>(&mut prefix), | |
| Err(DeserializeError::UnexpectedEof), | |
| "expected UnexpectedEof on truncated input of len {prefix_len}/{} for {val:?}", | |
| buf.len() | |
| ); | |
| } | |
| buf | |
| } | |
| #[derive(Debug, PartialEq, Eq, FxfsSerialization)] | |
| struct UnitStruct; | |
| #[derive(Debug, PartialEq, Eq, FxfsSerialization)] | |
| struct EmptyNamed {} | |
| #[derive(Debug, PartialEq, Eq, FxfsSerialization)] | |
| struct EmptyTuple(); | |
| #[derive(Debug, PartialEq, Eq, FxfsSerialization)] | |
| struct TupleStruct(u32, String, Option<u64>, [u8; 4]); | |
| #[derive(Debug, PartialEq, Eq, FxfsSerialization)] | |
| struct NamedStruct { | |
| a: u64, | |
| b: String, | |
| c: Option<u32>, | |
| } | |
| #[derive(Debug, PartialEq, Eq, FxfsSerialization)] | |
| struct GenericStruct<T> { | |
| item: T, | |
| count: u32, | |
| } | |
| #[derive(Debug, PartialEq, Eq, FxfsSerialization)] | |
| enum SampleEnum { | |
| Unit, | |
| Tuple(u32, String), | |
| Named { x: u64, y: bool }, | |
| EmptyTuple(), | |
| EmptyNamed {}, | |
| } | |
| /// Intentionally does not implement [`FxfsSerialization`] to verify that `#[fxfs_serialize(skip)]` | |
| /// does not require skipped variant payloads to be serializable. | |
| #[derive(Debug, PartialEq, Eq)] | |
| struct NonSerializable(u32); | |
| #[derive(Debug, PartialEq, Eq, FxfsSerialization)] | |
| enum EnumWithSkip { | |
| First(u64), | |
| #[fxfs_serialize(skip)] | |
| SkippedMiddle(u64), | |
| #[fxfs_serialize(skip)] | |
| SkippedNamed { | |
| payload: NonSerializable, | |
| }, | |
| After { | |
| name: String, | |
| count: u32, | |
| }, | |
| #[fxfs_serialize(skip)] | |
| SkippedTrailing, | |
| } | |
| macro_rules! define_large_enum { | |
| ($($var:ident),* $(,)?) => { | |
| #[derive(Debug, PartialEq, Eq, FxfsSerialization)] | |
| enum LargeEnum { | |
| $($var(u16),)* | |
| } | |
| impl LargeEnum { | |
| fn all_variants() -> Vec<Self> { | |
| let constructors: &[fn(u16) -> Self] = &[$(Self::$var),*]; | |
| constructors.iter().enumerate().map(|(i, f)| f(i as u16)).collect() | |
| } | |
| } | |
| }; | |
| } | |
| define_large_enum!( | |
| V0, V1, V2, V3, V4, V5, V6, V7, V8, V9, V10, V11, V12, V13, V14, V15, V16, V17, V18, V19, V20, | |
| V21, V22, V23, V24, V25, V26, V27, V28, V29, V30, V31, V32, V33, V34, V35, V36, V37, V38, V39, | |
| V40, V41, V42, V43, V44, V45, V46, V47, V48, V49, V50, V51, V52, V53, V54, V55, V56, V57, V58, | |
| V59, V60, V61, V62, V63, V64, V65, V66, V67, V68, V69, V70, V71, V72, V73, V74, V75, V76, V77, | |
| V78, V79, V80, V81, V82, V83, V84, V85, V86, V87, V88, V89, V90, V91, V92, V93, V94, V95, V96, | |
| V97, V98, V99, V100, V101, V102, V103, V104, V105, V106, V107, V108, V109, V110, V111, V112, | |
| V113, V114, V115, V116, V117, V118, V119, V120, V121, V122, V123, V124, V125, V126, V127, V128, | |
| V129, V130, V131, V132, V133, V134, V135, V136, V137, V138, V139, V140, V141, V142, V143, V144, | |
| V145, V146, V147, V148, V149, V150, V151, V152, V153, V154, V155, V156, V157, V158, V159, V160, | |
| V161, V162, V163, V164, V165, V166, V167, V168, V169, V170, V171, V172, V173, V174, V175, V176, | |
| V177, V178, V179, V180, V181, V182, V183, V184, V185, V186, V187, V188, V189, V190, V191, V192, | |
| V193, V194, V195, V196, V197, V198, V199, V200, V201, V202, V203, V204, V205, V206, V207, V208, | |
| V209, V210, V211, V212, V213, V214, V215, V216, V217, V218, V219, V220, V221, V222, V223, V224, | |
| V225, V226, V227, V228, V229, V230, V231, V232, V233, V234, V235, V236, V237, V238, V239, V240, | |
| V241, V242, V243, V244, V245, V246, V247, V248, V249, V250 | |
| ); | |
| #[test] | |
| fn test_derived_structs() { | |
| assert!(assert_roundtrip(&UnitStruct, "struct {}").is_empty()); | |
| assert!(assert_roundtrip(&EmptyNamed {}, "struct {}").is_empty()); | |
| assert!(assert_roundtrip(&EmptyTuple(), "struct {}").is_empty()); | |
| let tuple_val = TupleStruct(0xdead_beef, "tuple".to_owned(), Some(u64::MAX), [1, 2, 3, 4]); | |
| assert_roundtrip(&tuple_val, "struct {u32,String,Option<u64>,[u8;4]}"); | |
| let named_val = NamedStruct { a: 123_456, b: "named".to_owned(), c: Some(252) }; | |
| assert_roundtrip(&named_val, "struct {a:u64,b:String,c:Option<u32>}"); | |
| let generic_val = GenericStruct { item: named_val, count: 7 }; | |
| assert_roundtrip(&generic_val, "struct {item:struct {a:u64,b:String,c:Option<u32>},count:u32}"); | |
| } | |
| #[derive(Debug, PartialEq, Eq, FxfsSerialization)] | |
| enum ExplicitDiscriminant { | |
| A = 10, | |
| B = 20, | |
| } | |
| #[derive(Debug, PartialEq, Eq, FxfsSerialization)] | |
| enum EnumWithSkippedGeneric<T, U> { | |
| Live(T), | |
| #[fxfs_serialize(skip)] | |
| SkippedTuple(U), | |
| #[fxfs_serialize(skip)] | |
| SkippedNested { | |
| items: Vec<U>, | |
| }, | |
| After(u32), | |
| } | |
| #[derive(Debug, PartialEq, Eq, FxfsSerialization)] | |
| enum EnumOnlySkippedGeneric<T> { | |
| Live(u64), | |
| #[fxfs_serialize(skip)] | |
| Legacy(T), | |
| } | |
| #[test] | |
| fn test_derived_enums() { | |
| let expected_fp = "enum {Unit,Tuple(u32,String),Named(x:u64,y:bool),EmptyTuple,EmptyNamed}"; | |
| let variants = [ | |
| (0u8, SampleEnum::Unit), | |
| (1u8, SampleEnum::Tuple(500, "world".to_owned())), | |
| (2u8, SampleEnum::Named { x: u64::MAX, y: true }), | |
| (3u8, SampleEnum::EmptyTuple()), | |
| (4u8, SampleEnum::EmptyNamed {}), | |
| ]; | |
| for (expected_tag, variant) in variants { | |
| let buf = assert_roundtrip(&variant, expected_fp); | |
| assert_eq!(buf[0], expected_tag); | |
| } | |
| assert_eq!( | |
| deserialize_from::<SampleEnum, _>(&mut [5u8].as_slice()), | |
| Err(DeserializeError::InvalidEnumTag) | |
| ); | |
| // Explicit Rust discriminants are ignored; tags follow 0-based declaration order. | |
| assert_eq!(assert_roundtrip(&ExplicitDiscriminant::A, "enum {A,B}"), vec![0]); | |
| assert_eq!(assert_roundtrip(&ExplicitDiscriminant::B, "enum {A,B}"), vec![1]); | |
| } | |
| #[test] | |
| fn test_derived_enum_with_skipped_variants() { | |
| // Middle skipped variants are rendered as `<skipped>`, trailing skipped variants are omitted. | |
| let expected_fp = "enum {First(u64),<skipped>,<skipped>,After(name:String,count:u32)}"; | |
| assert_eq!(assert_roundtrip(&EnumWithSkip::First(42), expected_fp), vec![0, 42]); | |
| // `After` retains discriminant index 3 despite `SkippedMiddle` (1) and `SkippedNamed` (2). | |
| let after = EnumWithSkip::After { name: "ok".to_owned(), count: 9 }; | |
| assert_eq!(assert_roundtrip(&after, expected_fp)[0], 3); | |
| // Skipped variants fail with SkippedVariant on both serialize and deserialize. | |
| let mut buf = Vec::new(); | |
| assert_eq!( | |
| EnumWithSkip::SkippedMiddle(1).serialize_into(&mut buf), | |
| Err(SerializeError::SkippedVariant) | |
| ); | |
| assert_eq!(EnumWithSkip::SkippedMiddle(1).serialized_size(), 0); | |
| assert_eq!( | |
| EnumWithSkip::SkippedNamed { payload: NonSerializable(7) }.serialize_into(&mut buf), | |
| Err(SerializeError::SkippedVariant) | |
| ); | |
| assert_eq!(EnumWithSkip::SkippedNamed { payload: NonSerializable(7) }.serialized_size(), 0); | |
| assert_eq!( | |
| EnumWithSkip::SkippedTrailing.serialize_into(&mut buf), | |
| Err(SerializeError::SkippedVariant) | |
| ); | |
| assert_eq!(EnumWithSkip::SkippedTrailing.serialized_size(), 0); | |
| assert_eq!( | |
| deserialize_from::<EnumWithSkip, _>(&mut [1u8, 0].as_slice()), | |
| Err(DeserializeError::SkippedVariant) | |
| ); | |
| assert_eq!( | |
| deserialize_from::<EnumWithSkip, _>(&mut [2u8].as_slice()), | |
| Err(DeserializeError::SkippedVariant) | |
| ); | |
| assert_eq!( | |
| deserialize_from::<EnumWithSkip, _>(&mut [4u8].as_slice()), | |
| Err(DeserializeError::SkippedVariant) | |
| ); | |
| assert_eq!( | |
| deserialize_from::<EnumWithSkip, _>(&mut [5u8].as_slice()), | |
| Err(DeserializeError::InvalidEnumTag) | |
| ); | |
| // Type parameters that only appear in `#[fxfs_serialize(skip)]` variants do not require | |
| // `FxfsSerialization`. | |
| let generic_live: EnumWithSkippedGeneric<u64, NonSerializable> = | |
| EnumWithSkippedGeneric::Live(77); | |
| assert_eq!( | |
| assert_roundtrip(&generic_live, "enum {Live(u64),<skipped>,<skipped>,After(u32)}"), | |
| vec![0, 77] | |
| ); | |
| let generic_after: EnumWithSkippedGeneric<u64, NonSerializable> = | |
| EnumWithSkippedGeneric::After(9); | |
| assert_eq!( | |
| assert_roundtrip(&generic_after, "enum {Live(u64),<skipped>,<skipped>,After(u32)}"), | |
| vec![3, 9] | |
| ); | |
| let mut skip_buf = Vec::new(); | |
| assert_eq!( | |
| EnumWithSkippedGeneric::<u64, NonSerializable>::SkippedTuple(NonSerializable(1)) | |
| .serialize_into(&mut skip_buf), | |
| Err(SerializeError::SkippedVariant) | |
| ); | |
| assert_eq!( | |
| EnumWithSkippedGeneric::<u64, NonSerializable>::SkippedNested { | |
| items: vec![NonSerializable(2)], | |
| } | |
| .serialize_into(&mut skip_buf), | |
| Err(SerializeError::SkippedVariant) | |
| ); | |
| let only_skipped: EnumOnlySkippedGeneric<NonSerializable> = EnumOnlySkippedGeneric::Live(5); | |
| assert_eq!(assert_roundtrip(&only_skipped, "enum {Live(u64)}"), vec![0, 5]); | |
| assert_eq!( | |
| EnumOnlySkippedGeneric::Legacy(NonSerializable(3)).serialize_into(&mut skip_buf), | |
| Err(SerializeError::SkippedVariant) | |
| ); | |
| } | |
| #[test] | |
| fn test_large_enum_varint_discriminant() { | |
| for (idx, variant) in LargeEnum::all_variants().into_iter().enumerate() { | |
| let mut buf = Vec::new(); | |
| variant.serialize_into(&mut buf).unwrap(); | |
| assert_eq!(variant.serialized_size(), buf.len() as u64); | |
| assert_eq!(buf[0], idx as u8); | |
| assert_eq!(deserialize_from::<LargeEnum, _>(&mut buf.as_slice()).unwrap(), variant); | |
| } | |
| for tag in 251u8..=255 { | |
| assert_eq!( | |
| deserialize_from::<LargeEnum, _>(&mut [tag, 0, 0, 0].as_slice()), | |
| Err(DeserializeError::InvalidEnumTag) | |
| ); | |
| } | |
| } | |
| #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, FxfsSerialization)] | |
| enum SingleVariantUnit { | |
| Only, | |
| } | |
| #[test] | |
| fn test_single_variant_unit_enum_in_collections() { | |
| // A single-variant unit enum is zero-sized in Rust (`size_of == 0`), yet consumes 1 wire byte | |
| // for its discriminant tag (`0u8`). Verify it compiles and roundtrips inside `Vec`, `Box`, | |
| // `Box<[T]>`, `BTreeMap`, `HashMap`, `BTreeSet`, and `HashSet`. | |
| assert_eq!(std::mem::size_of::<SingleVariantUnit>(), 0); | |
| assert_eq!(assert_roundtrip(&SingleVariantUnit::Only, "enum {Only}"), vec![0]); | |
| let vec_val = vec![SingleVariantUnit::Only, SingleVariantUnit::Only, SingleVariantUnit::Only]; | |
| assert_eq!(assert_roundtrip(&vec_val, "Vec<enum {Only}>"), vec![3, 0, 0, 0]); | |
| let boxed_slice: Box<[SingleVariantUnit]> = vec_val.into_boxed_slice(); | |
| assert_eq!(assert_roundtrip(&boxed_slice, "Box<[enum {Only}]>"), vec![3, 0, 0, 0]); | |
| assert_eq!(assert_roundtrip(&Box::new(SingleVariantUnit::Only), "Box<enum {Only}>"), vec![0]); | |
| let mut bmap = std::collections::BTreeMap::new(); | |
| bmap.insert(SingleVariantUnit::Only, SingleVariantUnit::Only); | |
| assert_eq!(assert_roundtrip(&bmap, "BTreeMap<enum {Only},enum {Only}>"), vec![1, 0, 0]); | |
| let mut hmap = std::collections::HashMap::new(); | |
| hmap.insert(SingleVariantUnit::Only, SingleVariantUnit::Only); | |
| assert_eq!(assert_roundtrip(&hmap, "HashMap<enum {Only},enum {Only}>"), vec![1, 0, 0]); | |
| let mut bset = std::collections::BTreeSet::new(); | |
| bset.insert(SingleVariantUnit::Only); | |
| assert_eq!(assert_roundtrip(&bset, "BTreeSet<enum {Only}>"), vec![1, 0]); | |
| let mut hset = std::collections::HashSet::new(); | |
| hset.insert(SingleVariantUnit::Only); | |
| assert_eq!(assert_roundtrip(&hset, "HashSet<enum {Only}>"), vec![1, 0]); | |
| } | |
| #[deny(unreachable_code, unused_variables)] | |
| mod uninhabited_and_skipped_tests { | |
| use fxfs_serialization::{ | |
| DeserializeError, FxfsSerialization, SerializeError, deserialize_from, | |
| }; | |
| #[derive(Debug, PartialEq, Eq, FxfsSerialization)] | |
| enum Empty {} | |
| #[derive(Debug, PartialEq, Eq, FxfsSerialization)] | |
| enum AllSkipped { | |
| #[fxfs_serialize(skip)] | |
| First, | |
| #[fxfs_serialize(skip)] | |
| Second(u64), | |
| } | |
| #[test] | |
| fn test_empty_and_all_skipped_enums() { | |
| assert_eq!(Empty::fingerprint(), "enum {}"); | |
| assert_eq!( | |
| deserialize_from::<Empty, _>([0u8].as_slice()), | |
| Err(DeserializeError::InvalidEnumTag) | |
| ); | |
| assert_eq!( | |
| deserialize_from::<Empty, _>([].as_slice()), | |
| Err(DeserializeError::UnexpectedEof) | |
| ); | |
| assert_eq!(AllSkipped::fingerprint(), "enum {}"); | |
| let mut buf = Vec::new(); | |
| assert_eq!(AllSkipped::First.serialize_into(&mut buf), Err(SerializeError::SkippedVariant)); | |
| assert_eq!(AllSkipped::First.serialized_size(), 0); | |
| assert_eq!( | |
| AllSkipped::Second(42).serialize_into(&mut buf), | |
| Err(SerializeError::SkippedVariant) | |
| ); | |
| assert_eq!(AllSkipped::Second(42).serialized_size(), 0); | |
| assert_eq!( | |
| deserialize_from::<AllSkipped, _>([0u8].as_slice()), | |
| Err(DeserializeError::SkippedVariant) | |
| ); | |
| assert_eq!( | |
| deserialize_from::<AllSkipped, _>([1u8].as_slice()), | |
| Err(DeserializeError::SkippedVariant) | |
| ); | |
| assert_eq!( | |
| deserialize_from::<AllSkipped, _>([2u8].as_slice()), | |
| Err(DeserializeError::InvalidEnumTag) | |
| ); | |
| } | |
| } | |
| #[derive(Debug, PartialEq, Eq, FxfsSerialization)] | |
| struct ConstGenericStruct<const N: usize> { | |
| data: [u8; N], | |
| len: u32, | |
| } | |
| #[derive(Debug, PartialEq, Eq, FxfsSerialization)] | |
| struct WhereClauseStruct<T> | |
| where | |
| T: Clone + Default, | |
| { | |
| val: T, | |
| } | |
| #[derive(Debug, PartialEq, Eq, FxfsSerialization)] | |
| enum WhereClauseEnum<T> | |
| where | |
| T: Clone + Default, | |
| { | |
| Val(T), | |
| Empty, | |
| } | |
| #[derive(Debug, PartialEq, Eq, FxfsSerialization)] | |
| enum ShadowedFieldNames { | |
| Named { writer: u64, reader: u32, __writer: u16, __reader: u8, __f0: bool }, | |
| } | |
| #[derive(Debug, PartialEq, Eq, FxfsSerialization)] | |
| struct GenericWRStruct<W, R>(W, R); | |
| #[derive(Debug, PartialEq, Eq, FxfsSerialization)] | |
| enum GenericWREnum<W, R> { | |
| Writer(W), | |
| Reader { reader: R, writer: W }, | |
| } | |
| #[test] | |
| fn test_const_generics_where_clauses_and_name_collisions() { | |
| let cg = ConstGenericStruct { data: [1, 2, 3, 4], len: 4 }; | |
| assert_roundtrip(&cg, "struct {data:[u8;4],len:u32}"); | |
| let wcs = WhereClauseStruct { val: 99u64 }; | |
| assert_roundtrip(&wcs, "struct {val:u64}"); | |
| let wce = WhereClauseEnum::Val("hi".to_owned()); | |
| assert_roundtrip(&wce, "enum {Val(String),Empty}"); | |
| let shadowed = | |
| ShadowedFieldNames::Named { writer: 1, reader: 2, __writer: 3, __reader: 4, __f0: true }; | |
| assert_roundtrip( | |
| &shadowed, | |
| "enum {Named(writer:u64,reader:u32,__writer:u16,__reader:u8,__f0:bool)}", | |
| ); | |
| let gwr_s = GenericWRStruct(42u32, "ok".to_owned()); | |
| assert_roundtrip(&gwr_s, "struct {u32,String}"); | |
| let gwr_e = GenericWREnum::<u64, String>::Reader { reader: "r".to_owned(), writer: 7 }; | |
| assert_roundtrip(&gwr_e, "enum {Writer(u64),Reader(reader:String,writer:u64)}"); | |
| } | |
| mod prelude_shadowing_hygiene { | |
| // Shadow prelude items (`Result` with 1 type parameter, `Ok`, `Err`, `String`, `ToOwned`, | |
| // `From`) to ensure the derive macro emits fully-qualified paths everywhere. | |
| #[expect(dead_code)] | |
| type Result<T> = ::core::result::Result<T, ()>; | |
| #[expect(dead_code)] | |
| enum FakeResult { | |
| Ok, | |
| Err, | |
| } | |
| #[expect(unused_imports)] | |
| use FakeResult::{Err, Ok}; | |
| #[expect(dead_code)] | |
| struct String; | |
| #[expect(dead_code)] | |
| trait ToOwned {} | |
| #[expect(dead_code)] | |
| trait From {} | |
| #[derive(Debug, PartialEq, Eq, ::fxfs_serialization::FxfsSerialization)] | |
| struct HygieneStruct { | |
| a: u64, | |
| b: ::std::string::String, | |
| } | |
| #[derive(Debug, PartialEq, Eq, ::fxfs_serialization::FxfsSerialization)] | |
| enum HygieneEnum { | |
| First(u32), | |
| #[fxfs_serialize(skip)] | |
| Skipped, | |
| Named { | |
| writer: u64, | |
| reader: bool, | |
| }, | |
| } | |
| #[test] | |
| fn test_derive_under_shadowed_prelude() { | |
| let s = HygieneStruct { a: 123, b: ::std::string::String::from("clean") }; | |
| let mut buf = ::std::vec::Vec::new(); | |
| ::fxfs_serialization::FxfsSerialization::serialize_into(&s, &mut buf).unwrap(); | |
| let decoded: HygieneStruct = | |
| ::fxfs_serialization::deserialize_from(buf.as_slice()).unwrap(); | |
| assert_eq!(decoded, s); | |
| assert_eq!( | |
| <HygieneStruct as ::fxfs_serialization::FxfsSerialization>::fingerprint(), | |
| "struct {a:u64,b:String}" | |
| ); | |
| let f = HygieneEnum::First(99); | |
| let mut fbuf = ::std::vec::Vec::new(); | |
| ::fxfs_serialization::FxfsSerialization::serialize_into(&f, &mut fbuf).unwrap(); | |
| assert_eq!( | |
| ::fxfs_serialization::deserialize_from::<HygieneEnum, _>(fbuf.as_slice()).unwrap(), | |
| f | |
| ); | |
| let mut skip_buf = ::std::vec::Vec::new(); | |
| assert_eq!( | |
| ::fxfs_serialization::FxfsSerialization::serialize_into( | |
| &HygieneEnum::Skipped, | |
| &mut skip_buf, | |
| ), | |
| ::core::result::Result::Err(::fxfs_serialization::SerializeError::SkippedVariant) | |
| ); | |
| assert_eq!( | |
| ::fxfs_serialization::deserialize_from::<HygieneEnum, _>([1u8].as_slice()), | |
| ::core::result::Result::Err(::fxfs_serialization::DeserializeError::SkippedVariant) | |
| ); | |
| let e = HygieneEnum::Named { writer: 7, reader: true }; | |
| let mut ebuf = ::std::vec::Vec::new(); | |
| ::fxfs_serialization::FxfsSerialization::serialize_into(&e, &mut ebuf).unwrap(); | |
| let decoded_e: HygieneEnum = | |
| ::fxfs_serialization::deserialize_from(ebuf.as_slice()).unwrap(); | |
| assert_eq!(decoded_e, e); | |
| assert_eq!( | |
| <HygieneEnum as ::fxfs_serialization::FxfsSerialization>::fingerprint(), | |
| "enum {First(u32),<skipped>,Named(writer:u64,reader:bool)}" | |
| ); | |
| } | |
| } | |
| mod custom_fixed_u32 { | |
| use super::*; | |
| pub fn serialize_into<W: Writer>(val: &u32, writer: &mut W) -> Result<(), SerializeError> { | |
| writer.write_bytes(&val.to_le_bytes()) | |
| } | |
| pub fn deserialize_from<R: Reader>(reader: &mut R) -> Result<u32, DeserializeError> { | |
| let buf = <[u8; 4] as FxfsSerialization>::deserialize_from(reader)?; | |
| Ok(u32::from_le_bytes(buf)) | |
| } | |
| pub fn serialized_size(_val: &u32) -> u64 { | |
| 4 | |
| } | |
| pub fn fingerprint<T: FxfsSerialization>() -> String { | |
| format!("FixedLE<{}>", T::fingerprint()) | |
| } | |
| } | |
| #[derive(Debug, PartialEq, Eq, FxfsSerialization)] | |
| struct CustomWithStruct { | |
| #[fxfs_serialize(with = "custom_fixed_u32")] | |
| a: u32, | |
| b: u32, | |
| } | |
| #[derive(Debug, PartialEq, Eq, FxfsSerialization)] | |
| struct CustomWithTuple(#[fxfs_serialize(with = "custom_fixed_u32")] u32); | |
| #[derive(Debug, PartialEq, Eq, FxfsSerialization)] | |
| enum CustomWithEnum { | |
| Tuple(#[fxfs_serialize(with = "custom_fixed_u32")] u32), | |
| Named { | |
| #[fxfs_serialize(with = "custom_fixed_u32")] | |
| x: u32, | |
| }, | |
| } | |
| #[test] | |
| fn test_custom_with_attribute() { | |
| let s = CustomWithStruct { a: 1, b: 1 }; | |
| let mut buf = Vec::new(); | |
| s.serialize_into(&mut buf).unwrap(); | |
| assert_eq!(buf, vec![1, 0, 0, 0, 1]); | |
| assert_eq!(s.serialized_size(), 5); | |
| assert_eq!(deserialize_from::<CustomWithStruct, _>(&mut buf.as_slice()).unwrap(), s); | |
| assert_eq!(CustomWithStruct::fingerprint(), "struct {a:FixedLE<u32>,b:u32}"); | |
| let t = CustomWithTuple(7); | |
| let mut buf = Vec::new(); | |
| t.serialize_into(&mut buf).unwrap(); | |
| assert_eq!(buf, vec![7, 0, 0, 0]); | |
| assert_eq!(t.serialized_size(), 4); | |
| assert_eq!(deserialize_from::<CustomWithTuple, _>(&mut buf.as_slice()).unwrap(), t); | |
| assert_eq!(CustomWithTuple::fingerprint(), "struct {FixedLE<u32>}"); | |
| for e in [CustomWithEnum::Tuple(42), CustomWithEnum::Named { x: 99 }] { | |
| let mut buf = Vec::new(); | |
| e.serialize_into(&mut buf).unwrap(); | |
| assert_eq!(buf.len() as u64, e.serialized_size()); | |
| assert_eq!(deserialize_from::<CustomWithEnum, _>(&mut buf.as_slice()).unwrap(), e); | |
| } | |
| assert_eq!(CustomWithEnum::fingerprint(), "enum {Tuple(FixedLE<u32>),Named(x:FixedLE<u32>)}"); | |
| } | |
| #[derive(Debug, PartialEq, Eq, FxfsSerialization)] | |
| struct FixedFieldStruct { | |
| #[fxfs_serialize(with = "fixed")] | |
| id: u64, | |
| #[fxfs_serialize(with = "fixed")] | |
| short: u16, | |
| #[fxfs_serialize(with = "fixed")] | |
| arr: [u32; 2], | |
| } | |
| #[derive(Debug, PartialEq, Eq, FxfsSerialization)] | |
| enum FixedEnum { | |
| One(#[fxfs_serialize(with = "fixed")] u64), | |
| Array(#[fxfs_serialize(with = "fixed")] [u16; 2]), | |
| } | |
| #[derive(Debug, PartialEq, Eq, FxfsSerialization)] | |
| struct FixedSliceStruct { | |
| #[fxfs_serialize(with = "fixed_slice")] | |
| vec_u16: Vec<u16>, | |
| #[fxfs_serialize(with = "fixed_slice")] | |
| vec_u32: Vec<u32>, | |
| #[fxfs_serialize(with = "fixed_slice")] | |
| vec_u64: Vec<u64>, | |
| #[fxfs_serialize(with = "fixed_slice")] | |
| vec_u128: Vec<u128>, | |
| #[fxfs_serialize(with = "fixed_slice")] | |
| vec_arr: Vec<[u16; 2]>, | |
| #[fxfs_serialize(with = "fixed_slice")] | |
| box_u16: Box<[u16]>, | |
| #[fxfs_serialize(with = "fixed_slice")] | |
| box_u32: Box<[u32]>, | |
| #[fxfs_serialize(with = "fixed_slice")] | |
| box_u64: Box<[u64]>, | |
| #[fxfs_serialize(with = "fixed_slice")] | |
| box_u128: Box<[u128]>, | |
| #[fxfs_serialize(with = "fixed_slice")] | |
| box_arr: Box<[[u32; 2]]>, | |
| } | |
| #[test] | |
| fn test_fixed_and_fixed_slice_attributes() { | |
| let val = FixedFieldStruct { | |
| id: 0x1234_5678_9abc_def0, | |
| short: 0x55aa, | |
| arr: [0x1122_3344, 0x5566_7788], | |
| }; | |
| let mut buf = Vec::new(); | |
| val.serialize_into(&mut buf).unwrap(); | |
| assert_eq!(buf.len(), 18); | |
| assert_eq!(buf.len() as u64, val.serialized_size()); | |
| assert_eq!(&buf[0..8], &0x1234_5678_9abc_def0u64.to_le_bytes()); | |
| assert_eq!(&buf[8..10], &0x55aau16.to_le_bytes()); | |
| assert_eq!(&buf[10..14], &0x1122_3344u32.to_le_bytes()); | |
| assert_eq!(&buf[14..18], &0x5566_7788u32.to_le_bytes()); | |
| let decoded: FixedFieldStruct = deserialize_from(&mut buf.as_slice()).unwrap(); | |
| assert_eq!(decoded, val); | |
| assert_eq!( | |
| FixedFieldStruct::fingerprint(), | |
| "struct {id:Fixed<u64>,short:Fixed<u16>,arr:Fixed<[u32;2]>}" | |
| ); | |
| for (e, expected_len) in | |
| [(FixedEnum::One(0x99), 1 + 8), (FixedEnum::Array([0x1234, 0x5678]), 1 + 4)] | |
| { | |
| let mut buf2 = Vec::new(); | |
| e.serialize_into(&mut buf2).unwrap(); | |
| assert_eq!(buf2.len(), expected_len); | |
| assert_eq!(buf2.len() as u64, e.serialized_size()); | |
| let decoded_e: FixedEnum = deserialize_from(&mut buf2.as_slice()).unwrap(); | |
| assert_eq!(decoded_e, e); | |
| } | |
| assert_eq!(FixedEnum::fingerprint(), "enum {One(Fixed<u64>),Array(Fixed<[u16;2]>)}"); | |
| let slices = FixedSliceStruct { | |
| vec_u16: vec![0x1234, 0x5678], | |
| vec_u32: vec![0x1234_5678, 0x9abc_def0], | |
| vec_u64: vec![0x0102_0304_0506_0708, 0xf1f2_f3f4_f5f6_f7f8], | |
| vec_u128: vec![0x0102_0304_0506_0708_090a_0b0c_0d0e_0f10], | |
| vec_arr: vec![[0x1122, 0x3344], [0x5566, 0x7788]], | |
| box_u16: vec![0xaaaa, 0xbbbb, 0xcccc].into_boxed_slice(), | |
| box_u32: vec![0xdead_beef].into_boxed_slice(), | |
| box_u64: vec![0x1122_3344_5566_7788].into_boxed_slice(), | |
| box_u128: vec![0xff00_ff00_ff00_ff00_ff00_ff00_ff00_ff00].into_boxed_slice(), | |
| box_arr: vec![[0x0102_0304, 0x0506_0708]].into_boxed_slice(), | |
| }; | |
| let mut buf3 = Vec::new(); | |
| slices.serialize_into(&mut buf3).unwrap(); | |
| // Verify first field (`vec_u16` of len 2) | |
| assert_eq!(buf3[0], 2); | |
| assert_eq!(&buf3[1..3], &0x1234u16.to_le_bytes()); | |
| assert_eq!(&buf3[3..5], &0x5678u16.to_le_bytes()); | |
| assert_eq!(buf3.len() as u64, slices.serialized_size()); | |
| let decoded_slices: FixedSliceStruct = deserialize_from(&mut buf3.as_slice()).unwrap(); | |
| assert_eq!(decoded_slices, slices); | |
| assert_eq!( | |
| FixedSliceStruct::fingerprint(), | |
| "struct {vec_u16:Fixed<Vec<u16>>,vec_u32:Fixed<Vec<u32>>,vec_u64:Fixed<Vec<u64>>,vec_u128:Fixed<Vec<u128>>,vec_arr:Fixed<Vec<[u16;2]>>,box_u16:Fixed<Box<[u16]>>,box_u32:Fixed<Box<[u32]>>,box_u64:Fixed<Box<[u64]>>,box_u128:Fixed<Box<[u128]>>,box_arr:Fixed<Box<[[u32;2]]>>}" | |
| ); | |
| } | |
| #[test] | |
| fn test_limited_writer_fixed_struct() { | |
| let val = FixedFieldStruct { | |
| id: 0x1234_5678_9abc_def0, | |
| short: 0x55aa, | |
| arr: [0x1122_3344, 0x5566_7788], | |
| }; | |
| // Struct where serialized size <= limit | |
| let mut buf = Vec::new(); | |
| { | |
| let mut limited = buf.with_limit(18); | |
| val.serialize_into(&mut limited).unwrap(); | |
| } | |
| assert_eq!(buf.len(), 18); | |
| // Struct where serialized size > limit | |
| let mut buf = Vec::new(); | |
| assert_eq!(val.serialize_into(&mut buf.with_limit(17)), Err(SerializeError::LimitExceeded)); | |
| } | |
| // Foreign-like trait and type intentionally NOT implementing `FxfsSerialization`, used to verify | |
| // that generic fields using `with = "..."` do not receive spurious `FxfsSerialization` bounds. | |
| trait ForeignCodec: Sized { | |
| fn to_pair(&self) -> (u32, u32); | |
| fn from_pair(a: u32, b: u32) -> Self; | |
| } | |
| #[derive(Debug, PartialEq, Eq)] | |
| struct NonSerializablePair(u32, u32); | |
| impl ForeignCodec for NonSerializablePair { | |
| fn to_pair(&self) -> (u32, u32) { | |
| (self.0, self.1) | |
| } | |
| fn from_pair(a: u32, b: u32) -> Self { | |
| Self(a, b) | |
| } | |
| } | |
| mod foreign_codec_adapter { | |
| use super::ForeignCodec; | |
| use fxfs_serialization::{DeserializeError, FxfsSerialization, Reader, SerializeError, Writer}; | |
| pub fn serialize_into<T: ForeignCodec, W: Writer>( | |
| val: &T, | |
| writer: &mut W, | |
| ) -> Result<(), SerializeError> { | |
| let (a, b) = val.to_pair(); | |
| a.serialize_into(writer)?; | |
| b.serialize_into(writer) | |
| } | |
| pub fn deserialize_from<T: ForeignCodec, R: Reader>( | |
| reader: &mut R, | |
| ) -> Result<T, DeserializeError> { | |
| Ok(T::from_pair(u32::deserialize_from(reader)?, u32::deserialize_from(reader)?)) | |
| } | |
| pub fn serialized_size<T: ForeignCodec>(val: &T) -> u64 { | |
| let (a, b) = val.to_pair(); | |
| a.serialized_size() + b.serialized_size() | |
| } | |
| pub fn fingerprint<T>() -> String { | |
| "ForeignCodec".to_owned() | |
| } | |
| } | |
| #[derive(Debug, PartialEq, Eq, FxfsSerialization)] | |
| struct GenericFixed<T> { | |
| #[fxfs_serialize(with = "fixed")] | |
| val: T, | |
| } | |
| #[derive(Debug, PartialEq, Eq, FxfsSerialization)] | |
| struct GenericFixedSlice<T> { | |
| #[fxfs_serialize(with = "fixed_slice")] | |
| items: Vec<T>, | |
| } | |
| #[derive(Debug, PartialEq, Eq, FxfsSerialization)] | |
| struct GenericFixedSliceContainer<C> { | |
| #[fxfs_serialize(with = "fixed_slice")] | |
| items: C, | |
| } | |
| #[derive(Debug, PartialEq, Eq, FxfsSerialization)] | |
| struct GenericCustom<T: ForeignCodec> { | |
| #[fxfs_serialize(with = "foreign_codec_adapter")] | |
| val: T, | |
| } | |
| #[derive(Debug, PartialEq, Eq, FxfsSerialization)] | |
| enum GenericWithEnum<T, U, V: ForeignCodec> { | |
| Fixed(#[fxfs_serialize(with = "fixed")] T), | |
| Slice(#[fxfs_serialize(with = "fixed_slice")] Vec<U>), | |
| Custom(#[fxfs_serialize(with = "foreign_codec_adapter")] V), | |
| } | |
| #[test] | |
| fn test_generic_with_attribute_bounds() { | |
| // `[u32; 2]` implements `Fixed` but intentionally does NOT implement `FxfsSerialization`. | |
| let fixed_arr = GenericFixed { val: [0x1122_3344u32, 0x5566_7788] }; | |
| let mut buf = Vec::new(); | |
| fixed_arr.serialize_into(&mut buf).unwrap(); | |
| assert_eq!(buf.len() as u64, fixed_arr.serialized_size()); | |
| assert_eq!(deserialize_from::<GenericFixed<[u32; 2]>, _>(buf.as_slice()).unwrap(), fixed_arr); | |
| assert_eq!(GenericFixed::<[u32; 2]>::fingerprint(), "struct {val:Fixed<[u32;2]>}"); | |
| let fixed_slice = GenericFixedSlice { items: vec![[0x1234u16, 0x5678], [0x9abc, 0xdef0]] }; | |
| let mut buf = Vec::new(); | |
| fixed_slice.serialize_into(&mut buf).unwrap(); | |
| assert_eq!(buf.len() as u64, fixed_slice.serialized_size()); | |
| assert_eq!( | |
| deserialize_from::<GenericFixedSlice<[u16; 2]>, _>(buf.as_slice()).unwrap(), | |
| fixed_slice, | |
| ); | |
| assert_eq!(GenericFixedSlice::<[u16; 2]>::fingerprint(), "struct {items:Fixed<Vec<[u16;2]>>}"); | |
| let boxed_container = GenericFixedSliceContainer { | |
| items: vec![[0x1122_3344u32, 0x5566_7788]].into_boxed_slice(), | |
| }; | |
| let mut buf = Vec::new(); | |
| boxed_container.serialize_into(&mut buf).unwrap(); | |
| assert_eq!( | |
| deserialize_from::<GenericFixedSliceContainer<Box<[[u32; 2]]>>, _>(buf.as_slice()).unwrap(), | |
| boxed_container, | |
| ); | |
| let custom = GenericCustom { val: NonSerializablePair(10, 20) }; | |
| let mut buf = Vec::new(); | |
| custom.serialize_into(&mut buf).unwrap(); | |
| assert_eq!(buf.len() as u64, custom.serialized_size()); | |
| assert_eq!( | |
| deserialize_from::<GenericCustom<NonSerializablePair>, _>(buf.as_slice()).unwrap(), | |
| custom, | |
| ); | |
| assert_eq!(GenericCustom::<NonSerializablePair>::fingerprint(), "struct {val:ForeignCodec}"); | |
| for val in [ | |
| GenericWithEnum::<[u32; 2], [u16; 2], NonSerializablePair>::Fixed([1, 2]), | |
| GenericWithEnum::Slice(vec![[3, 4], [5, 6]]), | |
| GenericWithEnum::Custom(NonSerializablePair(7, 8)), | |
| ] { | |
| let mut buf = Vec::new(); | |
| val.serialize_into(&mut buf).unwrap(); | |
| assert_eq!(buf.len() as u64, val.serialized_size()); | |
| assert_eq!( | |
| deserialize_from::<GenericWithEnum<[u32; 2], [u16; 2], NonSerializablePair>, _>( | |
| buf.as_slice(), | |
| ) | |
| .unwrap(), | |
| val, | |
| ); | |
| } | |
| assert_eq!( | |
| GenericWithEnum::<[u32; 2], [u16; 2], NonSerializablePair>::fingerprint(), | |
| "enum {Fixed(Fixed<[u32;2]>),Slice(Fixed<Vec<[u16;2]>>),Custom(ForeignCodec)}", | |
| ); | |
| } |