Skip to main content

ab_aligned_buffer/
reader.rs

1//! Reading the contents of shared buffers front to back
2
3#[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/// Error of a read with [`SharedAlignedBufferReader`]
14#[derive(Debug, Copy, Clone, Eq, PartialEq)]
15pub enum ReadError {
16    /// The contents end before the read does
17    NotEnoughBytes {
18        /// How many more bytes the read needs.
19        ///
20        /// Counted from the position of the reader, so it is not larger than the number of bytes
21        /// missing for the rest of the data, whose size the reader doesn't know. Saturates at
22        /// `u32::MAX`, a read that needs more can't succeed with any buffer.
23        missing: NonZeroU32,
24    },
25    /// Bytes at the position of the reader are not aligned in memory as the read requires
26    Misaligned {
27        /// Required alignment in bytes
28        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/// Reads the contents of a [`SharedAlignedBuffer`] front to back, see
47/// [`SharedAlignedBuffer::reader()`].
48///
49/// Bytes are borrowed from the buffer for as long as the buffer is borrowed, so any number of them
50/// can be held at once, while [`Self::read_buffer()`] creates buffers that reference a part of the
51/// contents without copying them.
52///
53/// A read that fails leaves the reader unchanged.
54#[derive(Debug, Clone)]
55pub struct SharedAlignedBufferReader<'a, A>
56where
57    A: Alignment,
58{
59    buffer: &'a SharedAlignedBuffer<A>,
60    /// Never larger than the length of the buffer
61    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    /// Number of bytes read so far, including padding
77    #[inline(always)]
78    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
79    pub fn position(&self) -> u32 {
80        self.position
81    }
82
83    /// Bytes that were not read yet
84    #[inline(always)]
85    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
86    pub fn remaining(&self) -> &'a [u8] {
87        // SAFETY: Position is never larger than the length of the buffer, which can't change while
88        // it is borrowed
89        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    /// Read padding up to the next multiple of `B` bytes from the beginning of the contents.
97    ///
98    /// Returns padding bytes, which are empty if the position is already a multiple of `B`, so
99    /// that formats that require zero padding can check them.
100    #[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    /// Read the next `len` bytes
116    #[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    /// Read the next `N` bytes
128    #[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    /// Create a buffer that references the next `len` bytes without copying them.
142    ///
143    /// The bytes must be aligned to `B` in memory, [`Self::read_to_alignment()`] reads padding in
144    /// front of them if necessary. The new buffer keeps the whole allocation alive unless it is
145    /// empty, see [`SharedAlignedBuffer::into_standalone()`].
146    #[inline]
147    // Panics on 32-bit targets before the reference counter would wrap around
148    #[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    /// Read a value of a trivial type.
168    ///
169    /// The bytes must be aligned for `T` in memory, [`Self::read_to_alignment()`] reads padding in
170    /// front of them if necessary. [`Unaligned`] reads values that are not aligned.
171    ///
172    /// [`Unaligned`]: ab_io_type::unaligned::Unaligned
173    #[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    /// Read `N` values of a trivial type, like [`Self::read_trivial()`]
186    #[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    /// Read `count` values of a trivial type, like [`Self::read_trivial()`]
197    #[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    /// Check that bytes at the position of the reader are aligned to `alignment` in memory
215    #[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    /// Advance by `len` bytes, returns the position before advancing
230    #[inline(always)]
231    fn advance(&mut self, len: u64) -> Result<u32, ReadError> {
232        // SAFETY: Position is never larger than the length of the buffer, which can't change while
233        // it is borrowed
234        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        // Within the contents, whose length is a `u32`, as checked above
244        self.position += len;
245        Ok(start)
246    }
247}