statsig_rust/hashing/
hash_util.rs1use serde::Deserialize;
2
3use super::{djb2::djb2, memo_sha_256::MemoSha256};
4use std::fmt::Display;
5
6#[derive(Deserialize)]
7pub enum HashAlgorithm {
8 Djb2,
9 None,
10 Sha256,
11}
12
13impl HashAlgorithm {
14 #[must_use]
15 pub fn from_string(input: &str) -> Option<Self> {
16 match input {
17 "sha256" => Some(HashAlgorithm::Sha256),
18 "djb2" => Some(HashAlgorithm::Djb2),
19 "none" => Some(HashAlgorithm::None),
20 _ => None,
21 }
22 }
23}
24
25impl Display for HashAlgorithm {
26 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27 match self {
28 HashAlgorithm::Djb2 => write!(f, "djb2"),
29 HashAlgorithm::None => write!(f, "none"),
30 HashAlgorithm::Sha256 => write!(f, "sha256"),
31 }
32 }
33}
34
35pub struct HashUtil {
36 sha_hasher: MemoSha256,
37}
38
39impl Default for HashUtil {
40 fn default() -> Self {
41 Self::new()
42 }
43}
44
45impl HashUtil {
46 #[must_use]
47 pub fn new() -> Self {
48 Self {
49 sha_hasher: MemoSha256::new(),
50 }
51 }
52
53 pub fn hash(&self, input: &String, hash_algorithm: &HashAlgorithm) -> String {
54 match hash_algorithm {
55 HashAlgorithm::Sha256 => self.sha_hasher.hash_string(input),
56 HashAlgorithm::Djb2 => djb2(input),
57 HashAlgorithm::None => input.to_string(),
58 }
59 }
60
61 pub fn sha256(&self, input: &String) -> String {
62 self.sha_hasher.hash_string(input)
63 }
64
65 pub fn sha256_to_u64(&self, input: &String) -> u64 {
66 let hash = self.sha_hasher.hash_string(input);
67
68 let mut hasher_bytes = [0u8; 8];
69 hasher_bytes.copy_from_slice(&hash.as_bytes()[0..8]);
70
71 u64::from_be_bytes(hasher_bytes)
72 }
73
74 pub fn evaluation_hash(&self, input: &String) -> Option<usize> {
75 self.sha_hasher.compute_hash(input)
76 }
77}