musli_zerocopy/buf/
load.rs

1use crate::buf::Buf;
2use crate::endian::ByteOrder;
3use crate::error::Error;
4use crate::pointer::{Ref, Size};
5use crate::traits::ZeroCopy;
6
7/// Trait used for loading any kind of reference through [`Buf::load`].
8///
9/// This is a high level trait which can be implemented safely, typically it's
10/// used to build facade types for when you want some type to behave like a
11/// different type, but have a different layout.
12///
13/// See the [module level documentation][crate::buf#extension-traits] for an
14/// example.
15pub trait Load {
16    /// The target being read.
17    type Target: ?Sized;
18
19    /// Validate the value.
20    fn load<'buf>(&self, buf: &'buf Buf) -> Result<&'buf Self::Target, Error>;
21}
22
23/// Trait used for loading any kind of reference through [`Buf::load_mut`].
24///
25/// This is a high level trait which can be implemented safely, typically it's
26/// used to build facade types for when you want some type to behave like a
27/// different type, but have a different layout.
28///
29/// See the [module level documentation][crate::buf#extension-traits] for an
30/// example.
31pub trait LoadMut: Load {
32    /// Validate the value.
33    fn load_mut<'buf>(&self, buf: &'buf mut Buf) -> Result<&'buf mut Self::Target, Error>;
34}
35
36impl<T, E, O> Load for Ref<T, E, O>
37where
38    T: ZeroCopy,
39    E: ByteOrder,
40    O: Size,
41{
42    type Target = T;
43
44    #[inline]
45    fn load<'buf>(&self, buf: &'buf Buf) -> Result<&'buf Self::Target, Error> {
46        buf.load_sized::<T>(self.offset())
47    }
48}
49
50impl<T, E, O> Load for Ref<[T], E, O>
51where
52    T: ZeroCopy,
53    E: ByteOrder,
54    O: Size,
55{
56    type Target = [T];
57
58    #[inline]
59    fn load<'buf>(&self, buf: &'buf Buf) -> Result<&'buf Self::Target, Error> {
60        buf.load_unsized(*self)
61    }
62}
63
64impl<E, O> Load for Ref<str, E, O>
65where
66    E: ByteOrder,
67    O: Size,
68{
69    type Target = str;
70
71    #[inline]
72    fn load<'buf>(&self, buf: &'buf Buf) -> Result<&'buf Self::Target, Error> {
73        buf.load_unsized(*self)
74    }
75}
76
77impl<T, E, O> LoadMut for Ref<T, E, O>
78where
79    T: ZeroCopy,
80    E: ByteOrder,
81    O: Size,
82{
83    #[inline]
84    fn load_mut<'buf>(&self, buf: &'buf mut Buf) -> Result<&'buf mut Self::Target, Error> {
85        buf.load_sized_mut::<T>(self.offset())
86    }
87}
88
89impl<T, E, O> LoadMut for Ref<[T], E, O>
90where
91    T: ZeroCopy,
92    E: ByteOrder,
93    O: Size,
94{
95    #[inline]
96    fn load_mut<'buf>(&self, buf: &'buf mut Buf) -> Result<&'buf mut Self::Target, Error> {
97        buf.load_unsized_mut(*self)
98    }
99}
100
101impl<E, O> LoadMut for Ref<str, E, O>
102where
103    E: ByteOrder,
104    O: Size,
105{
106    #[inline]
107    fn load_mut<'buf>(&self, buf: &'buf mut Buf) -> Result<&'buf mut Self::Target, Error> {
108        buf.load_unsized_mut(*self)
109    }
110}