isobmff/
sized.rs

1use scuffle_bytes_util::zero_copy::{I24Be, I48Be, U24Be, U48Be};
2use scuffle_bytes_util::{BytesCow, StringCow};
3
4/// This trait should be implemented by all types that have a known size when serialized.
5pub trait IsoSized {
6    /// Returns the size of the type when serialized.
7    fn size(&self) -> usize;
8}
9
10macro_rules! impl_sized {
11    ($($t:ty),+) => {
12        $(
13            impl IsoSized for $t {
14                fn size(&self) -> usize {
15                    std::mem::size_of::<$t>()
16                }
17            }
18        )+
19    };
20}
21
22impl_sized!(f32, f64, i8, i16, i32, i64, i128, u8, u16, u32, u64, u128, char, ());
23
24impl<T, const LEN: usize> IsoSized for [T; LEN]
25where
26    T: IsoSized,
27{
28    fn size(&self) -> usize {
29        self.iter().map(|item| item.size()).sum()
30    }
31}
32
33impl<T> IsoSized for Vec<T>
34where
35    T: IsoSized,
36{
37    fn size(&self) -> usize {
38        self.iter().map(|item| item.size()).sum()
39    }
40}
41
42impl<T> IsoSized for Option<T>
43where
44    T: IsoSized,
45{
46    fn size(&self) -> usize {
47        match self {
48            Some(item) => item.size(),
49            None => 0,
50        }
51    }
52}
53
54impl IsoSized for BytesCow<'_> {
55    fn size(&self) -> usize {
56        self.len()
57    }
58}
59
60impl IsoSized for StringCow<'_> {
61    fn size(&self) -> usize {
62        self.len()
63    }
64}
65
66impl IsoSized for I24Be {
67    fn size(&self) -> usize {
68        3
69    }
70}
71
72impl IsoSized for I48Be {
73    fn size(&self) -> usize {
74        6
75    }
76}
77
78impl IsoSized for U24Be {
79    fn size(&self) -> usize {
80        3
81    }
82}
83
84impl IsoSized for U48Be {
85    fn size(&self) -> usize {
86        6
87    }
88}