1use std::time::{self, SystemTime};
2
3use crc32fast::Hasher;
4
5use crate::BLOCK_SIZE;
6
7pub 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#[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 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 (0..block_size)
79 .into_iter()
80 .map(|i| secret[i as usize & (secret.len() - 1)])
81 .collect()
82}