byteable 0.38.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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
//! `embedded-io` (sync) support - the `no_std`-friendly counterpart to [`crate::io`].
//!
//! Mirrors `io.rs`'s shape, but is generic over the [`EioReader`]/[`EioWriter`] marker traits
//! defined here rather than bound directly to `embedded_io::Read`/`Write`. Gated on the
//! `embedded-io` feature (`src/lib.rs`), same as `io.rs` is gated on `std`. The derive macro
//! only ever emits references to this module's traits when `byteable_derive`'s own mirrored
//! `embedded-io` feature is active (see `dynamic_pipeline_impls` in `byteable_derive/src/lib.rs`),
//! which is forwarded 1:1 from this crate's own `embedded-io` feature - so generated code and
//! this module's availability always agree; there's no case where generated code needs to
//! name-resolve these traits while this module is absent.

use crate::{DecodeError, PlainOldData, RawRepr, TryFromRawRepr};
use core::fmt;
use core::net::{IpAddr, SocketAddr};
use core::ops::Bound;

/// Minimal read primitive. Bridged to `embedded_io::Read` when the `embedded-io` feature is on.
///
/// Deliberately mirrors `embedded_io::Read`'s method surface (not just the raw `read`
/// primitive) so that any specialized override a concrete driver provides for `read_exact`
/// (e.g. a DMA-driven bulk transfer) is what actually runs, not a generic loop of ours. Methods
/// are prefixed `eio_` (rather than reusing `embedded_io::Read`'s bare `read`/`read_exact`
/// names) because the blanket impl below means every `embedded_io::Read` type also implements
/// this trait - unprefixed names would make plain method-call syntax ambiguous (`E0034`)
/// whenever both traits are in scope, which is the common case for callers.
pub trait EioReader {
    /// The backend's own error type.
    type Error;

    /// Read some bytes into `buf`, returning how many were read.
    fn eio_read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error>;

    /// Read exactly `buf.len()` bytes, blocking as needed.
    fn eio_read_exact(&mut self, buf: &mut [u8]) -> Result<(), EioReadExactError<Self::Error>>;
}

/// Minimal write primitive. Bridged to `embedded_io::Write` when the `embedded-io` feature is on.
///
/// See [`EioReader`] for why these methods are `eio_`-prefixed rather than reusing
/// `embedded_io::Write`'s bare names.
pub trait EioWriter {
    /// The backend's own error type.
    type Error;

    /// Write some bytes from `buf`, returning how many were written.
    fn eio_write(&mut self, buf: &[u8]) -> Result<usize, Self::Error>;

    /// Write all of `buf`, blocking as needed.
    fn eio_write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error>;

    /// Flush any buffered output.
    fn eio_flush(&mut self) -> Result<(), Self::Error>;
}

/// Error returned by [`EioReader::read_exact`]. Mirrors `embedded_io::ReadExactError<E>`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum EioReadExactError<E> {
    /// End-of-input was reached before `buf` was fully filled.
    UnexpectedEof,
    /// The underlying reader returned an error.
    Other(E),
}

impl<E: fmt::Debug> fmt::Display for EioReadExactError<E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{self:?}")
    }
}

#[cfg(feature = "std")]
impl<E: fmt::Debug> std::error::Error for EioReadExactError<E> {}

impl<T: ::embedded_io::Read + ?Sized> EioReader for T {
    type Error = T::Error;

    #[inline]
    fn eio_read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
        ::embedded_io::Read::read(self, buf)
    }

    #[inline]
    fn eio_read_exact(&mut self, buf: &mut [u8]) -> Result<(), EioReadExactError<Self::Error>> {
        ::embedded_io::Read::read_exact(self, buf).map_err(|e| match e {
            ::embedded_io::ReadExactError::UnexpectedEof => EioReadExactError::UnexpectedEof,
            ::embedded_io::ReadExactError::Other(err) => EioReadExactError::Other(err),
        })
    }
}

impl<T: ::embedded_io::Write + ?Sized> EioWriter for T {
    type Error = T::Error;

    #[inline]
    fn eio_write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
        ::embedded_io::Write::write(self, buf)
    }

    #[inline]
    fn eio_write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
        ::embedded_io::Write::write_all(self, buf)
    }

    #[inline]
    fn eio_flush(&mut self) -> Result<(), Self::Error> {
        ::embedded_io::Write::flush(self)
    }
}

