Skip to main content

le_stream/
prefixed.rs

1use core::fmt::Debug;
2use core::marker::PhantomData;
3use core::ops::{Deref, DerefMut};
4
5mod alloc;
6mod bytes;
7
8/// A wrapper that serializes a collection with a little-endian length prefix.
9///
10/// `P` is the integer type used for the prefix and `D` is the wrapped data.
11/// Implementations are provided for selected collection types behind feature
12/// flags. For example, `Prefixed<usize, Box<[u8]>>` serializes as a `usize`
13/// element count followed by the bytes in the boxed slice when the `alloc`
14/// feature is enabled. `Prefixed<P, bytes::Bytes>` and
15/// `Prefixed<P, bytes::BytesMut>` serialize a byte count followed by exactly
16/// that many raw bytes when the `bytes` feature is enabled.
17#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
18#[repr(transparent)]
19pub struct Prefixed<P, D> {
20    data: D,
21    prefix: PhantomData<P>,
22}
23
24impl<P, D> Prefixed<P, D> {
25    /// Returns the wrapped data without its prefix marker.
26    pub fn into_data(self) -> D {
27        self.data
28    }
29}
30
31impl<P, D, T> AsRef<T> for Prefixed<P, D>
32where
33    T: ?Sized,
34    D: AsRef<T>,
35{
36    fn as_ref(&self) -> &T {
37        self.data.as_ref()
38    }
39}
40
41impl<P, D, T> AsMut<T> for Prefixed<P, D>
42where
43    T: ?Sized,
44    D: AsMut<T>,
45{
46    fn as_mut(&mut self) -> &mut T {
47        self.data.as_mut()
48    }
49}
50
51impl<P, D> Deref for Prefixed<P, D>
52where
53    D: Deref,
54{
55    type Target = D::Target;
56
57    fn deref(&self) -> &Self::Target {
58        &self.data
59    }
60}
61
62impl<P, D> DerefMut for Prefixed<P, D>
63where
64    D: DerefMut,
65{
66    fn deref_mut(&mut self) -> &mut Self::Target {
67        &mut self.data
68    }
69}
70
71impl<P, D> IntoIterator for Prefixed<P, D>
72where
73    D: IntoIterator,
74{
75    type Item = D::Item;
76    type IntoIter = D::IntoIter;
77
78    fn into_iter(self) -> Self::IntoIter {
79        self.data.into_iter()
80    }
81}