automotive-wire-codec 0.3.0

Zero-copy, no_std, no-alloc binary codec traits for automotive diagnostic protocols
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
//! Big-endian, `core`-only slice read helpers. Each returns `(value, remainder)` so
//! callers thread the remainder through sequential/nested decodes.

use core::mem::size_of;

use crate::error::{Incomplete, InvalidWidth};

/// Split `n` bytes off the front of `buf`, returning `(head, tail)`.
///
/// # Errors
/// [`Incomplete`] if `buf` has fewer than `n` bytes.
pub fn take(buf: &[u8], n: usize) -> Result<(&[u8], &[u8]), Incomplete> {
    if buf.len() < n {
        Err(Incomplete {
            needed: n,
            available: buf.len(),
        })
    } else {
        Ok(buf.split_at(n))
    }
}

/// Read a single byte.
///
/// # Errors
/// [`Incomplete`] if `buf` is empty.
pub fn read_u8(buf: &[u8]) -> Result<(u8, &[u8]), Incomplete> {
    let (b, rest) = take(buf, 1)?;
    Ok((b[0], rest))
}

/// Read a big-endian `u16`.
///
/// # Errors
/// [`Incomplete`] if fewer than 2 bytes remain.
pub fn read_u16_be(buf: &[u8]) -> Result<(u16, &[u8]), Incomplete> {
    let (b, rest) = take(buf, 2)?;
    Ok((u16::from_be_bytes([b[0], b[1]]), rest))
}

/// Read a big-endian `u32`.
///
/// # Errors
/// [`Incomplete`] if fewer than 4 bytes remain.
pub fn read_u32_be(buf: &[u8]) -> Result<(u32, &[u8]), Incomplete> {
    let (b, rest) = take(buf, 4)?;
    Ok((u32::from_be_bytes([b[0], b[1], b[2], b[3]]), rest))
}

/// Read a big-endian `u64`.
///
/// # Errors
/// [`Incomplete`] if fewer than 8 bytes remain.
pub fn read_u64_be(buf: &[u8]) -> Result<(u64, &[u8]), Incomplete> {
    let (b, rest) = take(buf, 8)?;
    Ok((
        u64::from_be_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]),
        rest,
    ))
}

/// Read a big-endian `u128`.
///
/// # Errors
/// [`Incomplete`] if fewer than 16 bytes remain.
pub fn read_u128_be(buf: &[u8]) -> Result<(u128, &[u8]), Incomplete> {
    let (arr, rest) = read_array::<16>(buf)?;
    Ok((u128::from_be_bytes(arr), rest))
}

/// Read a fixed-size `N`-byte array (e.g. a 17-byte VIN, a 6-byte EID).
///
/// # Errors
/// [`Incomplete`] if fewer than `N` bytes remain.
pub fn read_array<const N: usize>(buf: &[u8]) -> Result<([u8; N], &[u8]), Incomplete> {
    let (b, rest) = take(buf, N)?;
    let mut arr = [0u8; N];
    arr.copy_from_slice(b);
    Ok((arr, rest))
}

/// Error from the variable-width read helpers ([`read_be_uint`],
/// `read_be_uint_into`).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ReadUintError {
    /// Not enough input bytes.
    Incomplete(Incomplete),
    /// Requested width out of range for the operation.
    InvalidWidth(InvalidWidth),
}

impl From<Incomplete> for ReadUintError {
    fn from(e: Incomplete) -> Self {
        ReadUintError::Incomplete(e)
    }
}
impl From<InvalidWidth> for ReadUintError {
    fn from(e: InvalidWidth) -> Self {
        ReadUintError::InvalidWidth(e)
    }
}
impl core::fmt::Display for ReadUintError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            ReadUintError::Incomplete(e) => e.fmt(f),
            ReadUintError::InvalidWidth(e) => e.fmt(f),
        }
    }
}
impl core::error::Error for ReadUintError {}

/// Read a variable-width (`0..=16` byte) big-endian unsigned integer into a `u128`.
///
/// The width may come straight off the wire: an out-of-range `n` is a *data*
/// error ([`InvalidWidth`]), not a panic, in every build profile. `n == 0` is
/// legal: it reads nothing and returns `0` (protocols that require a minimum
/// width of 1 must validate that upstream).
///
/// # Errors
/// [`ReadUintError::InvalidWidth`] if `n > 16`;
/// [`ReadUintError::Incomplete`] if fewer than `n` bytes remain.
pub fn read_be_uint(buf: &[u8], n: usize) -> Result<(u128, &[u8]), ReadUintError> {
    if n > 16 {
        return Err(InvalidWidth { max: 16, got: n }.into());
    }
    let (b, rest) = take(buf, n)?;
    let mut acc: u128 = 0;
    for &byte in b {
        acc = (acc << 8) | u128::from(byte);
    }
    Ok((acc, rest))
}