/// Error returned when reading a value from an [`EioReader`] source fails.
///
/// Independent of [`crate::io::ReadableError`], which stays `std::io::Error`-based and
/// untouched by this module.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum EioReadableError<E> {
    /// The underlying reader returned an error.
    Io(E),
    /// End-of-input was reached before a complete value could be read.
    UnexpectedEof,
    /// The bytes were read successfully but do not decode into a valid value.
    DecodeError(DecodeError),
}

impl<E> From<EioReadExactError<E>> for EioReadableError<E> {
    fn from(e: EioReadExactError<E>) -> Self {
        match e {
            EioReadExactError::UnexpectedEof => Self::UnexpectedEof,
            EioReadExactError::Other(err) => Self::Io(err),
        }
    }
}

impl<E> From<DecodeError> for EioReadableError<E> {
    fn from(e: DecodeError) -> Self {
        Self::DecodeError(e)
    }
}

impl<E: fmt::Debug> fmt::Display for EioReadableError<E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{self:?}")
    }
}

#[cfg(feature = "std")]
impl<E: fmt::Debug> std::error::Error for EioReadableError<E> {}

/// `eio` counterpart of [`crate::io::FixedReadable`].
pub trait EioFixedReadable: Sized {
    /// Read exactly `size_of::<Self::Raw>()` bytes and decode them into `Self`.
    fn read_fixed_from<R: EioReader + ?Sized>(
        reader: &mut R,
    ) -> Result<Self, EioReadableError<R::Error>>;
}

impl<T: TryFromRawRepr> EioFixedReadable for T {
    #[inline]
    fn read_fixed_from<R: EioReader + ?Sized>(
        reader: &mut R,
    ) -> Result<Self, EioReadableError<R::Error>> {
        let mut b = T::Raw::zeroed();
        reader.eio_read_exact(b.as_bytes_mut())?;
        let r = T::try_from_raw(b)?;
        Ok(r)
    }
}

/// `eio` counterpart of [`crate::io::Readable`].
pub trait EioReadable: Sized {
    /// Read a value from `reader`.
    fn read_from<R: EioReader + ?Sized>(reader: &mut R)
    -> Result<Self, EioReadableError<R::Error>>;
}

impl<T: EioFixedReadable> EioReadable for T {
    #[inline]
    fn read_from<R: EioReader + ?Sized>(
        reader: &mut R,
    ) -> Result<Self, EioReadableError<R::Error>> {
        T::read_fixed_from(reader)
    }
}

/// `eio` counterpart of [`crate::io::FixedWritable`].
pub trait EioFixedWritable {
    /// Write the fixed-size byte representation of `self` to `writer`.
    fn write_fixed_to<W: EioWriter + ?Sized>(&self, writer: &mut W) -> Result<(), W::Error>;
}

impl<T: RawRepr> EioFixedWritable for T {
    #[inline]
    fn write_fixed_to<W: EioWriter + ?Sized>(&self, writer: &mut W) -> Result<(), W::Error> {
        let raw = self.to_raw();
        writer.eio_write_all(raw.as_bytes())
    }
}

/// `eio` counterpart of [`crate::io::Writable`].
pub trait EioWritable {
    /// Write `self` to `writer`.
    fn write_to<W: EioWriter + ?Sized>(&self, writer: &mut W) -> Result<(), W::Error>;
}

impl<T: EioFixedWritable> EioWritable for T {
    #[inline]
    fn write_to<W: EioWriter + ?Sized>(&self, writer: &mut W) -> Result<(), W::Error> {
        self.write_fixed_to(writer)
    }
}

/// Extension trait adding [`read_fixed`](EioReadFixed::read_fixed) to any [`EioReader`].
pub trait EioReadFixed: EioReader {
    #[inline]
    fn read_fixed<T: EioFixedReadable>(&mut self) -> Result<T, EioReadableError<Self::Error>> {
        T::read_fixed_from(self)
    }
}
impl<T: EioReader + ?Sized> EioReadFixed for T {}

/// Extension trait adding [`read_value`](EioReadValue::read_value) to any [`EioReader`].
pub trait EioReadValue: EioReader {
    #[inline]
    fn read_value<T: EioReadable>(&mut self) -> Result<T, EioReadableError<Self::Error>> {
        T::read_from(self)
    }
}
impl<T: EioReader + ?Sized> EioReadValue for T {}

/// Extension trait adding [`write_fixed`](EioWriteFixed::write_fixed) to any [`EioWriter`].
pub trait EioWriteFixed: EioWriter {
    #[inline]
    fn write_fixed(&mut self, val: &impl EioFixedWritable) -> Result<(), Self::Error> {
        val.write_fixed_to(self)
    }
}
impl<T: EioWriter + ?Sized> EioWriteFixed for T {}

