commit plain_hasher to util
This commit is contained in:
commit
a8542c58eb
|
@ -0,0 +1,12 @@
|
|||
[package]
|
||||
name = "plain_hasher"
|
||||
description = "Hasher for 32-bit keys."
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
license = "MIT"
|
||||
keywords = ["hash", "hasher"]
|
||||
categories = ["no-std"]
|
||||
homepage = "https://github.com/paritytech/plain_hasher"
|
||||
|
||||
[dependencies]
|
||||
crunchy = "0.1.6"
|
|
@ -0,0 +1,33 @@
|
|||
#![feature(test)]
|
||||
|
||||
extern crate test;
|
||||
extern crate plain_hasher;
|
||||
|
||||
use std::hash::Hasher;
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use test::{Bencher, black_box};
|
||||
use plain_hasher::PlainHasher;
|
||||
|
||||
#[bench]
|
||||
fn write_plain_hasher(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let n: u8 = black_box(100);
|
||||
(0..n).fold(PlainHasher::default(), |mut old, new| {
|
||||
let bb = black_box([new; 32]);
|
||||
old.write(&bb as &[u8]);
|
||||
old
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn write_default_hasher(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let n: u8 = black_box(100);
|
||||
(0..n).fold(DefaultHasher::default(), |mut old, new| {
|
||||
let bb = black_box([new; 32]);
|
||||
old.write(&bb as &[u8]);
|
||||
old
|
||||
});
|
||||
});
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
#![no_std]
|
||||
#[macro_use]
|
||||
extern crate crunchy;
|
||||
|
||||
use core::{hash, mem};
|
||||
|
||||
/// Hasher that just takes 8 bytes of the provided value.
|
||||
/// May only be used for keys which are 32 bytes.
|
||||
#[derive(Default)]
|
||||
pub struct PlainHasher {
|
||||
prefix: u64,
|
||||
}
|
||||
|
||||
impl hash::Hasher for PlainHasher {
|
||||
#[inline]
|
||||
fn finish(&self) -> u64 {
|
||||
self.prefix
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[allow(unused_assignments)]
|
||||
fn write(&mut self, bytes: &[u8]) {
|
||||
debug_assert!(bytes.len() == 32);
|
||||
|
||||
unsafe {
|
||||
let mut bytes_ptr = bytes.as_ptr();
|
||||
let prefix_u8: &mut [u8; 8] = mem::transmute(&mut self.prefix);
|
||||
let mut prefix_ptr = prefix_u8.as_mut_ptr();
|
||||
|
||||
unroll! {
|
||||
for _i in 0..8 {
|
||||
*prefix_ptr ^= (*bytes_ptr ^ *bytes_ptr.offset(8)) ^ (*bytes_ptr.offset(16) ^ *bytes_ptr.offset(24));
|
||||
|
||||
bytes_ptr = bytes_ptr.offset(1);
|
||||
prefix_ptr = prefix_ptr.offset(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use core::hash::Hasher;
|
||||
use super::PlainHasher;
|
||||
|
||||
#[test]
|
||||
fn it_works() {
|
||||
let mut bytes = [32u8; 32];
|
||||
bytes[0] = 15;
|
||||
let mut hasher = PlainHasher::default();
|
||||
hasher.write(&bytes);
|
||||
assert_eq!(hasher.prefix, 47);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue