ring/aead/
shift.rs

1// Copyright 2018 Brian Smith.
2//
3// Permission to use, copy, modify, and/or distribute this software for any
4// purpose with or without fee is hereby granted, provided that the above
5// copyright notice and this permission notice appear in all copies.
6//
7// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
8// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
10// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14
15use super::block::{Block, BLOCK_LEN};
16
17#[cfg(target_arch = "x86")]
18pub fn shift_full_blocks<F>(in_out: &mut [u8], in_prefix_len: usize, mut transform: F)
19where
20    F: FnMut(&[u8; BLOCK_LEN]) -> Block,
21{
22    use core::convert::TryFrom;
23
24    let in_out_len = in_out.len().checked_sub(in_prefix_len).unwrap();
25
26    for i in (0..in_out_len).step_by(BLOCK_LEN) {
27        let block = {
28            let input =
29                <&[u8; BLOCK_LEN]>::try_from(&in_out[(in_prefix_len + i)..][..BLOCK_LEN]).unwrap();
30            transform(input)
31        };
32        let output = <&mut [u8; BLOCK_LEN]>::try_from(&mut in_out[i..][..BLOCK_LEN]).unwrap();
33        *output = *block.as_ref();
34    }
35}
36
37pub fn shift_partial<F>((in_prefix_len, in_out): (usize, &mut [u8]), transform: F)
38where
39    F: FnOnce(&[u8]) -> Block,
40{
41    let (block, in_out_len) = {
42        let input = &in_out[in_prefix_len..];
43        let in_out_len = input.len();
44        if in_out_len == 0 {
45            return;
46        }
47        debug_assert!(in_out_len < BLOCK_LEN);
48        (transform(input), in_out_len)
49    };
50    in_out[..in_out_len].copy_from_slice(&block.as_ref()[..in_out_len]);
51}