/// Extension trait adding [`write_value`](EioWriteValue::write_value) to any [`EioWriter`].
pub trait EioWriteValue: EioWriter {
    #[inline]
    fn write_value<T: EioWritable + ?Sized>(&mut self, data: &T) -> Result<(), Self::Error> {
        data.write_to(self)
    }
}
impl<T: EioWriter + ?Sized> EioWriteValue for T {}

// Wire format: 1-byte tag (0 = None, 1 = Some), followed by the value when Some. No alloc needed.
impl<T: EioReadable> EioReadable for Option<T> {
    fn read_from<R: EioReader + ?Sized>(
        reader: &mut R,
    ) -> Result<Self, EioReadableError<R::Error>> {
        let tag: u8 = reader.read_fixed()?;
        match tag {
            0 => Ok(None),
            1 => Ok(Some(reader.read_value()?)),
            _ => Err(EioReadableError::DecodeError(DecodeError::InvalidTag {
                raw: tag,
                type_name: "Option",
            })),
        }
    }
}

impl<T: EioWritable> EioWritable for Option<T> {
    fn write_to<W: EioWriter + ?Sized>(&self, writer: &mut W) -> Result<(), W::Error> {
        match self {
            None => writer.write_fixed(&0u8),
            Some(val) => {
                writer.write_fixed(&1u8)?;
                writer.write_value(val)
            }
        }
    }
}

// Wire format: 1-byte tag (0 = Ok, 1 = Err), followed by the Ok value or Err value.
impl<V: EioReadable, E: EioReadable> EioReadable for Result<V, E> {
    fn read_from<R: EioReader + ?Sized>(
        reader: &mut R,
    ) -> Result<Self, EioReadableError<R::Error>> {
        let discriminator: u8 = reader.read_fixed()?;
        match discriminator {
            0 => Ok(Ok(reader.read_value()?)),
            1 => Ok(Err(reader.read_value()?)),
            _ => Err(EioReadableError::DecodeError(DecodeError::InvalidTag {
                raw: discriminator,
                type_name: "Result",
            })),
        }
    }
}

impl<V: EioWritable, Er: EioWritable> EioWritable for Result<V, Er> {
    fn write_to<W: EioWriter + ?Sized>(&self, writer: &mut W) -> Result<(), W::Error> {
        match self {
            Ok(val) => {
                writer.write_fixed(&0u8)?;
                writer.write_value(val)
            }
            Err(err) => {
                writer.write_fixed(&1u8)?;
                writer.write_value(err)
            }
        }
    }
}

// Wire format: 1-byte tag (0 = V4, 1 = V6), followed by the variant's fixed-size address. No
// alloc needed.
impl EioReadable for IpAddr {
    fn read_from<R: EioReader + ?Sized>(
        reader: &mut R,
    ) -> Result<Self, EioReadableError<R::Error>> {
        let tag: u8 = reader.read_fixed()?;
        match tag {
            0 => Ok(IpAddr::V4(reader.read_fixed()?)),
            1 => Ok(IpAddr::V6(reader.read_fixed()?)),
            _ => Err(EioReadableError::DecodeError(DecodeError::InvalidTag {
                raw: tag,
                type_name: "IpAddr",
            })),
        }
    }
}

impl EioWritable for IpAddr {
    fn write_to<W: EioWriter + ?Sized>(&self, writer: &mut W) -> Result<(), W::Error> {
        match self {
            IpAddr::V4(addr) => {
                writer.write_fixed(&0u8)?;
                writer.write_fixed(addr)
            }
            IpAddr::V6(addr) => {
                writer.write_fixed(&1u8)?;
                writer.write_fixed(addr)
            }
        }
    }
}

// Wire format: 1-byte tag (0 = V4, 1 = V6), followed by the variant's fixed-size address. No
// alloc needed.
impl EioReadable for SocketAddr {
    fn read_from<R: EioReader + ?Sized>(
        reader: &mut R,
    ) -> Result<Self, EioReadableError<R::Error>> {
        let tag: u8 = reader.read_fixed()?;
        match tag {
            0 => Ok(SocketAddr::V4(reader.read_fixed()?)),
            1 => Ok(SocketAddr::V6(reader.read_fixed()?)),
            _ => Err(EioReadableError::DecodeError(DecodeError::InvalidTag {
                raw: tag,
                type_name: "SocketAddr",
            })),
        }
    }
}

