byteable 0.36.0

A Rust crate for convenient serialization and deserialization of byte-oriented data.
Documentation
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
//! Integration tests for the `eio_async` (embedded-io-async) support module.
#![cfg(all(feature = "embedded-io-async", feature = "derive"))]

mod fixed {
    use byteable::eio_async::{EioAsyncReadFixed, EioAsyncWriteFixed};
    use byteable::{Byteable, LittleEndian};

    #[derive(Byteable, Debug, Clone, Copy, PartialEq)]
    struct Header {
        #[byteable(big_endian)]
        magic: u32,
        #[byteable(little_endian)]
        version: u16,
    }

    #[tokio::test]
    async fn primitive_roundtrip_over_slice() {
        let mut buf = [0u8; 4];
        {
            let mut w: &mut [u8] = &mut buf;
            w.write_fixed(&42u32).await.unwrap();
        }
        let mut r: &[u8] = &buf;
        let val: u32 = r.read_fixed().await.unwrap();
        assert_eq!(val, 42u32);
    }

    #[tokio::test]
    async fn endian_wrapper_roundtrip_over_slice() {
        let original: LittleEndian<u32> = LittleEndian::new(0xDEADBEEF);
        let mut buf = [0u8; 4];
        {
            let mut w: &mut [u8] = &mut buf;
            w.write_fixed(&original).await.unwrap();
        }
        let mut r: &[u8] = &buf;
        let restored: LittleEndian<u32> = r.read_fixed().await.unwrap();
        assert_eq!(restored.get(), original.get());
    }

    #[tokio::test]
    async fn derived_struct_roundtrip_over_slice() {
        let header = Header {
            magic: 0x1234_5678,
            version: 7,
        };
        let mut buf = [0u8; 6];
        {
            let mut w: &mut [u8] = &mut buf;
            w.write_fixed(&header).await.unwrap();
        }
        let mut r: &[u8] = &buf;
        let restored: Header = r.read_fixed().await.unwrap();
        assert_eq!(restored, header);
    }

    #[tokio::test]
    async fn read_exact_error_on_truncated_slice() {
        use byteable::eio::EioReadableError;
        let buf = [0u8; 2]; // too short for a u32
        let mut r: &[u8] = &buf;
        let err = r.read_fixed::<u32>().await.unwrap_err();
        assert!(matches!(err, EioReadableError::UnexpectedEof));
    }

    // `Reverse<T>` only gets `EioAsyncFixedReadable`/`EioAsyncFixedWritable` (via the blanket
    // `RawRepr`/`TryFromRawRepr` chain), not the `ToByteArray` fixed byte-array API directly.
    #[tokio::test]
    async fn reverse_roundtrip_over_slice() {
        use core::cmp::Reverse;

        let original = Reverse(0xDEADBEEFu32);
        let mut buf = [0u8; 4];
        {
            let mut w: &mut [u8] = &mut buf;
            w.write_fixed(&original).await.unwrap();
        }
        let mut r: &[u8] = &buf;
        let restored: Reverse<u32> = r.read_fixed().await.unwrap();
        assert_eq!(restored, original);
    }
}

mod dynamic_over_fixed {
    use byteable::Byteable;
    use byteable::eio_async::{EioAsyncReadValue, EioAsyncWriteValue};

    #[derive(Byteable, Debug, Clone, Copy, PartialEq)]
    struct Point {
        x: i32,
        y: i32,
    }

    #[tokio::test]
    async fn read_value_write_value_roundtrip_fixed_type() {
        let p = Point { x: -5, y: 100 };
        let mut buf = [0u8; 8];
        {
            let mut w: &mut [u8] = &mut buf;
            w.write_value(&p).await.unwrap();
        }
        let mut r: &[u8] = &buf;
        let restored: Point = r.read_value().await.unwrap();
        assert_eq!(restored, p);
    }
}

mod option_result {
    use byteable::eio_async::{EioAsyncReadValue, EioAsyncWriteValue};
    use core::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
    use core::ops::Bound;

    #[tokio::test]
    async fn option_some_roundtrip() {
        let val: Option<u32> = Some(7);
        let mut buf = [0u8; 5];
        {
            let mut w: &mut [u8] = &mut buf;
            w.write_value(&val).await.unwrap();
        }
        let mut r: &[u8] = &buf;
        let restored: Option<u32> = r.read_value().await.unwrap();
        assert_eq!(restored, val);
    }

    #[tokio::test]
    async fn option_none_roundtrip() {
        let val: Option<u32> = None;
        let mut buf = [0u8; 5];
        {
            let mut w: &mut [u8] = &mut buf;
            w.write_value(&val).await.unwrap();
        }
        let mut r: &[u8] = &buf;
        let restored: Option<u32> = r.read_value().await.unwrap();
        assert_eq!(restored, val);
    }

