Skip to main content

ntex_bytes/buf/
uninit_slice.rs

1use std::ops::{
2    Index, IndexMut, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive,
3};
4use std::{fmt, mem::MaybeUninit, ptr};
5
6/// Uninitialized byte slice.
7///
8/// Returned by `BufMut::chunk_mut()`, the referenced byte slice may be
9/// uninitialized. The wrapper provides safe access without introducing
10/// undefined behavior.
11///
12/// The safety invariants of this wrapper are:
13///
14///  1. Reading from an `UninitSlice` is undefined behavior.
15///  2. Writing uninitialized bytes to an `UninitSlice` is undefined behavior.
16///
17/// The difference between `&mut UninitSlice` and `&mut [MaybeUninit<u8>]` is
18/// that it is possible in safe code to write uninitialized bytes to an
19/// `&mut [MaybeUninit<u8>]`, which this type prohibits.
20#[repr(transparent)]
21pub struct UninitSlice([MaybeUninit<u8>]);
22
23impl UninitSlice {
24    /// Create a `&mut UninitSlice` from a pointer and a length.
25    ///
26    /// # Safety
27    ///
28    /// The caller must ensure that `ptr` references a valid memory region owned
29    /// by the caller representing a byte slice for the duration of `'a`.
30    ///
31    /// # Examples
32    ///
33    /// ```
34    /// use ntex_bytes::buf::UninitSlice;
35    ///
36    /// let bytes = b"hello world".to_vec();
37    /// let ptr = bytes.as_ptr() as *mut _;
38    /// let len = bytes.len();
39    ///
40    /// let slice = unsafe { UninitSlice::from_raw_parts_mut(ptr, len) };
41    /// ```
42    #[inline]
43    pub unsafe fn from_raw_parts_mut<'a>(ptr: *mut u8, len: usize) -> &'a mut UninitSlice {
44        UninitSlice::from_uninit_mut(core::slice::from_raw_parts_mut(ptr.cast(), len))
45    }
46
47    // SAFETY for both: `UninitSlice` is a `repr(transparent)` wrapper of `[MaybeUninit<u8>]`
48    #[inline]
49    fn from_uninit(slice: &[MaybeUninit<u8>]) -> &UninitSlice {
50        unsafe { &*(ptr::from_ref(slice) as *const UninitSlice) }
51    }
52
53    #[inline]
54    fn from_uninit_mut(slice: &mut [MaybeUninit<u8>]) -> &mut UninitSlice {
55        unsafe { &mut *(ptr::from_mut(slice) as *mut UninitSlice) }
56    }
57
58    /// Write a single byte at the specified offset.
59    ///
60    /// # Panics
61    ///
62    /// The function panics if `index` is out of bounds.
63    ///
64    /// # Examples
65    ///
66    /// ```
67    /// use ntex_bytes::buf::UninitSlice;
68    ///
69    /// let mut data = [b'f', b'o', b'o'];
70    /// let slice = unsafe { UninitSlice::from_raw_parts_mut(data.as_mut_ptr(), 3) };
71    ///
72    /// slice.write_byte(0, b'b');
73    ///
74    /// assert_eq!(b"boo", &data[..]);
75    /// ```
76    #[inline]
77    pub fn write_byte(&mut self, index: usize, byte: u8) {
78        assert!(index < self.len());
79
80        unsafe { self[index..].as_mut_ptr().write(byte) }
81    }
82
83    /// Copies bytes  from `src` into `self`.
84    ///
85    /// The length of `src` must be the same as `self`.
86    ///
87    /// # Panics
88    ///
89    /// The function panics if `src` has a different length than `self`.
90    ///
91    /// # Examples
92    ///
93    /// ```
94    /// use ntex_bytes::buf::UninitSlice;
95    ///
96    /// let mut data = [b'f', b'o', b'o'];
97    /// let slice = unsafe { UninitSlice::from_raw_parts_mut(data.as_mut_ptr(), 3) };
98    ///
99    /// slice.copy_from_slice(b"bar");
100    ///
101    /// assert_eq!(b"bar", &data[..]);
102    /// ```
103    #[inline]
104    pub fn copy_from_slice(&mut self, src: &[u8]) {
105        use core::ptr;
106
107        assert_eq!(self.len(), src.len());
108
109        unsafe {
110            ptr::copy_nonoverlapping(src.as_ptr(), self.as_mut_ptr(), self.len());
111        }
112    }
113
114    /// Return a raw pointer to the slice's buffer.
115    ///
116    /// # Safety
117    ///
118    /// The caller **must not** read from the referenced memory and **must not**
119    /// write **uninitialized** bytes to the slice either.
120    ///
121    /// # Examples
122    ///
123    /// ```
124    /// use ntex_bytes::BufMut;
125    ///
126    /// let mut data = [0, 1, 2];
127    /// let mut slice = &mut data[..];
128    /// let ptr = BufMut::chunk_mut(&mut slice).as_mut_ptr();
129    /// ```
130    #[inline]
131    pub fn as_mut_ptr(&mut self) -> *mut u8 {
132        self.0.as_mut_ptr().cast()
133    }
134
135    /// Returns the number of bytes in the slice.
136    ///
137    /// # Examples
138    ///
139    /// ```
140    /// use ntex_bytes::BufMut;
141    ///
142    /// let mut data = [0, 1, 2];
143    /// let mut slice = &mut data[..];
144    /// let len = BufMut::chunk_mut(&mut slice).len();
145    ///
146    /// assert_eq!(len, 3);
147    /// ```
148    #[inline]
149    #[allow(clippy::len_without_is_empty)]
150    pub fn len(&self) -> usize {
151        self.0.len()
152    }
153
154    /// Returns the slice as a mutable slice of [`MaybeUninit<u8>`].
155    ///
156    /// # Safety
157    ///
158    /// The memory may already be initialized, for example when the slice was
159    /// returned by the [`BufMut`](crate::BufMut) implementation for
160    /// `&mut [u8]`. The caller **must not** write uninitialized bytes to the
161    /// returned slice.
162    ///
163    /// # Examples
164    ///
165    /// ```
166    /// use ntex_bytes::BufMut;
167    ///
168    /// let mut data = [0, 1, 2];
169    /// let mut slice = &mut data[..];
170    /// let uninit = unsafe { BufMut::chunk_mut(&mut slice).as_uninit_slice_mut() };
171    /// uninit[0].write(b'a');
172    ///
173    /// assert_eq!(data[0], b'a');
174    /// ```
175    #[inline]
176    pub unsafe fn as_uninit_slice_mut(&mut self) -> &mut [MaybeUninit<u8>] {
177        &mut self.0
178    }
179}
180
181impl fmt::Debug for UninitSlice {
182    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
183        fmt.debug_struct("UninitSlice[...]").finish()
184    }
185}
186
187macro_rules! impl_index {
188    ($($t:ty),*) => {
189        $(
190            impl Index<$t> for UninitSlice {
191                type Output = UninitSlice;
192
193                #[inline]
194                fn index(&self, index: $t) -> &UninitSlice {
195                    UninitSlice::from_uninit(&self.0[index])
196                }
197            }
198
199            impl IndexMut<$t> for UninitSlice {
200                #[inline]
201                fn index_mut(&mut self, index: $t) -> &mut UninitSlice {
202                    UninitSlice::from_uninit_mut(&mut self.0[index])
203                }
204            }
205        )*
206    };
207}
208
209impl_index!(
210    Range<usize>,
211    RangeFrom<usize>,
212    RangeFull,
213    RangeInclusive<usize>,
214    RangeTo<usize>,
215    RangeToInclusive<usize>
216);
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221
222    /// STATEMENT: `UninitSlice` supports standard range indexing and writes through uninitialized-slice views.
223    ///
224    /// HOW:
225    /// - Wrap an eight-byte array, check six range lengths, and write `a` and `b` through `as_uninit_slice_mut`.
226    /// - Verify the underlying array begins with `ab`.
227    #[test]
228    fn index_and_uninit_access() {
229        let mut data = [0u8; 8];
230        let slice = unsafe { UninitSlice::from_raw_parts_mut(data.as_mut_ptr(), data.len()) };
231
232        assert_eq!(slice[..].len(), 8);
233        assert_eq!(slice[2..].len(), 6);
234        assert_eq!(slice[..3].len(), 3);
235        assert_eq!(slice[..=3].len(), 4);
236        assert_eq!(slice[1..3].len(), 2);
237        assert_eq!(slice[1..=3].len(), 3);
238
239        unsafe {
240            slice.as_uninit_slice_mut()[0].write(b'a');
241            slice.as_uninit_slice_mut()[1].write(b'b');
242        }
243        assert_eq!(&data[..2], b"ab");
244    }
245}