pbf_core/
bit_cast.rs

1/// All encoding and decoding is done via u64.
2/// So all types must implement this trait to be able to be encoded and decoded.
3pub trait BitCast: Sized {
4    /// Convert the value to a u64.
5    fn to_u64(&self) -> u64;
6    /// Convert a u64 to the value.
7    fn from_u64(value: u64) -> Self;
8}
9macro_rules! impl_bitcast {
10    ($($t:ty),*) => {
11        $(
12            impl BitCast for $t {
13                fn to_u64(&self) -> u64 {
14                    *self as u64
15                }
16                fn from_u64(value: u64) -> Self {
17                    value as $t
18                }
19            }
20        )*
21    };
22}
23impl_bitcast!(u8, i8, u16, i16, u32, i32, u64, i64, usize, isize);
24impl BitCast for f32 {
25    fn to_u64(&self) -> u64 {
26        (*self).to_bits() as u64
27    }
28    fn from_u64(value: u64) -> Self {
29        f32::from_bits(value as u32)
30    }
31}
32impl BitCast for f64 {
33    fn to_u64(&self) -> u64 {
34        (*self).to_bits()
35    }
36    fn from_u64(value: u64) -> Self {
37        f64::from_bits(value)
38    }
39}
40impl BitCast for bool {
41    fn to_u64(&self) -> u64 {
42        if *self { 1 } else { 0 }
43    }
44    fn from_u64(value: u64) -> Self {
45        value != 0
46    }
47}