Skip to main content

walnut/
util.rs

1use std::time::{self, SystemTime};
2
3use crc32fast::Hasher;
4
5use crate::BLOCK_SIZE;
6
7/// Create 32bit checksums
8/// Wrapper struct around crc32fast hasher
9pub struct Checksum {
10    hasher: Hasher,
11}
12
13impl Checksum {
14    #[inline]
15    pub fn new() -> Self {
16        Self {
17            hasher: crc32fast::Hasher::new(),
18        }
19    }
20
21    #[inline]
22    pub fn update(&mut self, bytes: &[u8]) {
23        self.hasher.update(bytes);
24    }
25
26    #[inline]
27    pub fn finalize(self) -> u32 {
28        self.hasher.finalize()
29    }
30}
31
32// Calculate checksum for small objects
33// For large objects please use Checksum directly
34#[inline]
35pub fn calculate_checksum<S>(s: &S) -> u32
36where
37    S: serde::Serialize,
38{
39    let mut hasher = Checksum::new();
40    hasher.update(&bincode::serialize(&s).unwrap());
41    hasher.finalize()
42}
43
44#[inline]
45pub fn now() -> u64 {
46    SystemTime::now()
47        .duration_since(time::UNIX_EPOCH)
48        .unwrap()
49        .as_secs()
50}
51
52#[inline]
53pub fn block_seek_position(block_index: u32) -> u32 {
54    block_index * BLOCK_SIZE
55}
56
57#[inline]
58pub fn encrypt(bytes: &mut [u8], lookup_table: &Vec<u8>) {
59    // let len = secret.len();
60    // for (index, byte) in bytes.iter_mut().enumerate() {
61    //     let i = index & (len - 1);
62    //     // byte.bitxor_assign(secret[i]);
63    //     unsafe {
64    //         *byte ^= secret.get_unchecked(i);
65    //     }
66    // }
67    bytes
68        .iter_mut()
69        .zip(lookup_table)
70        .for_each(|(byte, secret)| *byte ^= secret);
71}
72
73#[inline]
74pub fn create_lookup_table(secret: &[u8], block_size: u32) -> Vec<u8> {
75    // let mut res: Vec<u8> = Vec::with_capacity(block_size as usize);
76    // unsafe { res.set_len(block_size as usize) };
77
78    (0..block_size)
79        .into_iter()
80        .map(|i| secret[i as usize & (secret.len() - 1)])
81        .collect()
82}