ab_aligned_buffer/
reader.rs1#[cfg(test)]
4mod tests;
5
6use crate::SharedAlignedBuffer;
7use crate::alignment::Alignment;
8#[cfg(feature = "io-type")]
9use ab_io_type::trivial_type::AnyBitPattern;
10use core::num::{NonZeroU32, NonZeroU64};
11use core::{fmt, hint};
12
13#[derive(Debug, Copy, Clone, Eq, PartialEq)]
15pub enum ReadError {
16 NotEnoughBytes {
18 missing: NonZeroU32,
24 },
25 Misaligned {
27 alignment: u32,
29 },
30}
31
32impl fmt::Display for ReadError {
33 #[inline]
34 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35 match self {
36 Self::NotEnoughBytes { missing } => write!(f, "Need {missing} more bytes"),
37 Self::Misaligned { alignment } => {
38 write!(f, "Bytes are not aligned to {alignment} bytes")
39 }
40 }
41 }
42}
43
44impl core::error::Error for ReadError {}
45
46#[derive(Debug, Clone)]
55pub struct SharedAlignedBufferReader<'a, A>
56where
57 A: Alignment,
58{
59 buffer: &'a SharedAlignedBuffer<A>,
60 position: u32,
62}
63
64impl<'a, A> SharedAlignedBufferReader<'a, A>
65where
66 A: Alignment,
67{
68 #[inline(always)]
69 pub(crate) const fn new(buffer: &'a SharedAlignedBuffer<A>) -> Self {
70 Self {
71 buffer,
72 position: 0,
73 }
74 }
75
76 #[inline(always)]
78 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
79 pub fn position(&self) -> u32 {
80 self.position
81 }
82
83 #[inline(always)]
85 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
86 pub fn remaining(&self) -> &'a [u8] {
87 unsafe { hint::assert_unchecked(self.position <= self.buffer.len()) }
90 let contents: &'a [u8] = self.buffer.as_slice();
91 contents
92 .get(self.position as usize..)
93 .expect("Position is not larger than the length of the buffer; qed")
94 }
95
96 #[inline]
101 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
102 pub fn read_to_alignment<B>(&mut self) -> Result<&'a [u8], ReadError>
103 where
104 B: Alignment,
105 {
106 let misalignment = self.position % B::ALIGN;
107 let padding = if misalignment == 0 {
108 0
109 } else {
110 B::ALIGN - misalignment
111 };
112 self.read_bytes(padding)
113 }
114
115 #[inline]
117 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
118 pub fn read_bytes(&mut self, len: u32) -> Result<&'a [u8], ReadError> {
119 let start = self.advance(u64::from(len))?;
120 let contents: &'a [u8] = self.buffer.as_slice();
121 Ok(contents
122 .get(start as usize..)
123 .and_then(|bytes| bytes.get(..len as usize))
124 .expect("Within the contents as checked above; qed"))
125 }
126
127 #[inline]
129 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
130 pub fn read_bytes_array<const N: usize>(&mut self) -> Result<&'a [u8; N], ReadError> {
131 const {
132 assert!(
133 N <= u32::MAX as usize,
134 "Buffers are never longer than `u32::MAX` bytes"
135 );
136 }
137 let bytes = self.read_bytes(u32::try_from(N).expect("Checked above; qed"))?;
138 Ok(bytes.try_into().expect("Exactly `N` bytes; qed"))
139 }
140
141 #[inline]
147 #[cfg_attr(
149 all(feature = "no-panic", target_pointer_width = "64"),
150 no_panic::no_panic
151 )]
152 pub fn read_buffer<B>(&mut self, len: u32) -> Result<SharedAlignedBuffer<B>, ReadError>
153 where
154 B: Alignment,
155 {
156 self.check_alignment(B::ALIGN)?;
157 let start = self.advance(u64::from(len))?;
158 if len == 0 {
159 return Ok(SharedAlignedBuffer::EMPTY);
160 }
161
162 Ok(SharedAlignedBuffer::from_inner(
163 self.buffer.inner.slice(start, len),
164 ))
165 }
166
167 #[cfg(feature = "io-type")]
174 #[inline]
175 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
176 pub fn read_trivial<T>(&mut self) -> Result<&'a T, ReadError>
177 where
178 T: AnyBitPattern,
179 {
180 self.check_alignment(u32::from(T::ALIGNMENT.get()))?;
181 let bytes = self.read_bytes(T::SIZE)?;
182 Ok(T::from_bytes_exact(bytes).expect("Aligned bytes of the size of `T`; qed"))
183 }
184
185 #[cfg(feature = "io-type")]
187 #[inline]
188 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
189 pub fn read_trivial_array<T, const N: usize>(&mut self) -> Result<&'a [T; N], ReadError>
190 where
191 [T; N]: AnyBitPattern,
192 {
193 self.read_trivial()
194 }
195
196 #[cfg(feature = "io-type")]
198 #[inline]
199 #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
200 pub fn read_trivial_slice<T>(&mut self, count: u32) -> Result<&'a [T], ReadError>
201 where
202 T: AnyBitPattern,
203 {
204 self.check_alignment(u32::from(T::ALIGNMENT.get()))?;
205 let start = self.advance(u64::from(T::SIZE) * u64::from(count))?;
206 let contents: &'a [u8] = self.buffer.as_slice();
207 let (values, _remainder) = contents
208 .get(start as usize..)
209 .and_then(|bytes| T::slice_from_bytes(bytes, count as usize))
210 .expect("Aligned bytes of the size of `count` values of `T`; qed");
211 Ok(values)
212 }
213
214 #[inline(always)]
216 fn check_alignment(&self, alignment: u32) -> Result<(), ReadError> {
217 if self
218 .remaining()
219 .as_ptr()
220 .addr()
221 .is_multiple_of(alignment as usize)
222 {
223 Ok(())
224 } else {
225 Err(ReadError::Misaligned { alignment })
226 }
227 }
228
229 #[inline(always)]
231 fn advance(&mut self, len: u64) -> Result<u32, ReadError> {
232 let remaining = unsafe { self.buffer.len().unchecked_sub(self.position) };
235 if let Some(missing) = NonZeroU64::new(len.saturating_sub(u64::from(remaining))) {
236 return Err(ReadError::NotEnoughBytes {
237 missing: NonZeroU32::try_from(missing).unwrap_or(NonZeroU32::MAX),
238 });
239 }
240 let len = u32::try_from(len).expect("Not larger than the number of remaining bytes; qed");
241
242 let start = self.position;
243 self.position += len;
245 Ok(start)
246 }
247}