tl_proto/
hasher.rs

1use std::hash::{Hash, Hasher};
2
3use crate::traits::*;
4
5/// Wrapper type to update hasher using the TL representation of type `T`.
6#[derive(Eq)]
7pub struct HashWrapper<T>(pub T);
8
9impl<T> HashWrapper<T>
10where
11    T: TlWrite,
12{
13    /// Updates the specified hasher this the TL representation of inner data.
14    #[inline(always)]
15    pub fn update_hasher<H: digest::Update>(&self, engine: &mut H) {
16        self.0.write_to(&mut DigestWriter(engine));
17    }
18}
19
20impl<T: PartialEq> PartialEq for HashWrapper<T> {
21    fn eq(&self, other: &Self) -> bool {
22        self.0.eq(&other.0)
23    }
24}
25
26struct DigestWriter<'a, T>(&'a mut T);
27
28impl<T> TlPacket for DigestWriter<'_, T>
29where
30    T: digest::Update,
31{
32    #[inline(always)]
33    fn ignore_signature(&self) -> bool {
34        true
35    }
36
37    #[inline(always)]
38    fn write_u32(&mut self, data: u32) {
39        self.0.update(&data.to_le_bytes());
40    }
41
42    #[inline(always)]
43    fn write_i32(&mut self, data: i32) {
44        self.0.update(&data.to_le_bytes());
45    }
46
47    #[inline(always)]
48    fn write_u64(&mut self, data: u64) {
49        self.0.update(&data.to_le_bytes());
50    }
51
52    #[inline(always)]
53    fn write_i64(&mut self, data: i64) {
54        self.0.update(&data.to_le_bytes());
55    }
56
57    #[inline(always)]
58    fn write_raw_slice(&mut self, data: &[u8]) {
59        self.0.update(data);
60    }
61}
62
63impl<T> Hash for HashWrapper<T>
64where
65    T: TlWrite,
66{
67    fn hash<H: Hasher>(&self, state: &mut H) {
68        self.0.write_to(&mut HashWriter(state))
69    }
70}
71
72struct HashWriter<'a>(pub &'a mut dyn Hasher);
73
74impl TlPacket for HashWriter<'_> {
75    #[inline(always)]
76    fn ignore_signature(&self) -> bool {
77        true
78    }
79
80    #[inline(always)]
81    fn write_u32(&mut self, data: u32) {
82        Hasher::write_u32(&mut self.0, data);
83    }
84
85    #[inline(always)]
86    fn write_i32(&mut self, data: i32) {
87        Hasher::write_i32(&mut self.0, data);
88    }
89
90    #[inline(always)]
91    fn write_u64(&mut self, data: u64) {
92        Hasher::write_u64(&mut self.0, data);
93    }
94
95    #[inline(always)]
96    fn write_i64(&mut self, data: i64) {
97        Hasher::write_i64(&mut self.0, data);
98    }
99
100    #[inline(always)]
101    fn write_raw_slice(&mut self, data: &[u8]) {
102        Hasher::write(&mut self.0, data);
103    }
104}