Skip to main content

layline_core/
buffer.rs

1//! Output buffers for encoding.
2
3/// A byte buffer that encode appends to and patches.
4///
5/// Encode fills in computed values and reads checksum ranges through
6/// [`written_mut`](Self::written_mut). Implemented for [`Vec<u8>`](alloc::vec::Vec) and [`Fixed`].
7///
8/// ```
9/// use layline_core::{Buffer, Fixed};
10///
11/// let mut room = [0u8; 4];
12/// let mut out = Fixed::new(&mut room);
13/// out.push(&[1, 2, 3]).unwrap();
14/// out.written_mut()[0] = 9;
15/// assert_eq!(out.written(), &[9, 2, 3]);
16/// assert!(out.push(&[4, 5]).is_err());
17/// ```
18pub trait Buffer {
19    /// Append `bytes`.
20    ///
21    /// # Errors
22    ///
23    /// [`Overflow`], leaving the buffer unchanged.
24    fn push(&mut self, bytes: &[u8]) -> Result<(), Overflow>;
25
26    /// The bytes written so far.
27    fn written(&self) -> &[u8];
28
29    /// The bytes written so far, mutably.
30    fn written_mut(&mut self) -> &mut [u8];
31
32    /// Truncate to `to` bytes. Does nothing if `to` is at or past the end.
33    fn rewind(&mut self, to: usize);
34
35    /// The number of bytes written.
36    fn len(&self) -> usize {
37        self.written().len()
38    }
39
40    /// Whether no bytes are written.
41    fn is_empty(&self) -> bool {
42        self.len() == 0
43    }
44
45    /// Append `n` zero bytes.
46    ///
47    /// # Errors
48    ///
49    /// [`Overflow`] if there is no room.
50    fn pad(&mut self, n: usize) -> Result<(), Overflow> {
51        const ZEROS: [u8; 64] = [0; 64];
52        let mut left = n;
53        while left > 0 {
54            let take = if left < ZEROS.len() { left } else { ZEROS.len() };
55            self.push(&ZEROS[..take])?;
56            left -= take;
57        }
58        Ok(())
59    }
60}
61
62/// Run one encode into a new vector.
63#[cfg(feature = "alloc")]
64pub(crate) fn to_vec(
65    encode: impl FnOnce(&mut alloc::vec::Vec<u8>) -> Result<(), Overflow>,
66) -> alloc::vec::Vec<u8> {
67    let mut out = alloc::vec::Vec::new();
68    encode(&mut out).expect("a vector grows to fit");
69    out
70}
71
72/// A buffer ran out of room during encode.
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
74pub struct Overflow;
75
76impl core::fmt::Display for Overflow {
77    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
78        f.write_str("the buffer has no room for the encoded bytes")
79    }
80}
81
82impl core::error::Error for Overflow {}
83
84/// A [`Buffer`] over a caller's byte slice, for encoding without an allocator.
85#[derive(Debug)]
86pub struct Fixed<'a> {
87    room: &'a mut [u8],
88    at: usize,
89}
90
91impl<'a> Fixed<'a> {
92    /// An empty buffer over `room`.
93    #[must_use]
94    pub const fn new(room: &'a mut [u8]) -> Self {
95        Self { room, at: 0 }
96    }
97
98    /// The bytes written, borrowed for the slice's lifetime.
99    #[must_use]
100    pub fn into_written(self) -> &'a [u8] {
101        &self.room[..self.at]
102    }
103}
104
105impl Buffer for Fixed<'_> {
106    fn push(&mut self, bytes: &[u8]) -> Result<(), Overflow> {
107        let end = self.at.checked_add(bytes.len()).ok_or(Overflow)?;
108        if end > self.room.len() {
109            return Err(Overflow);
110        }
111        self.room[self.at..end].copy_from_slice(bytes);
112        self.at = end;
113        Ok(())
114    }
115
116    fn written(&self) -> &[u8] {
117        &self.room[..self.at]
118    }
119
120    fn written_mut(&mut self) -> &mut [u8] {
121        &mut self.room[..self.at]
122    }
123
124    fn rewind(&mut self, to: usize) {
125        self.at = self.at.min(to);
126    }
127
128    fn len(&self) -> usize {
129        self.at
130    }
131}
132
133impl<T: Buffer + ?Sized> Buffer for &mut T {
134    fn push(&mut self, bytes: &[u8]) -> Result<(), Overflow> {
135        T::push(self, bytes)
136    }
137
138    fn written(&self) -> &[u8] {
139        T::written(self)
140    }
141
142    fn written_mut(&mut self) -> &mut [u8] {
143        T::written_mut(self)
144    }
145
146    fn rewind(&mut self, to: usize) {
147        T::rewind(self, to);
148    }
149
150    fn len(&self) -> usize {
151        T::len(self)
152    }
153}
154
155#[cfg(feature = "alloc")]
156impl Buffer for alloc::vec::Vec<u8> {
157    fn push(&mut self, bytes: &[u8]) -> Result<(), Overflow> {
158        self.extend_from_slice(bytes);
159        Ok(())
160    }
161
162    fn written(&self) -> &[u8] {
163        self
164    }
165
166    fn written_mut(&mut self) -> &mut [u8] {
167        self
168    }
169
170    fn rewind(&mut self, to: usize) {
171        self.truncate(to);
172    }
173
174    fn len(&self) -> usize {
175        alloc::vec::Vec::len(self)
176    }
177}
178
179#[cfg(test)]
180mod tests {
181    use super::*;
182
183    #[test]
184    fn a_fixed_buffer_fills_to_its_last_byte_and_refuses_the_next() {
185        let mut room = [0u8; 3];
186        let mut out = Fixed::new(&mut room);
187        assert_eq!(out.push(&[1, 2]), Ok(()));
188        assert_eq!(out.push(&[3]), Ok(()));
189        assert_eq!(out.push(&[4]), Err(Overflow));
190        assert_eq!(out.len(), 3);
191        assert_eq!(out.into_written(), &[1, 2, 3]);
192    }
193
194    #[test]
195    fn a_refused_push_writes_nothing() {
196        let mut room = [0u8; 4];
197        let mut out = Fixed::new(&mut room);
198        out.push(&[1, 2]).unwrap();
199        assert_eq!(out.push(&[3, 4, 5]), Err(Overflow));
200        assert_eq!(out.written(), &[1, 2]);
201    }
202
203    #[test]
204    fn a_rewind_drops_the_bytes_past_it_and_the_next_push_lands_there() {
205        let mut room = [0u8; 8];
206        let mut out = Fixed::new(&mut room);
207        out.push(&[1, 2, 3, 4]).unwrap();
208        out.rewind(2);
209        out.push(&[9]).unwrap();
210        assert_eq!(out.written(), &[1, 2, 9]);
211    }
212
213    #[test]
214    fn a_rewind_past_the_end_drops_nothing() {
215        let mut room = [0xEEu8; 8];
216        let mut out = Fixed::new(&mut room);
217        out.push(&[1, 2]).unwrap();
218        out.rewind(5);
219        assert_eq!(out.written(), &[1, 2]);
220    }
221
222    #[test]
223    fn a_pad_longer_than_the_zero_run_still_writes_zeros() {
224        let mut room = [0xFFu8; 200];
225        let mut out = Fixed::new(&mut room);
226        out.pad(130).unwrap();
227        assert_eq!(out.len(), 130);
228        assert!(out.written().iter().all(|b| *b == 0));
229    }
230
231    #[test]
232    fn a_pad_past_the_end_is_refused() {
233        let mut room = [0u8; 4];
234        let mut out = Fixed::new(&mut room);
235        assert_eq!(out.pad(5), Err(Overflow));
236    }
237}