inout/reserved.rs
1use crate::{InOutBuf, errors::OutIsTooSmallError};
2use core::{marker::PhantomData, slice};
3
4#[cfg(feature = "block-padding")]
5use {
6 crate::{InOut, errors::PadError},
7 block_padding::Padding,
8 hybrid_array::{Array, ArraySize},
9};
10
11/// Custom slice type which references one immutable (input) slice and one
12/// mutable (output) slice. Input and output slices are either the same or
13/// do not overlap. Length of the output slice is always equal or bigger than
14/// length of the input slice.
15pub struct InOutBufReserved<'inp, 'out, T> {
16 in_ptr: *const T,
17 out_ptr: *mut T,
18 in_len: usize,
19 out_len: usize,
20 _pd: PhantomData<(&'inp T, &'out mut T)>,
21}
22
23impl<'a, T> InOutBufReserved<'a, 'a, T> {
24 /// Crate [`InOutBufReserved`] from a single mutable slice.
25 ///
26 /// # Errors
27 /// If `out` is too small.
28 pub fn from_mut_slice(buf: &'a mut [T], msg_len: usize) -> Result<Self, OutIsTooSmallError> {
29 if msg_len > buf.len() {
30 return Err(OutIsTooSmallError);
31 }
32 let p = buf.as_mut_ptr();
33 let out_len = buf.len();
34 Ok(Self {
35 in_ptr: p,
36 out_ptr: p,
37 in_len: msg_len,
38 out_len,
39 _pd: PhantomData,
40 })
41 }
42}
43
44impl<T> InOutBufReserved<'_, '_, T> {
45 /// Create [`InOutBufReserved`] from raw input and output pointers.
46 ///
47 /// # Safety
48 /// Behavior is undefined if any of the following conditions are violated:
49 /// - `in_ptr` must point to a properly initialized value of type `T` and
50 /// must be valid for reads for `in_len * mem::size_of::<T>()` many bytes.
51 /// - `out_ptr` must point to a properly initialized value of type `T` and
52 /// must be valid for both reads and writes for `out_len * mem::size_of::<T>()`
53 /// many bytes.
54 /// - `in_ptr` and `out_ptr` must be either equal or non-overlapping.
55 /// - `in_len` must be less than or equal to `out_len` (i.e. `in_len <= out_len`).
56 /// - If `in_ptr` and `out_ptr` are equal, then the memory referenced by
57 /// them must not be accessed through any other pointer (not derived from
58 /// the return value) for the duration of lifetime 'a. Both read and write
59 /// accesses are forbidden.
60 /// - If `in_ptr` and `out_ptr` are not equal, then the memory referenced by
61 /// `out_ptr` must not be accessed through any other pointer (not derived from
62 /// the return value) for the duration of lifetime 'a. Both read and write
63 /// accesses are forbidden. The memory referenced by `in_ptr` must not be
64 /// mutated for the duration of lifetime `'a`, except inside an `UnsafeCell`.
65 /// - The total size `in_len * mem::size_of::<T>()` and
66 /// `out_len * mem::size_of::<T>()` must be no larger than `isize::MAX`.
67 #[inline(always)]
68 pub unsafe fn from_raw(
69 in_ptr: *const T,
70 in_len: usize,
71 out_ptr: *mut T,
72 out_len: usize,
73 ) -> Self {
74 Self {
75 in_ptr,
76 out_ptr,
77 in_len,
78 out_len,
79 _pd: PhantomData,
80 }
81 }
82
83 /// Get raw input and output pointers.
84 #[inline(always)]
85 #[must_use]
86 pub fn into_raw(self) -> (*const T, *mut T) {
87 (self.in_ptr, self.out_ptr)
88 }
89
90 /// Get input buffer length.
91 #[inline(always)]
92 #[must_use]
93 pub fn get_in_len(&self) -> usize {
94 self.in_len
95 }
96
97 /// Get output buffer length.
98 #[inline(always)]
99 #[must_use]
100 pub fn get_out_len(&self) -> usize {
101 self.out_len
102 }
103
104 /// Split buffer into `InOutBuf` with input length and mutable slice pointing to
105 /// the remaining reserved suffix.
106 pub fn split_reserved(&mut self) -> (InOutBuf<'_, '_, T>, &mut [T]) {
107 // This never underflows because the type ensures that `out_len` is
108 // bigger or equal to `in_len`.
109 let tail_len = self.out_len - self.in_len;
110 unsafe {
111 let body = InOutBuf::from_raw(self.in_ptr, self.out_ptr, self.in_len);
112 let tail_ptr = self.out_ptr.add(self.in_len);
113 let tail = slice::from_raw_parts_mut(tail_ptr, tail_len);
114 (body, tail)
115 }
116 }
117}
118
119impl<'inp, 'out, T> InOutBufReserved<'inp, 'out, T> {
120 /// Crate [`InOutBufReserved`] from two separate slices.
121 ///
122 /// # Errors
123 /// If `out` is too small.
124 pub fn from_slices(
125 in_buf: &'inp [T],
126 out_buf: &'out mut [T],
127 ) -> Result<Self, OutIsTooSmallError> {
128 if in_buf.len() > out_buf.len() {
129 return Err(OutIsTooSmallError);
130 }
131 Ok(Self {
132 in_ptr: in_buf.as_ptr(),
133 out_ptr: out_buf.as_mut_ptr(),
134 in_len: in_buf.len(),
135 out_len: out_buf.len(),
136 _pd: PhantomData,
137 })
138 }
139
140 /// Get input slice.
141 #[inline(always)]
142 #[must_use]
143 pub fn get_in(&self) -> &[T] {
144 unsafe { slice::from_raw_parts(self.in_ptr, self.in_len) }
145 }
146
147 /// Get output slice.
148 #[inline(always)]
149 pub fn get_out(&mut self) -> &mut [T] {
150 unsafe { slice::from_raw_parts_mut(self.out_ptr, self.out_len) }
151 }
152
153 /// Consume `self` and get output slice with lifetime `'out`.
154 #[inline(always)]
155 #[must_use]
156 pub fn into_out(self) -> &'out mut [T] {
157 unsafe { slice::from_raw_parts_mut(self.out_ptr, self.out_len) }
158 }
159}
160
161#[cfg(feature = "block-padding")]
162impl<'inp, 'out> InOutBufReserved<'inp, 'out, u8> {
163 /// Transform buffer into [`PaddedInOutBuf`] using padding algorithm `P`.
164 ///
165 /// # Errors
166 /// If the padding is invalid
167 #[inline(always)]
168 pub fn into_padded_blocks<P, BS>(self) -> Result<PaddedInOutBuf<'inp, 'out, BS>, PadError>
169 where
170 P: Padding,
171 BS: ArraySize,
172 {
173 use block_padding::PaddedData;
174 let out_blocks_len = self.out_len / BS::USIZE;
175
176 let (blocks, tail_block) = match P::pad_detached(self.get_in()) {
177 PaddedData::Pad { blocks, tail_block } => {
178 // If tail block is present, the output buffer must contain
179 // at least `blocks.len() + 1` full blocks
180 if out_blocks_len <= blocks.len() {
181 return Err(PadError);
182 }
183 (blocks, Some(tail_block))
184 }
185 PaddedData::NoPad { blocks } => {
186 // If tail block is not present, the output buffer must contain
187 // at least `blocks.len()` full blocks
188 if out_blocks_len < blocks.len() {
189 return Err(PadError);
190 }
191 (blocks, None)
192 }
193 PaddedData::Error => return Err(PadError),
194 };
195
196 // These invariants must hold for all valid padding implementations.
197 if blocks.as_ptr().cast() != self.in_ptr {
198 return Err(PadError);
199 }
200 if blocks.len() != self.in_len / BS::USIZE {
201 return Err(PadError);
202 }
203
204 Ok(PaddedInOutBuf {
205 in_ptr: self.in_ptr.cast(),
206 out_ptr: self.out_ptr.cast(),
207 blocks_len: blocks.len(),
208 tail_block,
209 _pd: PhantomData,
210 })
211 }
212}
213
214/// Variant of [`InOutBuf`] with optional padded tail block.
215#[cfg(feature = "block-padding")]
216pub struct PaddedInOutBuf<'inp, 'out, BS: ArraySize> {
217 /// Pointer to the input blocks.
218 in_ptr: *const Array<u8, BS>,
219 /// Pointer to the output blocks (including tail block if present).
220 out_ptr: *mut Array<u8, BS>,
221 /// Number of full blocks (i.e. excluding the tail block if present).
222 blocks_len: usize,
223 /// Padded input tail.
224 tail_block: Option<Array<u8, BS>>,
225 _pd: PhantomData<(&'inp u8, &'out mut u8)>,
226}
227
228#[cfg(feature = "block-padding")]
229impl<'out, BS: ArraySize> PaddedInOutBuf<'_, 'out, BS> {
230 /// Get full blocks.
231 #[inline(always)]
232 pub fn get_blocks(&mut self) -> InOutBuf<'_, '_, Array<u8, BS>> {
233 unsafe { InOutBuf::from_raw(self.in_ptr, self.out_ptr, self.blocks_len) }
234 }
235
236 /// Get padded tail block.
237 ///
238 /// Most padding implementations always return `Some`.
239 #[inline(always)]
240 pub fn get_tail_block(&mut self) -> Option<InOut<'_, '_, Array<u8, BS>>> {
241 // SAFETY: if `tail` is `Some`, then `out_ptr` points to a buffer with length equal
242 // to at least `blocks_len + 1` blocks, so it satisfies the safety conditions
243 // required by `InOut::from_raw`.
244 self.tail_block.as_ref().map(|in_block| unsafe {
245 let tail_out_ptr = self.out_ptr.add(self.blocks_len);
246 InOut::from_raw(in_block, tail_out_ptr)
247 })
248 }
249
250 /// Convert buffer into output slice.
251 #[inline(always)]
252 pub fn into_out(self) -> &'out [u8] {
253 let mut bytes_len = BS::USIZE * self.blocks_len;
254 // If tail is present, add its length to the resulting buffer length.
255 if self.tail_block.is_some() {
256 bytes_len += BS::USIZE;
257 }
258 // SAFETY: `out_ptr` points to a valid memory with size of `bytes_len`
259 unsafe { slice::from_raw_parts(self.out_ptr.cast(), bytes_len) }
260 }
261}