impl EioWritable for SocketAddr {
    fn write_to<W: EioWriter + ?Sized>(&self, writer: &mut W) -> Result<(), W::Error> {
        match self {
            SocketAddr::V4(addr) => {
                writer.write_fixed(&0u8)?;
                writer.write_fixed(addr)
            }
            SocketAddr::V6(addr) => {
                writer.write_fixed(&1u8)?;
                writer.write_fixed(addr)
            }
        }
    }
}

// Wire format: 1-byte tag (0 = Included, 1 = Excluded, 2 = Unbounded), followed by the bound
// value for Included/Excluded. No alloc needed.
impl<T: EioReadable> EioReadable for Bound<T> {
    fn read_from<R: EioReader + ?Sized>(
        reader: &mut R,
    ) -> Result<Self, EioReadableError<R::Error>> {
        let tag: u8 = reader.read_fixed()?;
        match tag {
            0 => Ok(Bound::Included(reader.read_value()?)),
            1 => Ok(Bound::Excluded(reader.read_value()?)),
            2 => Ok(Bound::Unbounded),
            _ => Err(EioReadableError::DecodeError(DecodeError::InvalidTag {
                raw: tag,
                type_name: "Bound",
            })),
        }
    }
}

impl<T: EioWritable> EioWritable for Bound<T> {
    fn write_to<W: EioWriter + ?Sized>(&self, writer: &mut W) -> Result<(), W::Error> {
        match self {
            Bound::Included(val) => {
                writer.write_fixed(&0u8)?;
                writer.write_value(val)
            }
            Bound::Excluded(val) => {
                writer.write_fixed(&1u8)?;
                writer.write_value(val)
            }
            Bound::Unbounded => writer.write_fixed(&2u8),
        }
    }
}

// Wire format: no tag or length prefix - arity is fixed at compile time, so each element is
// just serialized in order. Implemented for tuples of arity 1 through 12; see `std_types.rs`
// for why the macro reuses each type parameter identifier as a binding name. No alloc needed.
macro_rules! impl_tuple {
    ($($T:ident),+) => {
        impl<$($T: EioReadable),+> EioReadable for ($($T,)+) {
            fn read_from<R: EioReader + ?Sized>(
                reader: &mut R,
            ) -> Result<Self, EioReadableError<R::Error>> {
                Ok(($(reader.read_value::<$T>()?,)+))
            }
        }

        impl<$($T: EioWritable),+> EioWritable for ($($T,)+) {
            fn write_to<W: EioWriter + ?Sized>(&self, writer: &mut W) -> Result<(), W::Error> {
                #[allow(non_snake_case)]
                let ($($T,)+) = self;
                $( writer.write_value($T)?; )+
                Ok(())
            }
        }
    };
}

impl_tuple!(A);
impl_tuple!(A, B);
impl_tuple!(A, B, C);
impl_tuple!(A, B, C, D);
impl_tuple!(A, B, C, D, E);
impl_tuple!(A, B, C, D, E, F);
impl_tuple!(A, B, C, D, E, F, G);
impl_tuple!(A, B, C, D, E, F, G, H);
impl_tuple!(A, B, C, D, E, F, G, H, I);
impl_tuple!(A, B, C, D, E, F, G, H, I, J);
impl_tuple!(A, B, C, D, E, F, G, H, I, J, K);
impl_tuple!(A, B, C, D, E, F, G, H, I, J, K, L);

// Wire format: `u64` element count (LE) + elements in order. Write-only (borrowed): never
// allocates, so this is available without the `alloc` feature.
impl<T: EioWritable> EioWritable for [T] {
    fn write_to<W: EioWriter + ?Sized>(&self, writer: &mut W) -> Result<(), W::Error> {
        let len: u64 = self
            .len()
            .try_into()
            .expect("could not convert usize to u64");
        writer.write_fixed(&len)?;
        for el in self {
            writer.write_value(el)?;
        }
        Ok(())
    }
}

// Wire format: `u64` byte length (LE) + UTF-8 bytes. Write-only (borrowed), no `alloc` needed.
impl EioWritable for str {
    fn write_to<W: EioWriter + ?Sized>(&self, writer: &mut W) -> Result<(), W::Error> {
        let len: u64 = self
            .len()
            .try_into()
            .expect("could not convert usize to u64");
        writer.write_fixed(&len)?;
        writer.eio_write_all(self.as_bytes())
    }
}