byteserde/
size.rs

1/// Trait type used in advanced cases when serializing and deserializing an optional block of a byte
2/// stream whose type is represented by a `struct` whose size is deterministict at compile time.
3///
4/// Typically will be implemented using a `byteserde_derive::ByteSerializedSizeOf` proc macro.
5///
6/// # Guarantees
7/// * Must return the number of bytes the implementing structure will occupy in a byte stream
8///  when serialized. This is instance `independent` trait and may not be possible to implement for
9/// `struct`s whose elements might be allocated on the heap at run time, example String, Vec, etc.
10pub trait ByteSerializedSizeOf {
11    fn byte_size() -> usize;
12}
13macro_rules! size_of {
14    ($t:ty) => {
15        impl ByteSerializedSizeOf for $t {
16            fn byte_size() -> usize {
17                std::mem::size_of::<$t>()
18            }
19        }
20    };
21}
22size_of!(u8);
23size_of!(i8);
24size_of!(u16);
25size_of!(i16);
26size_of!(u32);
27size_of!(i32);
28size_of!(u64);
29size_of!(i64);
30size_of!(u128);
31size_of!(i128);
32size_of!(usize);
33size_of!(isize);
34
35/// Returns strictly the size of the type `T` in bytes and ignores the None variant
36impl<T: ByteSerializedSizeOf> ByteSerializedSizeOf for Option<T> {
37    fn byte_size() -> usize {
38        T::byte_size()
39    }
40}
41/// Trait type used in advanced cases when serializing and deserializing an optional block of a byte
42/// stream whose type is represented by a `struct` whose size is `NOT` deterministict at compile time.
43///
44/// Typically will be implemented using a `byteserde_derive::ByteSerializedLenOf` proc macro.
45///
46/// # Guarantees
47/// * Must return the number of bytes a specific `instance` of implementing structure will occupy in a byte stream
48/// when serialized. This is instance `dependent` trait and might return a differet length for each instance,
49/// example String, Vec, etc.
50pub trait ByteSerializedLenOf {
51    fn byte_len(&self) -> usize;
52}
53
54impl ByteSerializedLenOf for String {
55    fn byte_len(&self) -> usize {
56        self.len()
57    }
58}
59impl ByteSerializedLenOf for char {
60    fn byte_len(&self) -> usize {
61        self.len_utf8()
62    }
63}
64
65impl<T> ByteSerializedLenOf for Option<T>
66where T: ByteSerializedLenOf
67{
68    fn byte_len(&self) -> usize {
69        match self {
70            Some(t) => t.byte_len(),
71            None => 0,
72        }
73    }
74}