aws_lc_rs/cipher/
block.rs

1// Copyright 2018 Brian Smith.
2// SPDX-License-Identifier: ISC
3// Modifications copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
4// SPDX-License-Identifier: Apache-2.0 OR ISC
5
6/// An array of 16 bytes that can (in the `x86_64` and `AAarch64` ABIs, at least)
7/// be efficiently passed by value and returned by value (i.e. in registers),
8/// and which meets the alignment requirements of `u32` and `u64` (at least)
9/// for the target.
10#[repr(C)]
11#[derive(Copy, Clone)]
12pub(crate) struct Block {
13    subblocks: [u64; 2],
14}
15
16/// Block length
17pub(crate) const BLOCK_LEN: usize = 16;
18
19impl Block {
20    #[inline]
21    pub(crate) fn zero() -> Self {
22        Self { subblocks: [0, 0] }
23    }
24}
25
26impl From<[u8; BLOCK_LEN]> for Block {
27    #[inline]
28    fn from(bytes: [u8; BLOCK_LEN]) -> Self {
29        unsafe { core::mem::transmute(bytes) }
30    }
31}
32
33impl AsRef<[u8; BLOCK_LEN]> for Block {
34    #[allow(clippy::transmute_ptr_to_ptr)]
35    #[inline]
36    fn as_ref(&self) -> &[u8; BLOCK_LEN] {
37        unsafe { core::mem::transmute(self) }
38    }
39}
40
41impl AsMut<[u8; BLOCK_LEN]> for Block {
42    #[allow(clippy::transmute_ptr_to_ptr)]
43    #[inline]
44    fn as_mut(&mut self) -> &mut [u8; BLOCK_LEN] {
45        unsafe { core::mem::transmute(self) }
46    }
47}
48
49#[cfg(test)]
50mod tests {
51    #[test]
52    fn test_block_clone() {
53        use super::{Block, BLOCK_LEN};
54        let block_a = Block::from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);
55        #[allow(clippy::clone_on_copy)]
56        let block_b = block_a.clone();
57
58        for i in 0..BLOCK_LEN {
59            assert_eq!(block_a.as_ref()[i], block_b.as_ref()[i]);
60        }
61    }
62
63    #[test]
64    fn test_block_clone_mut_ref() {
65        use super::{Block, BLOCK_LEN};
66        let mut block_a = Block::from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);
67        #[allow(clippy::clone_on_copy)]
68        let mut block_b = block_a.clone();
69
70        for i in 0..BLOCK_LEN {
71            assert_eq!(block_a.as_mut()[i], block_b.as_mut()[i]);
72        }
73    }
74}