mod sealed {
    pub trait Sealed {}
}

/// Unsigned-integer targets for [`read_be_uint_into`]. Sealed: implemented for
/// `u8`, `u16`, `u32`, `u64`, `u128` only.
pub trait BeUint: sealed::Sealed + Sized {
    /// Byte width of the target type.
    const BYTES: usize;
    #[doc(hidden)]
    fn from_u128(v: u128) -> Self;
}

macro_rules! impl_be_uint {
    ($($t:ty),*) => {$(
        impl sealed::Sealed for $t {}
        impl BeUint for $t {
            const BYTES: usize = size_of::<$t>();
            #[allow(clippy::cast_possible_truncation, clippy::cast_lossless)]
            fn from_u128(v: u128) -> Self {
                // Callers guarantee v < 2^(8 * BYTES); see read_be_uint_into.
                v as $t
            }
        }
    )*};
}
impl_be_uint!(u8, u16, u32, u64, u128);

/// Read a variable-width big-endian unsigned integer directly into `T`,
/// validating the width against `T`'s size — no `as` cast at the call site,
/// and a width the target cannot hold is a typed data error.
///
/// # Errors
/// [`ReadUintError::InvalidWidth`] if `n > size_of::<T>()`;
/// [`ReadUintError::Incomplete`] if fewer than `n` bytes remain.
pub fn read_be_uint_into<T: BeUint>(buf: &[u8], n: usize) -> Result<(T, &[u8]), ReadUintError> {
    if n > T::BYTES {
        return Err(InvalidWidth {
            max: T::BYTES,
            got: n,
        }
        .into());
    }
    let (v, rest) = read_be_uint(buf, n)?;
    Ok((T::from_u128(v), rest))
}

/// `Ok(())` if `buf` has at least `needed` bytes, else [`Incomplete`].
///
/// The check-only form of [`take`]: use it before an aggregate read whose
/// parts you slice manually.
///
/// # Errors
/// [`Incomplete`] if `buf` has fewer than `needed` bytes.
#[inline]
pub fn ensure_len(buf: &[u8], needed: usize) -> Result<(), Incomplete> {
    if buf.len() < needed {
        Err(Incomplete {
            needed,
            available: buf.len(),
        })
    } else {
        Ok(())
    }
}

