2323use core:: {
2424 borrow:: Borrow ,
2525 fmt,
26- hash:: Hash ,
26+ hash:: { Hash , Hasher } ,
2727 marker:: PhantomData ,
2828} ;
2929
@@ -38,6 +38,38 @@ use crate::{
3838 MemoryProvider ,
3939} ;
4040
41+ /// A simple FNV-1a hasher for no_std environments.
42+ ///
43+ /// Uses the 64-bit FNV-1a algorithm for reasonable hash distribution
44+ /// without requiring std or external dependencies.
45+ struct SimpleHasher {
46+ state : u64 ,
47+ }
48+
49+ impl SimpleHasher {
50+ const FNV_OFFSET_BASIS : u64 = 0xcbf29ce484222325 ;
51+ const FNV_PRIME : u64 = 0x00000100000001B3 ;
52+
53+ fn new ( ) -> Self {
54+ Self {
55+ state : Self :: FNV_OFFSET_BASIS ,
56+ }
57+ }
58+ }
59+
60+ impl Hasher for SimpleHasher {
61+ fn finish ( & self ) -> u64 {
62+ self . state
63+ }
64+
65+ fn write ( & mut self , bytes : & [ u8 ] ) {
66+ for & byte in bytes {
67+ self . state ^= u64:: from ( byte) ;
68+ self . state = self . state . wrapping_mul ( Self :: FNV_PRIME ) ;
69+ }
70+ }
71+ }
72+
4173/// A simple fixed-capacity hash map implementation for no_std environments.
4274///
4375/// This implementation uses linear probing for collision resolution and
@@ -100,9 +132,13 @@ where
100132
101133impl < K , V > ToBytes for Entry < K , V >
102134where
103- K : Clone + PartialEq + Eq + ToBytes ,
104- V : Clone + PartialEq + Eq + ToBytes ,
135+ K : Clone + PartialEq + Eq + ToBytes + Default ,
136+ V : Clone + PartialEq + Eq + ToBytes + Default ,
105137{
138+ fn serialized_size ( & self ) -> usize {
139+ self . key . serialized_size ( ) + self . value . serialized_size ( ) + self . hash . serialized_size ( )
140+ }
141+
106142 fn to_bytes_with_provider < ' a , PStream : MemoryProvider > (
107143 & self ,
108144 writer : & mut crate :: traits:: WriteStream < ' a > ,
@@ -173,20 +209,11 @@ where
173209 N
174210 }
175211
176- /// Calculates the hash of a key.
212+ /// Calculates the hash of a key using a simple FNV-1a-style hasher .
177213 fn hash_key < Q : ?Sized + Hash > ( & self , key : & Q ) -> u64 {
178- // For no_std environments, use a simple hash function
179- // This is not cryptographically secure but sufficient for HashMap functionality
180- let hash: u64 = 5381 ; // DJB2 hash algorithm starting value
181-
182- // Binary std/no_std choice
183- // we'll use a simplified approach. In a real implementation, you'd want
184- // to use a proper no_std hasher like `ahash` or implement Hasher for a simple
185- // algorithm.
186-
187- // For now, use a basic checksum-style hash
188- hash. wrapping_mul ( 33 )
189- . wrapping_add ( core:: ptr:: addr_of!( * key) as * const ( ) as usize as u64 )
214+ let mut hasher = SimpleHasher :: new ( ) ;
215+ key. hash ( & mut hasher) ;
216+ hasher. finish ( )
190217 }
191218
192219 /// Calculates the initial index for a key.
0 commit comments