Skip to main content

le_stream/
prefixed.rs

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