1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
use super::Loadable;

impl Loadable for String {
    fn load(buffer: &[u8]) -> (Option<Self>, usize) {
        if buffer.len() < 4 {
            return (None, 0);
        }
        let mut u32_bytes: [u8; 4] = [u8::MAX; 4];
        u32_bytes.copy_from_slice(&buffer[..4]);
        let str_size = u32::from_le_bytes(u32_bytes) as usize;
        (Some(Self::from_utf8_lossy(&buffer[4..str_size + 4]).into_owned()), str_size + 4)
    }
}

impl<T: Loadable> Loadable for Vec<T> {
    fn load(buffer: &[u8]) -> (Option<Self>, usize) {
        if buffer.len() < 4 {
            return (None, 0);
        }
        let mut u32_bytes: [u8; 4] = [u8::MAX; 4];
        u32_bytes.copy_from_slice(&buffer[..4]);
        let count = u32::from_le_bytes(u32_bytes) as usize;
        let mut cursor = 4;
        let mut items = Vec::with_capacity(count);
        for _ in 0..count {
            let (obj, len) = T::load(&buffer[cursor..]);
            cursor += len;
            if let Some(obj) = obj {
                items.push(obj);
            } else {
                return (None, cursor);
            }
        }
        (Some(items), cursor)
    }
}

impl Loadable for bool {
    fn load(buffer: &[u8]) -> (Option<Self>, usize) {
        if buffer.len() < 1 {
            return (None, 0);
        }
        (Some(buffer[0] != 0), 1)
    }
}

impl Loadable for u8 {
    fn load(buffer: &[u8]) -> (Option<Self>, usize) {
        if buffer.len() < 1 {
            return (None, 0);
        }
        (Some(buffer[0]), 1)
    }
}

impl Loadable for i8 {
    fn load(buffer: &[u8]) -> (Option<Self>, usize) {
        if buffer.len() < 1 {
            return (None, 0);
        }
        (Some(i8::from_le_bytes([buffer[0]])), 1)
    }
}

macro_rules! int_impl {
    ($type:ty, $size:literal) => {
        impl Loadable for $type {
            fn load(buffer: &[u8]) -> (Option<Self>, usize) {
                if buffer.len() < $size {
                    return (None, 0);
                }
                let mut bytes: [u8; $size] = [u8::MAX; $size];
                bytes.copy_from_slice(&buffer[..$size]);
                let i = <$type>::from_le_bytes(bytes);
                (Some(i), $size)
            }
        }
    }
}

int_impl!{u16, 2}
int_impl!{u32, 4}
int_impl!{u64, 8}
int_impl!{u128, 16}

int_impl!{i16, 2}
int_impl!{i32, 4}
int_impl!{i64, 8}
int_impl!{i128, 16}

int_impl!{f32, 4}
int_impl!{f64, 8}

#[cfg(test)]
mod tests {
    use super::*;

    macro_rules! test_impl {
        ($fn_name:ident, $data:expr, $type:ty, $expected_len:literal, $expected_load:expr) => {
            #[test]
            fn $fn_name() {
                let buffer = $data;
                let (obj, read_len) = <$type>::load(&buffer);
                assert!(obj.is_some(), "Load not ok");
                assert_eq!(read_len, $expected_len, "Wrong amount read");
                assert_eq!(obj.unwrap(), $expected_load, "Loaded value not as expected");
            }
        }
    }

    test_impl!{string_load_test, [4u8, 0, 0, 0, 116, 101, 115, 116, 0, 128], String, 8, "test"}
    test_impl!{
        vec_load_test,
        [3u8, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 49, 5, 0, 0, 0, 116, 101, 115, 116, 50],
        Vec<String>,
        26,
        vec![
            "".to_string(),
            "test1".to_string(),
            "test2".to_string()
        ]
    }

    test_impl!{bool_true_load_test, [1], bool, 1, true}
    test_impl!{bool_false_load_test, [0], bool, 1, false}

    // testing macro-generated code isn't particularly useful, but do it anyway

    test_impl!{u8_load_test, [42], u8, 1, 42u8}
    test_impl!{u16_load_test, [42, 0], u16, 2, 42u16}
    test_impl!{u32_load_test, [42, 0, 0, 0], u32, 4, 42u32}
    test_impl!{u64_load_test, [42, 0, 0, 0, 0, 0, 0, 0], u64, 8, 42u64}
    test_impl!{u128_load_test, [42, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], u128, 16, 42u128}

    test_impl!{i8_load_test, [42], i8, 1, 42i8}
    test_impl!{i16_load_test, [42, 0], i16, 2, 42i16}
    test_impl!{i32_load_test, [42, 0, 0, 0], i32, 4, 42i32}
    test_impl!{i64_load_test, [42, 0, 0, 0, 0, 0, 0, 0], i64, 8, 42i64}
    test_impl!{i128_load_test, [42, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], i128, 16, 42i128}

    test_impl!{f32_load_test, [0, 0, 40, 66], f32, 4, 42f32}
    test_impl!{f64_load_test, [0, 0, 0, 0, 0, 0, 69, 64], f64, 8, 42f64}
}