Skip to main content

ntex_bytes/
write.rs

1use std::{fmt, io, mem::MaybeUninit, ptr, slice};
2
3use crate::BytesMut;
4
5/// Appends bytes to the spare capacity of a [`BytesMut`].
6///
7/// Created by [`BytesMut::spare_writer`]. Bytes are written into the spare
8/// capacity, which is not initialized first, and the writer reserves more
9/// capacity when it is full, at least doubling the buffer capacity. The
10/// buffer length is updated when the writer is dropped. If the writer is
11/// leaked, the buffer may not include all of the written bytes.
12pub struct SpareWriter<'a> {
13    buf: &'a mut BytesMut,
14    /// Buffer length when the writer was created.
15    base: usize,
16    /// Position of the first written byte, at `base` in the buffer.
17    ptr: *mut u8,
18    /// Number of bytes that fit at `ptr`.
19    cap: usize,
20    /// Number of written bytes.
21    len: usize,
22}
23
24// SAFETY: The writer exclusively borrows the buffer, `ptr` points into its
25// spare capacity.
26unsafe impl Send for SpareWriter<'_> {}
27// SAFETY: A shared reference only reads the written length.
28unsafe impl Sync for SpareWriter<'_> {}
29
30impl<'a> SpareWriter<'a> {
31    #[inline]
32    pub(crate) fn new(buf: &'a mut BytesMut, additional: usize) -> Self {
33        buf.reserve(additional);
34        let base = buf.len();
35        let spare = buf.storage.spare_mut();
36        let (ptr, cap) = (spare.as_mut_ptr(), spare.len());
37        SpareWriter {
38            buf,
39            base,
40            ptr,
41            cap,
42            len: 0,
43        }
44    }
45}
46
47// Serializers call these per value through a writer wrapper in another crate,
48// a missed inline turns each call into a function call.
49#[allow(clippy::inline_always)]
50impl SpareWriter<'_> {
51    /// Appends a byte.
52    #[inline(always)]
53    pub fn push(&mut self, byte: u8) {
54        if self.len == self.cap {
55            self.grow(1);
56        }
57        // SAFETY: `len < cap`, the byte is in the spare capacity of the buffer
58        unsafe { self.ptr.add(self.len).write(byte) };
59        self.len += 1;
60    }
61
62    /// Appends a byte slice.
63    #[inline(always)]
64    pub fn extend_from_slice(&mut self, src: &[u8]) {
65        if src.len() > self.cap - self.len {
66            self.grow(src.len());
67        }
68        // SAFETY: `src` fits in the spare capacity after the written bytes
69        unsafe { ptr::copy_nonoverlapping(src.as_ptr(), self.ptr.add(self.len), src.len()) };
70        self.len += src.len();
71    }
72
73    /// Returns the number of written bytes.
74    #[inline]
75    pub fn len(&self) -> usize {
76        self.len
77    }
78
79    /// Returns `true` if no bytes have been written.
80    #[inline]
81    pub fn is_empty(&self) -> bool {
82        self.len == 0
83    }
84
85    /// Reserves capacity for at least `additional` more bytes after the
86    /// written bytes.
87    ///
88    /// # Panics
89    ///
90    /// Panics if the new capacity exceeds `u32::MAX` minus the buffer
91    /// header size, just under 4 GiB.
92    #[inline(always)]
93    pub fn reserve(&mut self, additional: usize) {
94        if additional > self.cap - self.len {
95            self.grow(additional);
96        }
97    }
98
99    /// Returns the spare capacity after the written bytes.
100    ///
101    /// Bytes written into it are added to the writer with
102    /// [`advance`](Self::advance).
103    ///
104    /// # Examples
105    ///
106    /// ```
107    /// use ntex_bytes::BytesMut;
108    ///
109    /// let mut buf = BytesMut::new();
110    /// let mut w = buf.spare_writer(0);
111    /// w.reserve(2);
112    /// let spare = w.spare_capacity_mut();
113    /// spare[0].write(b'o');
114    /// spare[1].write(b'k');
115    /// // SAFETY: The first two bytes of the spare capacity are initialized
116    /// unsafe { w.advance(2) };
117    /// drop(w);
118    ///
119    /// assert_eq!(&buf[..], b"ok");
120    /// ```
121    #[inline(always)]
122    pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<u8>] {
123        // SAFETY: `cap - len` bytes after the written bytes are spare capacity
124        // of the buffer, exclusively borrowed by the writer
125        unsafe { slice::from_raw_parts_mut(self.ptr.add(self.len).cast(), self.cap - self.len) }
126    }
127
128    /// Adds `cnt` bytes of the spare capacity to the written bytes.
129    ///
130    /// # Safety
131    ///
132    /// The first `cnt` bytes of [`spare_capacity_mut`](Self::spare_capacity_mut)
133    /// must be initialized.
134    #[inline(always)]
135    pub unsafe fn advance(&mut self, cnt: usize) {
136        debug_assert!(cnt <= self.cap - self.len);
137        self.len += cnt;
138    }
139
140    #[inline]
141    fn grow(&mut self, additional: usize) {
142        let (ptr, spare) = grow_spare(self.buf, self.base + self.len, additional);
143        // SAFETY: The written bytes are the last `len` bytes of the buffer, right
144        // before its spare capacity
145        self.ptr = unsafe { ptr.sub(self.len) };
146        self.cap = self.len + spare;
147    }
148}
149
150/// Sets the length of `buf` to `len`, reserves `additional` bytes and returns
151/// the spare capacity.
152///
153/// Takes the fields instead of the writer, so the writer can stay in registers.
154#[cold]
155#[inline(never)]
156fn grow_spare(buf: &mut BytesMut, len: usize, additional: usize) -> (*mut u8, usize) {
157    // SAFETY: The writer initialized the bytes up to `len`. Setting the length
158    // again on drop, if `reserve` panics, sets the same value.
159    unsafe { buf.set_len(len) };
160    buf.reserve(additional);
161    let spare = buf.storage.spare_mut();
162    (spare.as_mut_ptr(), spare.len())
163}
164
165impl Drop for SpareWriter<'_> {
166    #[inline]
167    fn drop(&mut self) {
168        // SAFETY: The writer initialized `len` bytes from `base`
169        unsafe { self.buf.set_len(self.base + self.len) };
170    }
171}
172
173#[allow(clippy::inline_always)]
174impl io::Write for SpareWriter<'_> {
175    #[inline(always)]
176    fn write(&mut self, src: &[u8]) -> Result<usize, io::Error> {
177        self.extend_from_slice(src);
178        Ok(src.len())
179    }
180
181    #[inline]
182    fn flush(&mut self) -> Result<(), io::Error> {
183        Ok(())
184    }
185}
186
187impl fmt::Debug for SpareWriter<'_> {
188    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189        f.debug_struct("SpareWriter")
190            .field("len", &self.len)
191            .finish_non_exhaustive()
192    }
193}
194
195#[cfg(test)]
196mod tests {
197    use super::*;
198
199    /// STATEMENT: A `SpareWriter` keeps every written byte when it grows the buffer,
200    /// including a buffer shared with split off `Bytes`.
201    ///
202    /// HOW:
203    /// - Split a 4-byte head off a buffer, so the storage is shared, and start a writer with no reserve.
204    /// - Write 10,000 bytes through `push`, `extend_from_slice` and `io::Write`.
205    /// - Check the writer length, the buffer contents after the drop, and the untouched head.
206    #[test]
207    fn spare_writer_grows() {
208        let mut buf = BytesMut::with_capacity(8);
209        buf.extend_from_slice(b"headtail");
210        let head = buf.split_to(4);
211
212        let mut expected = b"tail".to_vec();
213        let mut w = buf.spare_writer(0);
214        for i in 0..2000_u32 {
215            let b = (i % 251) as u8;
216            w.push(b);
217            w.extend_from_slice(&[b, b]);
218            io::Write::write_all(&mut w, &[b, b]).unwrap();
219            expected.extend_from_slice(&[b; 5]);
220        }
221        assert_eq!(w.len(), 10_000);
222        drop(w);
223
224        assert_eq!(&buf[..], &expected[..]);
225        assert_eq!(&head[..], b"head");
226    }
227
228    /// STATEMENT: A `SpareWriter` adds nothing to the buffer when it writes nothing or
229    /// is leaked before it grows.
230    ///
231    /// HOW:
232    /// - Drop a writer with no writes and check the length and `is_empty`.
233    /// - Leak a writer after pushing bytes into reserved capacity and check the length is unchanged.
234    #[test]
235    fn spare_writer_uncommitted() {
236        let mut buf = BytesMut::copy_from_slice(b"abc");
237        let w = buf.spare_writer(16);
238        assert!(w.is_empty());
239        drop(w);
240        assert_eq!(&buf[..], b"abc");
241
242        let mut w = buf.spare_writer(16);
243        w.extend_from_slice(b"defg");
244        std::mem::forget(w);
245        assert_eq!(&buf[..], b"abc");
246    }
247
248    /// STATEMENT: Bytes initialized in `SpareWriter::spare_capacity_mut` are added to the
249    /// buffer by `advance`, and `reserve` keeps the written bytes when it grows the buffer.
250    ///
251    /// HOW:
252    /// - Start a writer after existing bytes, write one byte, then `reserve` more than the
253    ///   spare capacity and check the spare slice is at least that long.
254    /// - Fill part of the spare slice, `advance` over it, append with `push`, and check the
255    ///   writer length and the buffer contents after the drop.
256    #[test]
257    fn spare_writer_advance() {
258        let mut buf = BytesMut::copy_from_slice(b"abc");
259        let mut w = buf.spare_writer(0);
260        w.push(b'd');
261        let need = w.spare_capacity_mut().len() + 100;
262        w.reserve(need);
263        let spare = w.spare_capacity_mut();
264        assert!(spare.len() >= need);
265        for (i, b) in spare[..need].iter_mut().enumerate() {
266            b.write((i % 251) as u8);
267        }
268        // SAFETY: The first `need` bytes of the spare capacity are initialized
269        unsafe { w.advance(need) };
270        w.push(b'z');
271        assert_eq!(w.len(), need + 2);
272        drop(w);
273
274        let mut expected = b"abcd".to_vec();
275        expected.extend((0..need).map(|i| (i % 251) as u8));
276        expected.push(b'z');
277        assert_eq!(&buf[..], &expected[..]);
278    }
279}