/// Read an optional fixed-size trailing array: `Some` + remainder when `N`
/// bytes are present, `(None, buf)` (buffer untouched) when they are not.
///
/// "Not enough bytes" is the `None` case, not an error — this helper is for
/// fields a protocol defines as legitimately absent at the tail (e.g. `DoIP`'s
/// optional 4-byte OEM fields). A *partial* tail (`1..N` bytes) also returns
/// `None` and leaves the bytes in place, so a subsequent
/// [`Decode::decode_exact`](crate::Decode::decode_exact) surfaces them as
/// [`TrailingBytes`](crate::TrailingBytes).
#[must_use]
pub fn read_optional_array<const N: usize>(buf: &[u8]) -> (Option<[u8; N]>, &[u8]) {
    match read_array::<N>(buf) {
        Ok((arr, rest)) => (Some(arr), rest),
        Err(_) => (None, buf),
    }
}

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

    #[test]
    fn take_splits_and_returns_remainder() {
        let (head, tail) = take(&[1, 2, 3, 4], 2).unwrap();
        assert_eq!(head, &[1, 2]);
        assert_eq!(tail, &[3, 4]);
    }

    #[test]
    fn take_past_end_is_incomplete() {
        let buf = [1, 2, 3];
        assert_eq!(
            take(&buf, 4),
            Err(Incomplete {
                needed: 4,
                available: 3
            })
        );
    }

    #[test]
    fn read_u16_be_reads_big_endian_and_remainder() {
        let (v, rest) = read_u16_be(&[0x12, 0x34, 0x56]).unwrap();
        assert_eq!(v, 0x1234);
        assert_eq!(rest, &[0x56]);
    }

    #[test]
    fn read_u32_be_exact_leaves_empty_remainder() {
        let (v, rest) = read_u32_be(&[0xDE, 0xAD, 0xBE, 0xEF]).unwrap();
        assert_eq!(v, 0xDEAD_BEEF);
        assert!(rest.is_empty());
    }

    #[test]
    fn read_helpers_one_byte_short_are_incomplete() {
        assert_eq!(
            read_u8(&[]),
            Err(Incomplete {
                needed: 1,
                available: 0
            })
        );
        assert_eq!(
            read_u16_be(&[0]),
            Err(Incomplete {
                needed: 2,
                available: 1
            })
        );
        assert_eq!(
            read_u32_be(&[0; 3]),
            Err(Incomplete {
                needed: 4,
                available: 3
            })
        );
        assert_eq!(
            read_u64_be(&[0; 7]),
            Err(Incomplete {
                needed: 8,
                available: 7
            })
        );
    }

    #[test]
    fn read_array_reads_fixed_width() {
        let (arr, rest) = read_array::<3>(&[1, 2, 3, 4]).unwrap();
        assert_eq!(arr, [1, 2, 3]);
        assert_eq!(rest, &[4]);
        assert_eq!(
            read_array::<3>(&[1, 2]),
            Err(Incomplete {
                needed: 3,
                available: 2
            })
        );
    }

    #[test]
    fn read_be_uint_reads_low_n_bytes() {
        let (v, rest) = read_be_uint(&[0x01, 0x02, 0x03], 2).unwrap();
        assert_eq!(v, 0x0102);
        assert_eq!(rest, &[0x03]);
        assert_eq!(
            read_be_uint(&[0x00], 2),
            Err(ReadUintError::Incomplete(Incomplete {
                needed: 2,
                available: 1
            }))
        );
    }

    #[test]
    fn read_be_uint_hostile_width_is_data_error_not_panic() {
        // SE-1: n > 16 must be a recoverable error in ALL build profiles.
        let buf = [0u8; 300];
        assert_eq!(
            read_be_uint(&buf, 255),
            Err(ReadUintError::InvalidWidth(InvalidWidth {
                max: 16,
                got: 255
            }))
        );
        assert_eq!(
            read_be_uint(&buf, 17),
            Err(ReadUintError::InvalidWidth(InvalidWidth {
                max: 16,
                got: 17
            }))
        );
    }

    #[test]
    fn read_be_uint_zero_width_reads_nothing() {
        // Documented contract: n == 0 is legal, reads nothing, returns 0.
        let buf = [0xAA, 0xBB];
        let (v, rest) = read_be_uint(&buf, 0).unwrap();
        assert_eq!(v, 0);
        assert_eq!(rest, &buf);
    }

    #[test]
    fn read_be_uint_into_returns_target_type() {
        // SE-4: no `as` cast, no clippy allow at the call site.
        let buf = [0x01, 0x02, 0x03, 0xFF];
        let (v, rest) = read_be_uint_into::<u32>(&buf, 3).unwrap();
        assert_eq!(v, 0x0001_0203_u32);
        assert_eq!(rest, &[0xFF]);
    }

    #[test]
    fn read_be_uint_into_rejects_width_wider_than_target() {
        // n = 5 fits in a u128 but NOT in the u32 target: typed data error.
        let buf = [0u8; 8];
        assert_eq!(
            read_be_uint_into::<u32>(&buf, 5),
            Err(ReadUintError::InvalidWidth(InvalidWidth { max: 4, got: 5 }))
        );
    }

    #[test]
    fn read_be_uint_into_full_width_roundtrips() {
        let buf = 0xDEAD_BEEF_u32.to_be_bytes();
        let (v, rest) = read_be_uint_into::<u32>(&buf, 4).unwrap();
        assert_eq!(v, 0xDEAD_BEEF);
        assert!(rest.is_empty());
        let (b, _) = read_be_uint_into::<u8>(&buf, 1).unwrap();
        assert_eq!(b, 0xDE);
    }

    #[test]
    fn read_u128_be_reads_full_width() {
        let v = 0x0102_0304_0506_0708_090A_0B0C_0D0E_0F10_u128;
        let bytes = v.to_be_bytes();
        let mut buf = [0u8; 17];
        buf[..16].copy_from_slice(&bytes);
        buf[16] = 0xFF;
        let (got, rest) = read_u128_be(&buf).unwrap();
        assert_eq!(got, v);
        assert_eq!(rest, &[0xFF]);
        assert_eq!(
            read_u128_be(&[0u8; 15]),
            Err(Incomplete {
                needed: 16,
                available: 15
            })
        );
    }

    #[test]
    fn ensure_len_passes_and_fails_with_counts() {
        assert_eq!(ensure_len(&[1, 2, 3], 3), Ok(()));
        assert_eq!(ensure_len(&[1, 2, 3], 2), Ok(()));
        assert_eq!(
            ensure_len(&[1, 2, 3], 4),
            Err(Incomplete {
                needed: 4,
                available: 3
            })
        );
    }

    #[test]
    fn read_optional_array_present_and_absent() {
        // doip P2: "not enough bytes" IS the None case, not an error.
        let (arr, rest) = read_optional_array::<4>(&[1, 2, 3, 4, 5]);
        assert_eq!(arr, Some([1, 2, 3, 4]));
        assert_eq!(rest, &[5]);

        let (arr, rest) = read_optional_array::<4>(&[]);
        assert_eq!(arr, None);
        assert!(rest.is_empty());

        // Partial tail: None, buffer untouched — a following decode_exact
        // will surface the stragglers as TrailingBytes.
        let (arr, rest) = read_optional_array::<4>(&[1, 2]);
        assert_eq!(arr, None);
        assert_eq!(rest, &[1, 2]);
    }
}