Debian Codegraph @

third_party/rust/block-buffer/src/lib.rs

raw
1 //! Fixed size buffer for block processing of data.
2 #![no_std]
3 #![doc(
4 html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg",
5 html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg"
6 )]
7 #![warn(missing_docs, rust_2018_idioms)]
8
9 pub use generic_array;
10
11 use core::{fmt, marker::PhantomData, slice};
12 use generic_array::{
13 typenum::{IsLess, Le, NonZero, U256},
14 ArrayLength, GenericArray,
15 };
16
17 mod sealed;
18
19 /// Block on which `BlockBuffer` operates.
20 pub type Block<BlockSize> = GenericArray<u8, BlockSize>;
21
22 /// Trait for buffer kinds.
23 pub trait BufferKind: sealed::Sealed {}
24
25 /// Eager block buffer kind, which guarantees that buffer position
26 /// always lies in the range of `0..BlockSize`.
27 #[derive(Copy, Clone, Debug, Default)]
28 pub struct Eager {}
29
30 /// Lazy block buffer kind, which guarantees that buffer position
31 /// always lies in the range of `0..=BlockSize`.
32 #[derive(Copy, Clone, Debug, Default)]
33 pub struct Lazy {}
34
35 impl BufferKind for Eager {}
36 impl BufferKind for Lazy {}
37
38 /// Eager block buffer.
39 pub type EagerBuffer<B> = BlockBuffer<B, Eager>;
40 /// Lazy block buffer.
41 pub type LazyBuffer<B> = BlockBuffer<B, Lazy>;
42
43 /// Block buffer error.
44 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
45 pub struct Error;
46
47 impl fmt::Display for Error {
48 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
49 f.write_str("Block buffer error")
50 }
51 }
52
53 /// Buffer for block processing of data.
54 #[derive(Debug)]
55 pub struct BlockBuffer<BlockSize, Kind>
56 where
57 BlockSize: ArrayLength<u8> + IsLess<U256>,
58 Le<BlockSize, U256>: NonZero,
59 Kind: BufferKind,
60 {
61 buffer: Block<BlockSize>,
62 pos: u8,
63 _pd: PhantomData<Kind>,
64 }
65
66 impl<BlockSize, Kind> Default for BlockBuffer<BlockSize, Kind>
67 where
68 BlockSize: ArrayLength<u8> + IsLess<U256>,
69 Le<BlockSize, U256>: NonZero,
70 Kind: BufferKind,
71 {
72 fn default() -> Self {
73 Self {
74 buffer: Default::default(),
75 pos: 0,
76 _pd: PhantomData,
77 }
78 }
79 }
80
81 impl<BlockSize, Kind> Clone for BlockBuffer<BlockSize, Kind>
82 where
83 BlockSize: ArrayLength<u8> + IsLess<U256>,
84 Le<BlockSize, U256>: NonZero,
85 Kind: BufferKind,
86 {
87 fn clone(&self) -> Self {
88 Self {
89 buffer: self.buffer.clone(),
90 pos: self.pos,
91 _pd: PhantomData,
92 }
93 }
94 }
95
96 impl<BlockSize, Kind> BlockBuffer<BlockSize, Kind>
97 where
98 BlockSize: ArrayLength<u8> + IsLess<U256>,
99 Le<BlockSize, U256>: NonZero,
100 Kind: BufferKind,
101 {
102 /// Create new buffer from slice.
103 ///
104 /// # Panics
105 /// If slice length is not valid for used buffer kind.
106 #[inline(always)]
107 pub fn new(buf: &[u8]) -> Self {
108 Self::try_new(buf).unwrap()
109 }
110
111 /// Create new buffer from slice.
112 ///
113 /// Returns an error if slice length is not valid for used buffer kind.
114 #[inline(always)]
115 pub fn try_new(buf: &[u8]) -> Result<Self, Error> {
116 let pos = buf.len();
117 if !Kind::invariant(pos, BlockSize::USIZE) {
118 return Err(Error);
119 }
120 let mut buffer = Block::<BlockSize>::default();
121 buffer[..pos].copy_from_slice(buf);
122 Ok(Self {
123 buffer,
124 pos: pos as u8,
125 _pd: PhantomData,
126 })
127 }
128
129 /// Digest data in `input` in blocks of size `BlockSize` using
130 /// the `compress` function, which accepts slice of blocks.
131 #[inline]
132 pub fn digest_blocks(
133 &mut self,
134 mut input: &[u8],
135 mut compress: impl FnMut(&[Block<BlockSize>]),
136 ) {
137 let pos = self.get_pos();
138 // using `self.remaining()` for some reason
139 // prevents panic elimination
140 let rem = self.size() - pos;
141 let n = input.len();
142 // Note that checking condition `pos + n < BlockSize` is
143 // equivalent to checking `n < rem`, where `rem` is equal
144 // to `BlockSize - pos`. Using the latter allows us to work
145 // around compiler accounting for possible overflow of
146 // `pos + n` which results in it inserting unreachable
147 // panic branches. Using `unreachable_unchecked` in `get_pos`
148 // we convince compiler that `BlockSize - pos` never underflows.
149 if Kind::invariant(n, rem) {
150 // double slicing allows to remove panic branches
151 self.buffer[pos..][..n].copy_from_slice(input);
152 self.set_pos_unchecked(pos + n);
153 return;
154 }
155 if pos != 0 {
156 let (left, right) = input.split_at(rem);
157 input = right;
158 self.buffer[pos..].copy_from_slice(left);
159 compress(slice::from_ref(&self.buffer));
160 }
161
162 let (blocks, leftover) = Kind::split_blocks(input);
163 if !blocks.is_empty() {
164 compress(blocks);
165 }
166
167 let n = leftover.len();
168 self.buffer[..n].copy_from_slice(leftover);
169 self.set_pos_unchecked(n);
170 }
171
172 /// Reset buffer by setting cursor position to zero.
173 #[inline(always)]
174 pub fn reset(&mut self) {
175 self.set_pos_unchecked(0);
176 }
177
178 /// Pad remaining data with zeros and return resulting block.
179 #[inline(always)]
180 pub fn pad_with_zeros(&mut self) -> &mut Block<BlockSize> {
181 let pos = self.get_pos();
182 self.buffer[pos..].iter_mut().for_each(|b| *b = 0);
183 self.set_pos_unchecked(0);
184 &mut self.buffer
185 }
186
187 /// Return current cursor position.
188 #[inline(always)]
189 pub fn get_pos(&self) -> usize {
190 let pos = self.pos as usize;
191 if !Kind::invariant(pos, BlockSize::USIZE) {
192 debug_assert!(false);
193 // SAFETY: `pos` never breaks the invariant
194 unsafe {
195 core::hint::unreachable_unchecked();
196 }
197 }
198 pos
199 }
200
201 /// Return slice of data stored inside the buffer.
202 #[inline(always)]
203 pub fn get_data(&self) -> &[u8] {
204 &self.buffer[..self.get_pos()]
205 }
206
207 /// Set buffer content and cursor position.
208 ///
209 /// # Panics
210 /// If `pos` is bigger or equal to block size.
211 #[inline]
212 pub fn set(&mut self, buf: Block<BlockSize>, pos: usize) {
213 assert!(Kind::invariant(pos, BlockSize::USIZE));
214 self.buffer = buf;
215 self.set_pos_unchecked(pos);
216 }
217
218 /// Return size of the internall buffer in bytes.
219 #[inline(always)]
220 pub fn size(&self) -> usize {
221 BlockSize::USIZE
222 }
223
224 /// Return number of remaining bytes in the internall buffer.
225 #[inline(always)]
226 pub fn remaining(&self) -> usize {
227 self.size() - self.get_pos()
228 }
229
230 #[inline(always)]
231 fn set_pos_unchecked(&mut self, pos: usize) {
232 debug_assert!(Kind::invariant(pos, BlockSize::USIZE));
233 self.pos = pos as u8;
234 }
235 }
236
237 impl<BlockSize> BlockBuffer<BlockSize, Eager>
238 where
239 BlockSize: ArrayLength<u8> + IsLess<U256>,
240 Le<BlockSize, U256>: NonZero,
241 {
242 /// Set `data` to generated blocks.
243 #[inline]
244 pub fn set_data(
245 &mut self,
246 mut data: &mut [u8],
247 mut process_blocks: impl FnMut(&mut [Block<BlockSize>]),
248 ) {
249 let pos = self.get_pos();
250 let r = self.remaining();
251 let n = data.len();
252 if pos != 0 {
253 if n < r {
254 // double slicing allows to remove panic branches
255 data.copy_from_slice(&self.buffer[pos..][..n]);
256 self.set_pos_unchecked(pos + n);
257 return;
258 }
259 let (left, right) = data.split_at_mut(r);
260 data = right;
261 left.copy_from_slice(&self.buffer[pos..]);
262 }
263
264 let (blocks, leftover) = to_blocks_mut(data);
265 process_blocks(blocks);
266
267 let n = leftover.len();
268 if n != 0 {
269 let mut block = Default::default();
270 process_blocks(slice::from_mut(&mut block));
271 leftover.copy_from_slice(&block[..n]);
272 self.buffer = block;
273 }
274 self.set_pos_unchecked(n);
275 }
276
277 /// Compress remaining data after padding it with `delim`, zeros and
278 /// the `suffix` bytes. If there is not enough unused space, `compress`
279 /// will be called twice.
280 ///
281 /// # Panics
282 /// If suffix length is bigger than block size.
283 #[inline(always)]
284 pub fn digest_pad(
285 &mut self,
286 delim: u8,
287 suffix: &[u8],
288 mut compress: impl FnMut(&Block<BlockSize>),
289 ) {
290 if suffix.len() > BlockSize::USIZE {
291 panic!("suffix is too long");
292 }
293 let pos = self.get_pos();
294 self.buffer[pos] = delim;
295 for b in &mut self.buffer[pos + 1..] {
296 *b = 0;
297 }
298
299 let n = self.size() - suffix.len();
300 if self.size() - pos - 1 < suffix.len() {
301 compress(&self.buffer);
302 let mut block = Block::<BlockSize>::default();
303 block[n..].copy_from_slice(suffix);
304 compress(&block);
305 } else {
306 self.buffer[n..].copy_from_slice(suffix);
307 compress(&self.buffer);
308 }
309 self.set_pos_unchecked(0)
310 }
311
312 /// Pad message with 0x80, zeros and 64-bit message length using
313 /// big-endian byte order.
314 #[inline]
315 pub fn len64_padding_be(&mut self, data_len: u64, compress: impl FnMut(&Block<BlockSize>)) {
316 self.digest_pad(0x80, &data_len.to_be_bytes(), compress);
317 }
318
319 /// Pad message with 0x80, zeros and 64-bit message length using
320 /// little-endian byte order.
321 #[inline]
322 pub fn len64_padding_le(&mut self, data_len: u64, compress: impl FnMut(&Block<BlockSize>)) {
323 self.digest_pad(0x80, &data_len.to_le_bytes(), compress);
324 }
325
326 /// Pad message with 0x80, zeros and 128-bit message length using
327 /// big-endian byte order.
328 #[inline]
329 pub fn len128_padding_be(&mut self, data_len: u128, compress: impl FnMut(&Block<BlockSize>)) {
330 self.digest_pad(0x80, &data_len.to_be_bytes(), compress);
331 }
332 }
333
334 /// Split message into mutable slice of parallel blocks, blocks, and leftover bytes.
335 #[inline(always)]
336 fn to_blocks_mut<N: ArrayLength<u8>>(data: &mut [u8]) -> (&mut [Block<N>], &mut [u8]) {
337 let nb = data.len() / N::USIZE;
338 let (left, right) = data.split_at_mut(nb * N::USIZE);
339 let p = left.as_mut_ptr() as *mut Block<N>;
340 // SAFETY: we guarantee that `blocks` does not point outside of `data`, and `p` is valid for
341 // mutation
342 let blocks = unsafe { slice::from_raw_parts_mut(p, nb) };
343 (blocks, right)
344 }