    #[tokio::test]
    async fn result_roundtrip() {
        let val: Result<u8, u8> = Ok(9);
        let mut buf = [0u8; 2];
        {
            let mut w: &mut [u8] = &mut buf;
            w.write_value(&val).await.unwrap();
        }
        let mut r: &[u8] = &buf;
        let restored: Result<u8, u8> = r.read_value().await.unwrap();
        assert_eq!(restored, val);
    }

    #[tokio::test]
    async fn ip_addr_roundtrip() {
        for val in [
            IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)),
            IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)),
        ] {
            let mut buf = [0u8; 17];
            {
                let mut w: &mut [u8] = &mut buf;
                w.write_value(&val).await.unwrap();
            }
            let mut r: &[u8] = &buf;
            let restored: IpAddr = r.read_value().await.unwrap();
            assert_eq!(restored, val);
        }
    }

    #[tokio::test]
    async fn socket_addr_roundtrip() {
        for val in [
            SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(192, 168, 0, 1), 8080)),
            SocketAddr::V6(SocketAddrV6::new(
                Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1),
                443,
                0,
                0,
            )),
        ] {
            let mut buf = [0u8; 27];
            {
                let mut w: &mut [u8] = &mut buf;
                w.write_value(&val).await.unwrap();
            }
            let mut r: &[u8] = &buf;
            let restored: SocketAddr = r.read_value().await.unwrap();
            assert_eq!(restored, val);
        }
    }

    #[tokio::test]
    async fn bound_roundtrip() {
        for val in [
            Bound::Included(7u32),
            Bound::Excluded(9u32),
            Bound::Unbounded,
        ] {
            let mut buf = [0u8; 5];
            {
                let mut w: &mut [u8] = &mut buf;
                w.write_value(&val).await.unwrap();
            }
            let mut r: &[u8] = &buf;
            let restored: Bound<u32> = r.read_value().await.unwrap();
            assert_eq!(restored, val);
        }
    }

    #[tokio::test]
    async fn tuple_roundtrip() {
        let val: (u8, u32, bool) = (7, 0xDEAD_BEEF, true);
        let mut buf = [0u8; 6];
        {
            let mut w: &mut [u8] = &mut buf;
            w.write_value(&val).await.unwrap();
        }
        let mut r: &[u8] = &buf;
        let restored: (u8, u32, bool) = r.read_value().await.unwrap();
        assert_eq!(restored, val);
    }

    #[tokio::test]
    async fn single_element_tuple_roundtrip() {
        let val: (u32,) = (0xDEAD_BEEF,);
        let mut buf = [0u8; 4];
        {
            let mut w: &mut [u8] = &mut buf;
            w.write_value(&val).await.unwrap();
        }
        let mut r: &[u8] = &buf;
        let restored: (u32,) = r.read_value().await.unwrap();
        assert_eq!(restored, val);
    }
}

mod borrowed_write {
    use byteable::eio_async::EioAsyncWriteValue;

    #[tokio::test]
    async fn write_u8_slice_no_alloc() {
        let data: &[u8] = &[1, 2, 3];
        let mut buf = [0u8; 11];
        let mut w: &mut [u8] = &mut buf;
        w.write_value(data).await.unwrap();
        assert_eq!(&buf[..8], &3u64.to_le_bytes());
        assert_eq!(&buf[8..11], &[1, 2, 3]);
    }

    #[tokio::test]
    async fn write_str_no_alloc() {
        let s: &str = "hi";
        let mut buf = [0u8; 10];
        let mut w: &mut [u8] = &mut buf;
        w.write_value(s).await.unwrap();
        assert_eq!(&buf[..8], &2u64.to_le_bytes());
        assert_eq!(&buf[8..10], b"hi");
    }
}

#[cfg(feature = "alloc")]
mod alloc_collections {
    extern crate alloc;

    use alloc::string::String;
    use alloc::vec::Vec;
    use byteable::eio_async::{EioAsyncReadValue, EioAsyncWriteValue};

    #[tokio::test]
    async fn vec_roundtrip() {
        let v: Vec<u32> = alloc::vec![1, 2, 3];
        let mut buf = [0u8; 20];
        {
            let mut w: &mut [u8] = &mut buf;
            w.write_value(&v).await.unwrap();
        }
        let mut r: &[u8] = &buf;
        let restored: Vec<u32> = r.read_value().await.unwrap();
        assert_eq!(restored, v);
    }

