hasher.rs 808 B

12345678910111213141516171819202122232425262728
  1. use core::convert::TryInto;
  2. use core::hash::{BuildHasherDefault, Hasher};
  3. use core::mem::size_of;
  4. /// A simple `Hasher` implementation tuned for performance.
  5. #[derive(Default)]
  6. pub struct FastHasher(u64);
  7. /// A `BuildHasher` for `FastHasher`.
  8. pub type BuildFastHasher = BuildHasherDefault<FastHasher>;
  9. impl Hasher for FastHasher {
  10. fn finish(&self) -> u64 {
  11. self.0
  12. }
  13. fn write(&mut self, bytes: &[u8]) {
  14. let mut bytes = bytes;
  15. while bytes.len() > size_of::<u64>() {
  16. let (u64_bytes, remaining) = bytes.split_at(size_of::<u64>());
  17. self.0 ^= u64::from_ne_bytes(u64_bytes.try_into().unwrap());
  18. bytes = remaining
  19. }
  20. self.0 ^= bytes
  21. .iter()
  22. .fold(0u64, |result, b| (result << 8) | *b as u64);
  23. }
  24. }