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 let maybe_init: &mut [MaybeUninit<u8>] =
45 core::slice::from_raw_parts_mut(ptr.cast(), len);
46 &mut *(ptr::from_mut::<[MaybeUninit<u8>]>(maybe_init) as *mut UninitSlice)
47 }
48
49 /// Write a single byte at the specified offset.
50 ///
51 /// # Panics
52 ///
53 /// The function panics if `index` is out of bounds.
54 ///
55 /// # Examples
56 ///
57 /// ```
58 /// use ntex_bytes::buf::UninitSlice;
59 ///
60 /// let mut data = [b'f', b'o', b'o'];
61 /// let slice = unsafe { UninitSlice::from_raw_parts_mut(data.as_mut_ptr(), 3) };
62 ///
63 /// slice.write_byte(0, b'b');
64 ///
65 /// assert_eq!(b"boo", &data[..]);
66 /// ```
67 #[inline]
68 pub fn write_byte(&mut self, index: usize, byte: u8) {
69 assert!(index < self.len());
70
71 unsafe { self[index..].as_mut_ptr().write(byte) }
72 }
73
74 /// Copies bytes from `src` into `self`.
75 ///
76 /// The length of `src` must be the same as `self`.
77 ///
78 /// # Panics
79 ///
80 /// The function panics if `src` has a different length than `self`.
81 ///
82 /// # Examples
83 ///
84 /// ```
85 /// use ntex_bytes::buf::UninitSlice;
86 ///
87 /// let mut data = [b'f', b'o', b'o'];
88 /// let slice = unsafe { UninitSlice::from_raw_parts_mut(data.as_mut_ptr(), 3) };
89 ///
90 /// slice.copy_from_slice(b"bar");
91 ///
92 /// assert_eq!(b"bar", &data[..]);
93 /// ```
94 #[inline]
95 pub fn copy_from_slice(&mut self, src: &[u8]) {
96 use core::ptr;
97
98 assert_eq!(self.len(), src.len());
99
100 unsafe {
101 ptr::copy_nonoverlapping(src.as_ptr(), self.as_mut_ptr(), self.len());
102 }
103 }
104
105 /// Return a raw pointer to the slice's buffer.
106 ///
107 /// // Safety
108 ///
109 /// The caller **must not** read from the referenced memory and **must not**
110 /// write **uninitialized** bytes to the slice either.
111 ///
112 /// # Examples
113 ///
114 /// ```
115 /// use ntex_bytes::BufMut;
116 ///
117 /// let mut data = [0, 1, 2];
118 /// let mut slice = &mut data[..];
119 /// let ptr = BufMut::chunk_mut(&mut slice).as_mut_ptr();
120 /// ```
121 #[inline]
122 pub fn as_mut_ptr(&mut self) -> *mut u8 {
123 self.0.as_mut_ptr().cast()
124 }
125
126 /// Returns the number of bytes in the slice.
127 ///
128 /// # Examples
129 ///
130 /// ```
131 /// use ntex_bytes::BufMut;
132 ///
133 /// let mut data = [0, 1, 2];
134 /// let mut slice = &mut data[..];
135 /// let len = BufMut::chunk_mut(&mut slice).len();
136 ///
137 /// assert_eq!(len, 3);
138 /// ```
139 #[inline]
140 #[allow(clippy::len_without_is_empty)]
141 pub fn len(&self) -> usize {
142 self.0.len()
143 }
144}
145
146impl AsMut<[MaybeUninit<u8>]> for UninitSlice {
147 fn as_mut(&mut self) -> &mut [MaybeUninit<u8>] {
148 &mut self.0
149 }
150}
151
152impl fmt::Debug for UninitSlice {
153 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
154 fmt.debug_struct("UninitSlice[...]").finish()
155 }
156}
157
158macro_rules! impl_index {
159 ($($t:ty),*) => {
160 $(
161 impl Index<$t> for UninitSlice {
162 type Output = UninitSlice;
163
164 #[inline]
165 fn index(&self, index: $t) -> &UninitSlice {
166 let maybe_uninit: &[MaybeUninit<u8>] = &self.0[index];
167 unsafe { &*(ptr::from_ref::<[MaybeUninit<u8>]>(maybe_uninit) as *const UninitSlice) }
168 }
169 }
170
171 impl IndexMut<$t> for UninitSlice {
172 #[inline]
173 fn index_mut(&mut self, index: $t) -> &mut UninitSlice {
174 let maybe_uninit: &mut [MaybeUninit<u8>] = &mut self.0[index];
175 unsafe { &mut *(ptr::from_mut::<[MaybeUninit<u8>]>(maybe_uninit) as *mut UninitSlice) }
176 }
177 }
178 )*
179 };
180}
181
182impl_index!(
183 Range<usize>,
184 RangeFrom<usize>,
185 RangeFull,
186 RangeInclusive<usize>,
187 RangeTo<usize>,
188 RangeToInclusive<usize>
189);