├── .gitignore ├── Cargo.toml ├── examples └── derive.rs ├── README.md ├── LICENSE-MIT ├── src ├── fnv.rs ├── lib.rs └── murmur3.rs ├── tests ├── murmur3.rs └── fnv.rs ├── .github └── workflows │ └── ci.yml ├── CHANGELOG.md └── LICENSE-APACHE /.gitignore: -------------------------------------------------------------------------------- 1 | **/*.rs.bk 2 | .#* 3 | target 4 | Cargo.lock 5 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors = ["Jorge Aparicio "] 3 | categories = ["no-std"] 4 | description = "32-bit hashing algorithms" 5 | keywords = ["32-bit", "hash", "fnv", "murmur3"] 6 | license = "MIT OR Apache-2.0" 7 | name = "hash32" 8 | repository = "https://github.com/rust-embedded-community/hash32" 9 | version = "1.0.0" 10 | edition = "2021" 11 | rust-version = "1.56" 12 | -------------------------------------------------------------------------------- /examples/derive.rs: -------------------------------------------------------------------------------- 1 | use std::hash::Hash; 2 | 3 | use hash32::{FnvHasher, Hasher}; 4 | 5 | #[derive(Hash)] 6 | struct Led { 7 | state: bool, 8 | } 9 | 10 | #[derive(Hash)] 11 | struct Ipv4Addr([u8; 4]); 12 | 13 | #[derive(Hash)] 14 | struct Generic { 15 | inner: T, 16 | } 17 | 18 | fn main() { 19 | let mut fnv = FnvHasher::default(); 20 | Led { state: true }.hash(&mut fnv); 21 | Generic { inner: 0 }.hash(&mut fnv); 22 | Ipv4Addr([127, 0, 0, 1]).hash(&mut fnv); 23 | println!("{}", fnv.finish32()) 24 | } 25 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # `hash32` 2 | 3 | > 32-bit hashing machinery 4 | 5 | ## [Documentation](https://docs.rs/hash32) 6 | 7 | ## License 8 | 9 | Licensed under either of 10 | 11 | - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or 12 | http://www.apache.org/licenses/LICENSE-2.0) 13 | - MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 14 | 15 | at your option. 16 | 17 | ### Contribution 18 | 19 | Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the 20 | work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any 21 | additional terms or conditions. 22 | 23 | ## Minimum Supported Rust Version (MSRV) 24 | This crate is guaranteed to compile on latest stable Rust. It *might* compile on older 25 | versions but that may change in any new patch release. 26 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2018 Jorge Aparicio 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /src/fnv.rs: -------------------------------------------------------------------------------- 1 | use crate::Hasher as _; 2 | 3 | const BASIS: u32 = 0x811c9dc5; 4 | const PRIME: u32 = 0x1000193; 5 | 6 | /// 32-bit Fowler-Noll-Vo hasher 7 | /// 8 | /// Specifically this implements the [FNV-1a hash]. 9 | /// 10 | /// [FNV-1a hash]: https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function#FNV-1a_hash 11 | /// 12 | /// # Examples 13 | /// 14 | /// ``` 15 | /// use core::hash::Hasher as _; 16 | /// use hash32::{FnvHasher, Hasher as _}; 17 | /// 18 | /// let mut hasher: FnvHasher = Default::default(); 19 | /// hasher.write(b"Hello, World!"); 20 | /// 21 | /// println!("Hash is {:x}!", hasher.finish32()); 22 | /// ``` 23 | #[derive(Debug, Clone)] 24 | pub struct FnvHasher { 25 | state: u32, 26 | } 27 | 28 | impl Default for FnvHasher { 29 | #[inline] 30 | fn default() -> Self { 31 | Self { state: BASIS } 32 | } 33 | } 34 | 35 | impl crate::Hasher for FnvHasher { 36 | #[inline] 37 | fn finish32(&self) -> u32 { 38 | self.state 39 | } 40 | } 41 | 42 | impl core::hash::Hasher for FnvHasher { 43 | #[inline] 44 | fn write(&mut self, bytes: &[u8]) { 45 | for byte in bytes { 46 | self.state ^= u32::from(*byte); 47 | self.state = self.state.wrapping_mul(PRIME); 48 | } 49 | } 50 | 51 | #[inline] 52 | fn finish(&self) -> u64 { 53 | self.finish32().into() 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /tests/murmur3.rs: -------------------------------------------------------------------------------- 1 | use hash32::Murmur3Hasher; 2 | use std::hash::Hasher; 3 | 4 | fn testcase(data: &[u8], expected_hash_value: u64) { 5 | let mut hasher: Murmur3Hasher = Default::default(); 6 | hasher.write(data); 7 | assert_eq!(hasher.finish(), expected_hash_value); 8 | } 9 | 10 | #[test] 11 | fn murmurhash3_vectors() { 12 | // Test vectors are adapted from this gist 13 | // https://gist.github.com/vladimirgamalyan/defb2482feefbf5c3ea25b14c557753b 14 | 15 | // with zero data and zero seed, everything becomes zero 16 | testcase(&[], 0); 17 | // make sure 4-byte chunks use unsigned math 18 | testcase(&[0xff, 0xff, 0xff, 0xff], 0x76293B50); 19 | // Endian order. UInt32 should end up as 0x87654321 20 | testcase(&[0x21, 0x43, 0x65, 0x87], 0xF55B516B); 21 | // Only three bytes. Should end up as 0x654321 22 | testcase(&[0x21, 0x43, 0x65], 0x7E4A8634); 23 | // Only two bytes. Should end up as 0x4321 24 | testcase(&[0x21, 0x43], 0xA0F7B07A); 25 | // Only one byte. Should end up as 0x21 26 | testcase(&[0x21], 0x72661CF4); 27 | // Make sure compiler doesn't see zero and convert to null 28 | testcase(&[0x00, 0x00, 0x00, 0x00], 0x2362F9DE); 29 | testcase(&[0x00, 0x00, 0x00], 0x85F0B427); 30 | testcase(&[0x00, 0x00], 0x30F4C306); 31 | testcase(&[0x00], 0x514E28B7); 32 | 33 | testcase( 34 | "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".as_bytes(), 35 | 0xEE925B90, 36 | ); 37 | } 38 | -------------------------------------------------------------------------------- /tests/fnv.rs: -------------------------------------------------------------------------------- 1 | use hash32::FnvHasher; 2 | use std::hash::Hasher; 3 | 4 | #[test] 5 | fn fnv1a_vectors() { 6 | // Test vectors adapted from this public domain repo: 7 | // https://github.com/drichardson/fnv/blob/cd12926ef306ec32dbef3e65c62662c4eb5b99ed/test_fnv.c 8 | 9 | const FNV1A_TEST_VECTORS: &[(&str, u64)] = &[ 10 | ("", 0x811c9dc5), 11 | ("a", 0xe40c292c), 12 | ("b", 0xe70c2de5), 13 | ("c", 0xe60c2c52), 14 | ("d", 0xe10c2473), 15 | ("e", 0xe00c22e0), 16 | ("f", 0xe30c2799), 17 | ("fo", 0x6222e842), 18 | ("foo", 0xa9f37ed7), 19 | ("foob", 0x3f5076ef), 20 | ("fooba", 0x39aaa18a), 21 | ("foobar", 0xbf9cf968), 22 | ("ch", 0x5f299f4e), 23 | ("cho", 0xef8580f3), 24 | ("chon", 0xac297727), 25 | ("chong", 0x4546b9c0), 26 | ("chongo", 0xbd564e7d), 27 | ("chongo ", 0x6bdd5c67), 28 | ("chongo w", 0xdd77ed30), 29 | ("chongo wa", 0xf4ca9683), 30 | ("chongo was", 0x4aeb9bd0), 31 | ("chongo was ", 0xe0e67ad0), 32 | ("chongo was h", 0xc2d32fa8), 33 | ("chongo was he", 0x7f743fb7), 34 | ("chongo was her", 0x6900631f), 35 | ("chongo was here", 0xc59c990e), 36 | ("chongo was here!", 0x448524fd), 37 | ("chongo was here!\n", 0xd49930d5), 38 | ]; 39 | 40 | for (data, expected) in FNV1A_TEST_VECTORS { 41 | let mut hasher: FnvHasher = Default::default(); 42 | hasher.write(data.as_bytes()); 43 | assert_eq!(hasher.finish(), *expected); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | branches: [main, staging, trying] 4 | pull_request: 5 | branches: [main] 6 | merge_group: 7 | workflow_dispatch: 8 | 9 | name: Continuous integration 10 | 11 | jobs: 12 | test: 13 | name: test 14 | runs-on: ubuntu-latest 15 | env: {"RUSTFLAGS": "-D warnings"} 16 | strategy: 17 | matrix: 18 | target: 19 | - x86_64-unknown-linux-gnu 20 | - i686-unknown-linux-musl 21 | steps: 22 | - uses: actions/checkout@v4 23 | - uses: dtolnay/rust-toolchain@master 24 | with: 25 | toolchain: stable 26 | target: ${{ matrix.target }} 27 | - run: cargo test --target=${{ matrix.target }} 28 | 29 | style: 30 | name: style 31 | runs-on: ubuntu-latest 32 | steps: 33 | - uses: actions/checkout@v4 34 | - uses: dtolnay/rust-toolchain@stable 35 | with: 36 | components: rustfmt 37 | - name: cargo fmt --check 38 | run: cargo fmt --all -- --check 39 | 40 | clippy: 41 | runs-on: ubuntu-latest 42 | steps: 43 | - uses: actions/checkout@v4 44 | - uses: dtolnay/rust-toolchain@stable 45 | with: 46 | components: clippy 47 | - run: cargo clippy --all --all-targets -- --deny warnings 48 | 49 | rustdoc: 50 | name: rustdoc 51 | runs-on: ubuntu-latest 52 | env: {"RUSTDOCFLAGS": "-D warnings"} 53 | steps: 54 | - uses: actions/checkout@v4 55 | - uses: dtolnay/rust-toolchain@nightly 56 | # docs.rs builds documentation with: 57 | # - nightly rust 58 | # - all features 59 | # - cargo rustdoc, not cargo doc 60 | - run: cargo +nightly rustdoc --all-features 61 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](http://keepachangelog.com/) 6 | and this project adheres to [Semantic Versioning](http://semver.org/). 7 | 8 | ## [v1.0.0] - 2025-05-27 9 | 10 | ### Added 11 | 12 | - Added `Debug` implementations to hashers. 13 | - Added `Clone` implementations to hashers. 14 | 15 | ### Changed 16 | 17 | - Updated the edition from 2015 to 2021. 18 | 19 | ### Removed 20 | 21 | - Removed the `byteorder` dependency. 22 | - Removed the `BuildHasherDefault` type. 23 | - This type existed because `core::hash::BuildHasherDefault` did not have a const constructor. 24 | - As of 1.85 `core::hash::BuildHasherDefault` has a const constructor. 25 | 26 | ## [v0.3.1] - 2022-08-09 27 | 28 | ### Fixed 29 | 30 | - fixed downstream clippy warnings around `murmur3::Hasher` 31 | 32 | ## [v0.3.0] - 2022-04-29 33 | 34 | ### Changed 35 | 36 | - [breaking-change] Made `Hasher` a subtrait of `core::hash::Hasher`, and 37 | renamed `finish` to `finish32` to avoid conflicting 38 | - Relaxed some restrictions on `BuildHasherDefault` 39 | 40 | ### Removed 41 | 42 | - [breaking-change] Removed `Hash` in favour of `core::hash::Hash` 43 | - [breaking-change] Removed `BuildHasher` in favour of `core::hash::BuildHasher` 44 | 45 | ## [v0.2.1] - 2021-04-19 46 | 47 | ### Added 48 | 49 | - implement `Clone`, `PartialEq`, `Eq` for `BuildDefaultHasher` 50 | 51 | ## [v0.2.0] - 2021-04-19 52 | 53 | ### Changed 54 | 55 | - [breaking-change] `const-fn` feature has been removed 56 | - [breaking-change] MSRV policy has been changed to "only latest stable is guaranteed to be supported" 57 | 58 | ## [v0.1.2] - 2019-11-14 59 | 60 | ### Updated 61 | 62 | - Included MSRV in the documentation; also added examples for 2015 and 2018 63 | editions. 64 | 65 | ## [v0.1.1] - 2019-11-14 66 | 67 | ### Added 68 | 69 | - Implementations for tuples 70 | 71 | ## v0.1.0 - 2018-04-23 72 | 73 | Initial release 74 | 75 | [Unreleased]: https://github.com/rust-embedded-community/hash32/compare/v1.0.0...HEAD 76 | [v1.0.0]: https://github.com/rust-embedded-community/hash32/compare/v0.3.1...v1.0.0 77 | [v0.3.1]: https://github.com/rust-embedded-community/hash32/compare/v0.3.0...v0.3.1 78 | [v0.3.0]: https://github.com/rust-embedded-community/hash32/compare/v0.2.1...v0.3.0 79 | [v0.2.1]: https://github.com/rust-embedded-community/hash32/compare/v0.2.0...v0.2.1 80 | [v0.2.0]: https://github.com/rust-embedded-community/hash32/compare/v0.1.2...v0.2.0 81 | [v0.1.2]: https://github.com/rust-embedded-community/hash32/compare/v0.1.1...v0.1.2 82 | [v0.1.1]: https://github.com/rust-embedded-community/hash32/compare/v0.1.0...v0.1.1 83 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! 32-bit hashing algorithms 2 | //! 3 | //! # Why? 4 | //! 5 | //! Because 32-bit architectures are a thing (e.g. ARM Cortex-M) and you don't want your hashing 6 | //! function to pull in a bunch of slow 64-bit compiler intrinsics (software implementations of 7 | //! 64-bit operations). 8 | //! 9 | //! # Relationship to `core::hash` 10 | //! 11 | //! This crate extends [`core::hash::Hasher`] with a 32-bit version, [`hash32::Hasher`]. 12 | //! 13 | //! The [`hash32::Hasher`] trait requires the hasher to perform only 32-bit operations when 14 | //! computing the hash. 15 | //! The trait method [`hash32::Hasher::finish32`] returns the hasher's result as a `u32`. 16 | //! The [`core::hash::Hasher::finish`] method zero-extends the [`hash32::Hasher::finish32`] 17 | //! result to a `u64`. 18 | //! 19 | //! Since [`hash32::Hasher`] extends [`core::hash::Hasher`], the [`hash32::Hasher`] trait can be 20 | //! used with any type which implements the [`core::hash::Hash`] trait. 21 | //! 22 | //! [`hash32::Hasher`]: crate::Hasher 23 | //! [`hash32::Hasher::finish32`]: crate::Hasher::finish32 24 | //! [`core::hash`]: https://doc.rust-lang.org/std/hash/index.html 25 | //! [`finish32`]: crate::Hasher::finish32 26 | //! 27 | //! # Hashers 28 | //! 29 | //! This crate provides implementations of the following 32-bit hashing algorithms: 30 | //! 31 | //! - [`FnvHasher`] Fowler-Noll-Vo 1a 32 | //! - [`Murmur3Hasher`] `MurmurHash3` 33 | //! 34 | //! ## Picking a hasher 35 | //! 36 | //! - [`FnvHasher`] is faster and consumes less code space than [`Murmur3Hasher`]. 37 | //! - [`Murmur3Hasher`] offers better collision resistance than [`FnvHasher`]. 38 | //! 39 | //! ## Security 40 | //! 41 | //! Hashers provided by this crate are not cryptographically secure, and must **not** be used 42 | //! for security purposes. 43 | //! Additionally, unlike [`std::hash::DefaultHasher`] the provided hash algorithms lack 44 | //! denial-of-service protection, and must only be used with trusted data. 45 | //! 46 | //! # Generic code 47 | //! 48 | //! In generic code, the trait bound `H: core::hash::Hasher` accepts **both** 64-bit hashers such 49 | //! as [`std::hash::DefaultHasher`]; and 32-bit hashers such as the ones defined in this crate, 50 | //! [`FnvHasher`], and [`Murmur3Hasher`]. 51 | //! 52 | //! The trait bound `H: hash32::Hasher` is **more** restrictive as it only accepts 32-bit hashers. 53 | //! 54 | //! [`std::hash::DefaultHasher`]: https://doc.rust-lang.org/std/hash/struct.DefaultHasher.html 55 | //! 56 | //! # MSRV 57 | //! 58 | //! This crate is guaranteed to compile on latest stable Rust. It *might* compile on older 59 | //! versions but that may change in any new patch release. 60 | //! 61 | //! # Examples 62 | //! 63 | //! ``` 64 | //! use hash32::{FnvHasher, Hasher as _}; 65 | //! 66 | //! #[derive(Hash)] 67 | //! struct Person { 68 | //! id: u32, 69 | //! name: &'static str, 70 | //! phone: u64, 71 | //! } 72 | //! 73 | //! let person1 = Person { 74 | //! id: 5, 75 | //! name: "Janet", 76 | //! phone: 555_666_7777, 77 | //! }; 78 | //! let person2 = Person { 79 | //! id: 5, 80 | //! name: "Bob", 81 | //! phone: 555_666_7777, 82 | //! }; 83 | //! 84 | //! assert!(calculate_hash(&person1) != calculate_hash(&person2)); 85 | //! 86 | //! fn calculate_hash(t: &T) -> u32 { 87 | //! let mut fnv: FnvHasher = Default::default(); 88 | //! t.hash(&mut fnv); 89 | //! fnv.finish32() 90 | //! } 91 | //! ``` 92 | 93 | #![warn( 94 | missing_docs, 95 | clippy::use_self, 96 | clippy::doc_markdown, 97 | clippy::ptr_as_ptr, 98 | clippy::trivially_copy_pass_by_ref 99 | )] 100 | #![no_std] 101 | 102 | pub use crate::fnv::FnvHasher; 103 | pub use crate::murmur3::Murmur3Hasher; 104 | 105 | mod fnv; 106 | mod murmur3; 107 | 108 | /// An extension of [`core::hash::Hasher`] for 32-bit hashers. 109 | /// 110 | /// For hashers that implement this trait, the [`core::hash::Hasher::finish`] method should return a 111 | /// zero-extended version of the result from [`Hasher::finish32`]. 112 | /// 113 | /// # Contract 114 | /// 115 | /// Implementers of this trait must **not** perform any 64-bit (or 128-bit) operation while computing 116 | /// the hash. 117 | /// 118 | /// # Examples 119 | /// 120 | /// ``` 121 | /// use core::hash::Hasher as _; 122 | /// use hash32::{FnvHasher, Hasher as _}; 123 | /// 124 | /// let mut hasher: FnvHasher = Default::default(); 125 | /// 126 | /// hasher.write_u32(1989); 127 | /// hasher.write_u8(11); 128 | /// hasher.write_u8(9); 129 | /// hasher.write(b"Huh?"); 130 | /// 131 | /// println!("Hash is {:x}!", hasher.finish32()); 132 | /// ``` 133 | pub trait Hasher: core::hash::Hasher { 134 | /// The equivalent of [`core::hash::Hasher::finish`] for 32-bit hashers. 135 | /// 136 | /// This returns the hash directly; [`core::hash::Hasher::finish`] zero-extends the `finish32` 137 | /// result to 64-bits for compatibility. 138 | fn finish32(&self) -> u32; 139 | } 140 | -------------------------------------------------------------------------------- /src/murmur3.rs: -------------------------------------------------------------------------------- 1 | use core::mem::MaybeUninit; 2 | use core::slice; 3 | 4 | use crate::Hasher as _; 5 | 6 | /// 32-bit `MurmurHash3` hasher 7 | /// 8 | /// # Examples 9 | /// 10 | /// ``` 11 | /// use core::hash::Hasher as _; 12 | /// use hash32::{Hasher as _, Murmur3Hasher}; 13 | /// 14 | /// let mut hasher: Murmur3Hasher = Default::default(); 15 | /// hasher.write(b"Hello, World!"); 16 | /// 17 | /// println!("Hash is {:x}!", hasher.finish32()); 18 | /// ``` 19 | #[derive(Debug, Clone)] 20 | pub struct Murmur3Hasher { 21 | buf: Buffer, 22 | index: Index, 23 | processed: u32, 24 | state: State, 25 | } 26 | 27 | #[derive(Debug, Clone)] 28 | struct State(u32); 29 | 30 | #[derive(Debug, Clone, Copy)] 31 | #[repr(align(4))] 32 | struct Buffer { 33 | bytes: MaybeUninit<[u8; 4]>, 34 | } 35 | 36 | #[derive(Debug, Clone, Copy, PartialEq)] 37 | enum Index { 38 | _0, 39 | _1, 40 | _2, 41 | _3, 42 | } 43 | 44 | impl Index { 45 | fn usize(self) -> usize { 46 | match self { 47 | Self::_0 => 0, 48 | Self::_1 => 1, 49 | Self::_2 => 2, 50 | Self::_3 => 3, 51 | } 52 | } 53 | } 54 | 55 | impl From for Index { 56 | fn from(x: usize) -> Self { 57 | match x % 4 { 58 | 0 => Self::_0, 59 | 1 => Self::_1, 60 | 2 => Self::_2, 61 | 3 => Self::_3, 62 | _ => unreachable!(), 63 | } 64 | } 65 | } 66 | 67 | impl Murmur3Hasher { 68 | /// # Safety 69 | /// 70 | /// The caller must ensure that `self.index.usize() + buf.len() <= 4`. 71 | unsafe fn push(&mut self, buf: &[u8]) { 72 | let start = self.index.usize(); 73 | let len = buf.len(); 74 | // NOTE(unsafe) avoid calling `memcpy` on a 0-3 byte copy 75 | // self.buf.bytes[start..start+len].copy_from(buf); 76 | for i in 0..len { 77 | unsafe { 78 | *self 79 | .buf 80 | .bytes 81 | .assume_init_mut() 82 | .get_unchecked_mut(start + i) = *buf.get_unchecked(i); 83 | } 84 | } 85 | self.index = Index::from(start + len); 86 | } 87 | } 88 | 89 | impl Default for Murmur3Hasher { 90 | fn default() -> Self { 91 | Self { 92 | buf: Buffer { 93 | bytes: MaybeUninit::uninit(), 94 | }, 95 | index: Index::_0, 96 | processed: 0, 97 | state: State(0), 98 | } 99 | } 100 | } 101 | 102 | impl crate::Hasher for Murmur3Hasher { 103 | fn finish32(&self) -> u32 { 104 | // tail 105 | let mut state = match self.index { 106 | Index::_3 => { 107 | let mut block = 0; 108 | unsafe { 109 | block ^= u32::from(self.buf.bytes.assume_init_ref()[2]) << 16; 110 | block ^= u32::from(self.buf.bytes.assume_init_ref()[1]) << 8; 111 | block ^= u32::from(self.buf.bytes.assume_init_ref()[0]); 112 | } 113 | self.state.0 ^ pre_mix(block) 114 | } 115 | Index::_2 => { 116 | let mut block = 0; 117 | unsafe { 118 | block ^= u32::from(self.buf.bytes.assume_init_ref()[1]) << 8; 119 | block ^= u32::from(self.buf.bytes.assume_init_ref()[0]); 120 | } 121 | self.state.0 ^ pre_mix(block) 122 | } 123 | Index::_1 => { 124 | let mut block = 0; 125 | unsafe { 126 | block ^= u32::from(self.buf.bytes.assume_init_ref()[0]); 127 | } 128 | self.state.0 ^ pre_mix(block) 129 | } 130 | Index::_0 => self.state.0, 131 | }; 132 | 133 | // finalization mix 134 | state ^= self.processed; 135 | state ^= state >> 16; 136 | state = state.wrapping_mul(0x85ebca6b); 137 | state ^= state >> 13; 138 | state = state.wrapping_mul(0xc2b2ae35); 139 | state ^= state >> 16; 140 | 141 | state 142 | } 143 | } 144 | 145 | impl core::hash::Hasher for Murmur3Hasher { 146 | #[inline] 147 | fn write(&mut self, bytes: &[u8]) { 148 | let len = bytes.len(); 149 | self.processed += len as u32; 150 | 151 | let body = if self.index == Index::_0 { 152 | // CASE 1 153 | bytes 154 | } else { 155 | let index = self.index.usize(); 156 | if len + index >= 4 { 157 | // CASE 2 158 | 159 | // we can complete a block using the data left in the buffer 160 | // NOTE(unsafe) avoid panicking branch (`slice_index_len_fail`) 161 | // let (head, body) = bytes.split_at(4 - index); 162 | let mid = 4 - index; 163 | let head = unsafe { slice::from_raw_parts(bytes.as_ptr(), mid) }; 164 | let body = unsafe { slice::from_raw_parts(bytes.as_ptr().add(mid), len - mid) }; 165 | 166 | // NOTE(unsafe) avoid calling `memcpy` on a 0-3 byte copy 167 | // self.buf.bytes[index..].copy_from_slice(head); 168 | for i in 0..4 - index { 169 | unsafe { 170 | *self 171 | .buf 172 | .bytes 173 | .assume_init_mut() 174 | .get_unchecked_mut(index + i) = *head.get_unchecked(i); 175 | } 176 | } 177 | 178 | self.index = Index::_0; 179 | 180 | self.state.process_block(&self.buf.bytes); 181 | 182 | body 183 | } else { 184 | // CASE 3 185 | bytes 186 | } 187 | }; 188 | 189 | for block in body.chunks(4) { 190 | if block.len() == 4 { 191 | self.state 192 | .process_block(unsafe { &*(block.as_ptr().cast()) }); 193 | } else { 194 | // NOTE(unsafe) In this branch, `block.len() < 4`. For CASE 1 and CASE 2 above, 195 | // `self.index.usize()` will be 0 here, so `self.index.usize() + block.len() < 4`. 196 | // The condition for CASE 3 ensures that `self.index.usize() + bytes.len() < 4`. 197 | unsafe { 198 | self.push(block); 199 | } 200 | } 201 | } 202 | } 203 | 204 | #[inline] 205 | fn finish(&self) -> u64 { 206 | self.finish32().into() 207 | } 208 | } 209 | 210 | const C1: u32 = 0xcc9e2d51; 211 | const C2: u32 = 0x1b873593; 212 | const R1: u32 = 15; 213 | 214 | impl State { 215 | #[allow(clippy::trivially_copy_pass_by_ref)] 216 | fn process_block(&mut self, block: &MaybeUninit<[u8; 4]>) { 217 | self.0 ^= pre_mix(u32::from_le_bytes(unsafe { *block.assume_init_ref() })); 218 | self.0 = self.0.rotate_left(13); 219 | self.0 = 5u32.wrapping_mul(self.0).wrapping_add(0xe6546b64); 220 | } 221 | } 222 | 223 | fn pre_mix(mut block: u32) -> u32 { 224 | block = block.wrapping_mul(C1); 225 | block = block.rotate_left(R1); 226 | block = block.wrapping_mul(C2); 227 | block 228 | } 229 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------