|
1 |
| -use crate::{HasId, Id, UpdateArg}; |
| 1 | +use core::hash::Hasher; |
| 2 | + |
| 3 | +use crate::{FxHasher, HasId, Id, UpdateArg}; |
2 | 4 |
|
3 | 5 | pub trait Parents<const N: usize>: AllParents {
|
4 | 6 | fn ids(&self) -> [Id; N];
|
5 | 7 | fn maybe_ids(&self) -> [Option<Id>; N];
|
| 8 | + |
| 9 | + #[inline] |
| 10 | + fn hash(&self) -> u64 { |
| 11 | + let mut hasher = FxHasher::default(); |
| 12 | + core::hash::Hash::hash(&self.ids(), &mut hasher); |
| 13 | + hasher.finish() |
| 14 | + } |
6 | 15 | }
|
7 | 16 |
|
8 | 17 | impl Parents<0> for () {
|
@@ -103,3 +112,67 @@ impl<T: HasId + Copy, const N: usize> Parents<N> for [T; N] {
|
103 | 112 | impl<T: HasId + Copy, const N: usize> AllParents for [T; N] {}
|
104 | 113 |
|
105 | 114 | pub trait AllParents {}
|
| 115 | + |
| 116 | +#[cfg(test)] |
| 117 | +mod tests { |
| 118 | + |
| 119 | + #[cfg(feature = "std")] |
| 120 | + #[ignore = "slow"] |
| 121 | + #[test] |
| 122 | + fn test_collisions() { |
| 123 | + use std::collections::HashSet; |
| 124 | + use crate::{Id, Parents}; |
| 125 | + |
| 126 | + let handle = std::thread::spawn(|| { |
| 127 | + let mut hashes = HashSet::new(); |
| 128 | + for i in 20000..30000u16 { |
| 129 | + for j in 20000..30000 { |
| 130 | + let i = Id { |
| 131 | + id: i as u64, |
| 132 | + len: 0, |
| 133 | + }; |
| 134 | + let j = Id { |
| 135 | + id: j, |
| 136 | + len: 0, |
| 137 | + }; |
| 138 | + let parents = (i, j); |
| 139 | + let hash = parents.hash(); |
| 140 | + if hashes.contains(&(hash)) { |
| 141 | + panic!("collision {}, {}, hash: {hash}", i.id, j.id,); |
| 142 | + } |
| 143 | + hashes.insert(hash); |
| 144 | + } |
| 145 | + if i % 1000 == 0 { |
| 146 | + println!("i: {}", i); |
| 147 | + } |
| 148 | + } |
| 149 | + hashes |
| 150 | + }); |
| 151 | + let mut hashes = HashSet::new(); |
| 152 | + |
| 153 | + for i in 10000..20000 { |
| 154 | + for j in 10000..20000 { |
| 155 | + let i = Id { |
| 156 | + id: i, |
| 157 | + len: 0, |
| 158 | + }; |
| 159 | + let j = Id { |
| 160 | + id: j, |
| 161 | + len: 0, |
| 162 | + }; |
| 163 | + let parents = (i, j); |
| 164 | + let hash = parents.hash(); |
| 165 | + if hashes.contains(&(hash)) { |
| 166 | + panic!("collision"); |
| 167 | + } |
| 168 | + hashes.insert(hash); |
| 169 | + } |
| 170 | + if i % 1000 == 0 { |
| 171 | + println!("i: {}", i); |
| 172 | + } |
| 173 | + } |
| 174 | + |
| 175 | + let other_hashes = handle.join().unwrap(); |
| 176 | + assert_eq!(hashes.intersection(&other_hashes).count(), 0); |
| 177 | + } |
| 178 | +} |
0 commit comments