| 1 |
use core::hash::Hasher; |
| 2 |
use siphasher::sip128::{Hash128, Hasher128}; |
| 3 |
|
| 4 |
pub struct PortableSipHasher<H> { |
| 5 |
inner: H, |
| 6 |
} |
| 7 |
|
| 8 |
impl<H> PortableSipHasher<H> { |
| 9 |
pub fn new(inner: H) -> Self { |
| 10 |
Self { inner } |
| 11 |
} |
| 12 |
} |
| 13 |
|
| 14 |
impl<H: Hasher> Hasher for PortableSipHasher<H> { |
| 15 |
fn finish(&self) -> u64 { |
| 16 |
self.inner.finish() |
| 17 |
} |
| 18 |
|
| 19 |
fn write(&mut self, bytes: &[u8]) { |
| 20 |
self.inner.write(bytes) |
| 21 |
} |
| 22 |
|
| 23 |
fn write_u8(&mut self, i: u8) { |
| 24 |
self.inner.write_u8(i) |
| 25 |
} |
| 26 |
|
| 27 |
// `SipHasher` invokes `to_le` on integers before encoding them, treating them as byte arrays |
| 28 |
// rather than values, which is not the right interpretation for us; fix that by flipping |
| 29 |
// endianness twice. |
| 30 |
fn write_u16(&mut self, i: u16) { |
| 31 |
self.inner.write_u16(i.to_le()); |
| 32 |
} |
| 33 |
fn write_u32(&mut self, i: u32) { |
| 34 |
self.inner.write_u32(i.to_le()); |
| 35 |
} |
| 36 |
fn write_u64(&mut self, i: u64) { |
| 37 |
self.inner.write_u64(i.to_le()); |
| 38 |
} |
| 39 |
fn write_u128(&mut self, i: u128) { |
| 40 |
self.inner.write_u128(i.to_le()); |
| 41 |
} |
| 42 |
|
| 43 |
fn write_usize(&mut self, i: usize) { |
| 44 |
self.inner.write_u64((i as u64).to_le()); |
| 45 |
} |
| 46 |
// The default `write_isize` implementation casts to `usize` first, so we end up with |
| 47 |
// `i as usize as u64`, which is different on 32-bit and 64-bit architectures: |
| 48 |
// |
| 49 |
// 32-bit: `-1` -> `2^32 - 1` -> `2^32 - 1` |
| 50 |
// 64-bit: `-1` -> `2^64 - 1` -> `2^64 - 1` |
| 51 |
fn write_isize(&mut self, i: isize) { |
| 52 |
self.inner.write_u64((i as u64).to_le()); |
| 53 |
} |
| 54 |
|
| 55 |
// Fixed-size signed integers correctly forward to unsigned implementations. |
| 56 |
} |
| 57 |
|
| 58 |
impl<H: Hasher128> Hasher128 for PortableSipHasher<H> { |
| 59 |
fn finish128(&self) -> Hash128 { |
| 60 |
self.inner.finish128() |
| 61 |
} |
| 62 |
} |