|
1 | 1 | #![cfg_attr(not(feature = "std"), no_std)] |
2 | 2 |
|
3 | | -mod hash_utils; |
4 | | -use hash_utils::do_hash; |
| 3 | +#[cfg(feature = "std")] |
| 4 | +pub fn do_hash<T: core::hash::Hash>(t: &T) -> u64 { |
| 5 | + use std::hash::{DefaultHasher, Hasher}; |
| 6 | + let mut hasher = DefaultHasher::default(); |
| 7 | + t.hash(&mut hasher); |
| 8 | + hasher.finish() |
| 9 | +} |
| 10 | + |
| 11 | +#[cfg(not(feature = "std"))] |
| 12 | +pub fn do_hash<T: core::hash::Hash>(t: &T) -> u64 { |
| 13 | + use core::hash::Hasher; |
| 14 | + // Simple FNV-1a hasher for no_std, for testing purposes only. |
| 15 | + struct FnvHasher(u64); |
| 16 | + |
| 17 | + impl core::hash::Hasher for FnvHasher { |
| 18 | + fn write(&mut self, bytes: &[u8]) { |
| 19 | + for byte in bytes { |
| 20 | + self.0 ^= *byte as u64; |
| 21 | + self.0 = self.0.wrapping_mul(0x100000001b3); |
| 22 | + } |
| 23 | + } |
| 24 | + fn finish(&self) -> u64 { |
| 25 | + self.0 |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + let mut hasher = FnvHasher(0xcbf29ce484222325); |
| 30 | + t.hash(&mut hasher); |
| 31 | + hasher.finish() |
| 32 | +} |
5 | 33 |
|
6 | 34 | pub mod utils { |
7 | 35 | pub fn alternate_u32_hash_function<H: core::hash::Hasher>( |
@@ -237,3 +265,49 @@ mod enums { |
237 | 265 | assert_eq!(do_hash(&wc), do_hash(&core::mem::discriminant(&wc))); |
238 | 266 | } |
239 | 267 | } |
| 268 | + |
| 269 | +#[cfg(feature = "eq")] |
| 270 | +mod hash_respects_eq_skip { |
| 271 | + use super::*; |
| 272 | + use derive_more::{Eq, Hash, PartialEq}; |
| 273 | + |
| 274 | + #[derive(Hash, Eq, PartialEq)] |
| 275 | + struct Struct { |
| 276 | + field: i32, |
| 277 | + #[eq(skip)] |
| 278 | + _skipped: &'static str, |
| 279 | + } |
| 280 | + |
| 281 | + #[derive(Hash, Eq, PartialEq)] |
| 282 | + enum Enum { |
| 283 | + A { |
| 284 | + field: i32, |
| 285 | + #[partial_eq(skip)] |
| 286 | + _skipped: &'static str, |
| 287 | + }, |
| 288 | + } |
| 289 | + |
| 290 | + #[test] |
| 291 | + fn assert() { |
| 292 | + assert_eq!( |
| 293 | + do_hash(&Struct { |
| 294 | + field: 42, |
| 295 | + _skipped: "ignored" |
| 296 | + }), |
| 297 | + do_hash(&42) |
| 298 | + ); |
| 299 | + assert_eq!( |
| 300 | + do_hash(&Enum::A { |
| 301 | + field: 42, |
| 302 | + _skipped: "ignored" |
| 303 | + }), |
| 304 | + do_hash(&( |
| 305 | + core::mem::discriminant(&Enum::A { |
| 306 | + field: 0, |
| 307 | + _skipped: "ignored" |
| 308 | + }), |
| 309 | + 42 |
| 310 | + )) |
| 311 | + ); |
| 312 | + } |
| 313 | +} |
0 commit comments