    #[tokio::test]
    async fn string_roundtrip() {
        let s: String = String::from("hello");
        let mut buf = [0u8; 13];
        {
            let mut w: &mut [u8] = &mut buf;
            w.write_value(&s).await.unwrap();
        }
        let mut r: &[u8] = &buf;
        let restored: String = r.read_value().await.unwrap();
        assert_eq!(restored, s);
    }

    #[tokio::test]
    async fn string_invalid_utf8_is_decode_error() {
        use byteable::DecodeError;
        use byteable::eio::EioReadableError;
        let mut buf = [0u8; 9];
        buf[..8].copy_from_slice(&1u64.to_le_bytes());
        buf[8] = 0xFF; // invalid UTF-8 byte
        let mut r: &[u8] = &buf;
        let err = r.read_value::<String>().await.unwrap_err();
        assert!(matches!(
            err,
            EioReadableError::DecodeError(DecodeError::InvalidUtf8)
        ));
    }
}

#[cfg(feature = "std")]
mod hash_collections {
    use byteable::eio_async::{EioAsyncReadValue, EioAsyncWriteValue};
    use std::collections::{HashMap, HashSet};

    #[tokio::test]
    async fn hashmap_roundtrip() {
        let mut m: HashMap<u32, u32> = HashMap::new();
        m.insert(1, 10);
        m.insert(2, 20);
        let mut buf = [0u8; 32];
        {
            let mut w: &mut [u8] = &mut buf;
            w.write_value(&m).await.unwrap();
        }
        let mut r: &[u8] = &buf;
        let restored: HashMap<u32, u32> = r.read_value().await.unwrap();
        assert_eq!(restored, m);
    }

    #[tokio::test]
    async fn hashset_roundtrip() {
        let s: HashSet<u32> = HashSet::from([1, 2, 3]);
        let mut buf = [0u8; 20];
        {
            let mut w: &mut [u8] = &mut buf;
            w.write_value(&s).await.unwrap();
        }
        let mut r: &[u8] = &buf;
        let restored: HashSet<u32> = r.read_value().await.unwrap();
        assert_eq!(restored, s);
    }
}

mod dynamic_struct {
    use byteable::Byteable;
    use byteable::eio_async::{EioAsyncReadValue, EioAsyncWriteValue};

    #[derive(Byteable, Debug, PartialEq)]
    #[byteable(io_only)]
    struct Message {
        id: u32,
        flag: Option<u8>,
        #[byteable(big_endian)]
        tag: u16,
    }

    #[tokio::test]
    async fn io_only_struct_roundtrip_over_eio_async() {
        let msg = Message {
            id: 42,
            flag: Some(1),
            tag: 0x0102,
        };
        let mut buf = [0u8; 8];
        {
            let mut w: &mut [u8] = &mut buf;
            w.write_value(&msg).await.unwrap();
        }
        // id (4) + flag discriminant (1) + flag payload (1) = 6, so `tag` starts at offset 6
        // and must be laid out most-significant byte first.
        assert_eq!(&buf[6..8], &[0x01, 0x02]);
        let mut r: &[u8] = &buf;
        let restored: Message = r.read_value().await.unwrap();
        assert_eq!(restored, msg);
    }

    #[tokio::test]
    async fn io_only_struct_roundtrip_none_flag() {
        let msg = Message {
            id: 1,
            flag: None,
            tag: 0x0304,
        };
        let mut buf = [0u8; 7];
        {
            let mut w: &mut [u8] = &mut buf;
            w.write_value(&msg).await.unwrap();
        }
        // id (4) + flag discriminant (1) = 5, so `tag` starts at offset 5.
        assert_eq!(&buf[5..7], &[0x03, 0x04]);
        let mut r: &[u8] = &buf;
        let restored: Message = r.read_value().await.unwrap();
        assert_eq!(restored, msg);
    }
}

mod field_enum {
    use byteable::Byteable;
    use byteable::eio_async::{EioAsyncReadValue, EioAsyncWriteValue};

    #[derive(Byteable, Debug, PartialEq)]
    enum Command {
        Nothing,
        Read(u32, u64),
        Write { a: u32, b: u64 },
    }

    #[tokio::test]
    async fn tuple_and_named_variants_roundtrip_over_eio_async() {
        for cmd in [
            Command::Nothing,
            Command::Read(1, 2),
            Command::Write { a: 3, b: 4 },
        ] {
            let mut buf = [0u8; 32];
            {
                let mut w: &mut [u8] = &mut buf;
                w.write_value(&cmd).await.unwrap();
            }
            let mut r: &[u8] = &buf;
            let restored: Command = r.read_value().await.unwrap();
            assert_eq!(restored, cmd);
        }
    }
}