musli_wire/
test.rs

1//! Helpers for writing tests.
2
3use core::fmt::Debug;
4
5use musli::mode::Binary;
6use musli::{Decode, Encode};
7
8use crate::tag::Tag;
9
10/// A typed field, which is prefixed with a type tag.
11///
12/// This is used in combination with the storage deserializer to "inspect" type
13/// tags.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)]
15#[musli(packed)]
16pub struct Typed<const N: usize> {
17    tag: Tag,
18    #[musli(bytes)]
19    value: [u8; N],
20}
21
22impl<const N: usize> Typed<N> {
23    /// Construct a new typed field.
24    pub const fn new(tag: Tag, value: [u8; N]) -> Self {
25        Self { tag, value }
26    }
27}
28
29musli_utils::test_fns!("wire", musli::mode::Binary);
30
31/// Encode a type as one and decode as another.
32#[inline(never)]
33#[track_caller]
34pub fn transcode<T, O>(value: T) -> O
35where
36    T: Debug + PartialEq + Encode<Binary>,
37    O: for<'de> Decode<'de, Binary>,
38{
39    let out = crate::to_vec(&value).expect("failed to encode");
40    let mut buf = out.as_slice();
41    let value: O = crate::decode(&mut buf).expect("failed to decode");
42    assert!(buf.is_empty());
43    value
44}