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
181/// Deprecated, use [`UninitSlice::as_uninit_slice_mut`] instead.
182///
183/// This impl is unsound. The memory may already be initialized, for example
184/// when the slice was returned by the [`BufMut`](crate::BufMut) implementation
185/// for `&mut [u8]`, and safe code can write uninitialized bytes to the
186/// returned slice. It will be removed in the next major release.
187///
188/// Rust does not allow `#[deprecated]` on trait impls, so using this impl
189/// does not emit a warning.
190impl AsMut<[MaybeUninit<u8>]> for UninitSlice {
191    fn as_mut(&mut self) -> &mut [MaybeUninit<u8>] {
192        &mut self.0
193    }
194}
195
196impl fmt::Debug for UninitSlice {
197    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
198        fmt.debug_struct("UninitSlice[...]").finish()
199    }
200}
201
202macro_rules! impl_index {
203    ($($t:ty),*) => {
204        $(
205            impl Index<$t> for UninitSlice {
206                type Output = UninitSlice;
207
208                #[inline]
209                fn index(&self, index: $t) -> &UninitSlice {
210                    UninitSlice::from_uninit(&self.0[index])
211                }
212            }
213
214            impl IndexMut<$t> for UninitSlice {
215                #[inline]
216                fn index_mut(&mut self, index: $t) -> &mut UninitSlice {
217                    UninitSlice::from_uninit_mut(&mut self.0[index])
218                }
219            }
220        )*
221    };
222}
223
224impl_index!(
225    Range<usize>,
226    RangeFrom<usize>,
227    RangeFull,
228    RangeInclusive<usize>,
229    RangeTo<usize>,
230    RangeToInclusive<usize>
231);
232
233#[cfg(test)]
234mod tests {
235    use super::*;
236
237    #[test]
238    fn index_and_uninit_access() {
239        let mut data = [0u8; 8];
240        let slice = unsafe { UninitSlice::from_raw_parts_mut(data.as_mut_ptr(), data.len()) };
241
242        assert_eq!(slice[..].len(), 8);
243        assert_eq!(slice[2..].len(), 6);
244        assert_eq!(slice[..3].len(), 3);
245        assert_eq!(slice[..=3].len(), 4);
246        assert_eq!(slice[1..3].len(), 2);
247        assert_eq!(slice[1..=3].len(), 3);
248
249        unsafe { slice.as_uninit_slice_mut()[0].write(b'a') };
250        AsMut::<[MaybeUninit<u8>]>::as_mut(slice)[1].write(b'b');
251        assert_eq!(&data[..2], b"ab");
252    }
253}