├── .github └── workflows │ └── rust.yml ├── .gitignore ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md └── src ├── lib.rs ├── random_state.rs └── seeded_state.rs /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | permissions: 4 | contents: read 5 | 6 | on: [push, pull_request] 7 | 8 | env: 9 | CARGO_TERM_COLOR: always 10 | RUST_BACKTRACE: 1 11 | RUSTUP_MAX_RETRIES: 10 12 | 13 | concurrency: 14 | group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }} 15 | cancel-in-progress: true 16 | 17 | jobs: 18 | test: 19 | strategy: 20 | matrix: 21 | os: [ubuntu, windows, macos] 22 | runs-on: ${{ matrix.os }}-latest 23 | timeout-minutes: 30 24 | steps: 25 | - uses: actions/checkout@v4 26 | - run: rustup update stable && rustup default stable 27 | - run: cargo check 28 | - run: cargo test 29 | - run: rustup update nightly && rustup default nightly 30 | - run: cargo test --all-features 31 | cross-test: 32 | strategy: 33 | matrix: 34 | target: [ 35 | "x86_64-unknown-linux-gnu", # 64-bits, little-endian 36 | "i686-unknown-linux-gnu", # 32-bits, little-endian 37 | "mips-unknown-linux-gnu", # 32-bits, big-endian 38 | "mips64-unknown-linux-gnuabi64", # 64-bits, big-endian 39 | ] 40 | runs-on: ubuntu-latest 41 | timeout-minutes: 30 42 | steps: 43 | - uses: actions/checkout@v4 44 | - name: install miri 45 | run: rustup toolchain add nightly --no-self-update --component miri && rustup default nightly 46 | - run: | 47 | cargo miri test --target=${{ matrix.target }} --all-features 48 | env: 49 | MIRIFLAGS: -Zmiri-strict-provenance 50 | RUSTDOCFLAGS: ${{ env.RUSTDOCFLAGS }} -Z randomize-layout 51 | RUSTFLAGS: ${{ env.RUSTFLAGS }} -Z randomize-layout 52 | fmt: 53 | runs-on: ubuntu-latest 54 | steps: 55 | - uses: actions/checkout@v4 56 | - run: rustup update stable && rustup default stable 57 | - run: rustup component add rustfmt 58 | - run: cargo fmt --all --check 59 | docs: 60 | runs-on: ubuntu-latest 61 | steps: 62 | - uses: actions/checkout@v4 63 | - run: rustup update stable && rustup default stable 64 | - run: cargo doc --workspace --document-private-items --no-deps 65 | env: 66 | RUSTDOCFLAGS: -D warnings 67 | clippy: 68 | runs-on: ubuntu-latest 69 | steps: 70 | - uses: actions/checkout@v4 71 | - run: rustup update stable && rustup default stable 72 | - run: rustup component add clippy 73 | - run: cargo clippy --workspace --all-targets --no-deps 74 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | /Cargo.lock 4 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # 2.1.1 2 | 3 | - Change the internal algorithm to better accomodate large hashmaps. 4 | This mitigates a [regression with 2.0 in rustc](https://github.com/rust-lang/rust/issues/135477). 5 | See [PR#55](https://github.com/rust-lang/rustc-hash/pull/55) for more details on the change (this PR was not merged). 6 | This problem might be improved with changes to hashbrown in the future. 7 | 8 | ## 2.1.0 9 | 10 | - Implement `Clone` for `FxRandomState` 11 | - Implement `Clone` for `FxSeededState` 12 | - Use SPDX license expression in license field 13 | 14 | ## 2.0.0 15 | 16 | - Replace hash with faster and better finalized hash. 17 | This replaces the previous "fxhash" algorithm originating in Firefox 18 | with a custom hasher designed and implemented by Orson Peters ([`@orlp`](https://github.com/orlp)). 19 | It was measured to have slightly better performance for rustc, has better theoretical properties 20 | and also includes a significantly better string hasher. 21 | - Fix `no_std` builds 22 | 23 | ## 1.2.0 (**YANKED**) 24 | 25 | **Note: This version has been yanked due to issues with the `no_std` feature!** 26 | 27 | - Add a `FxBuildHasher` unit struct 28 | - Improve documentation 29 | - Add seed API for supplying custom seeds other than 0 30 | - Add `FxRandomState` based on `rand` (behind the `rand` feature) for random seeds 31 | - Make many functions `const fn` 32 | - Implement `Clone` for `FxHasher` struct 33 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # The Rust Code of Conduct 2 | 3 | The Code of Conduct for this repository [can be found online](https://www.rust-lang.org/conduct.html). -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rustc-hash" 3 | version = "2.1.1" 4 | authors = ["The Rust Project Developers"] 5 | description = "A speedy, non-cryptographic hashing algorithm used by rustc" 6 | license = "Apache-2.0 OR MIT" 7 | readme = "README.md" 8 | keywords = ["hash", "hasher", "fxhash", "rustc"] 9 | repository = "https://github.com/rust-lang/rustc-hash" 10 | edition = "2021" 11 | 12 | [features] 13 | default = ["std"] 14 | std = [] 15 | nightly = [] 16 | rand = ["dep:rand", "std"] 17 | 18 | [dependencies] 19 | rand = { version = "0.8", optional = true } 20 | -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rustc-hash 2 | 3 | [![crates.io](https://img.shields.io/crates/v/rustc-hash.svg)](https://crates.io/crates/rustc-hash) 4 | [![Documentation](https://docs.rs/rustc-hash/badge.svg)](https://docs.rs/rustc-hash) 5 | 6 | A speedy, non-cryptographic hashing algorithm used by `rustc`. 7 | The [hash map in `std`](https://doc.rust-lang.org/std/collections/struct.HashMap.html) uses SipHash by default, which provides resistance against DOS attacks. 8 | These attacks aren't a concern in the compiler so we prefer to use a quicker, 9 | non-cryptographic hash algorithm. 10 | 11 | The original hash algorithm provided by this crate was one taken from Firefox, 12 | hence the hasher it provides is called FxHasher. This name is kept for backwards 13 | compatibility, but the underlying hash has since been replaced. The current 14 | design for the hasher is a polynomial hash finished with a single bit rotation, 15 | together with a wyhash-inspired compression function for strings/slices, both 16 | designed by Orson Peters. 17 | 18 | For `rustc` we have tried many different hashing algorithms. Hashing speed is 19 | critical, especially for single integers. Spending more CPU cycles on a higher 20 | quality hash does not reduce hash collisions enough to make the compiler faster 21 | on real-world benchmarks. 22 | 23 | ## Usage 24 | 25 | This crate provides `FxHashMap` and `FxHashSet` as collections. 26 | They are simply type aliases for their `std::collection` counterparts using the Fx hasher. 27 | 28 | ```rust 29 | use rustc_hash::FxHashMap; 30 | 31 | let mut map: FxHashMap = FxHashMap::default(); 32 | map.insert(22, 44); 33 | ``` 34 | 35 | ### `no_std` 36 | 37 | The `std` feature is on by default to enable collections. 38 | It can be turned off in `Cargo.toml` like so: 39 | 40 | ```toml 41 | rustc-hash = { version = "2.1", default-features = false } 42 | ``` 43 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! A speedy, non-cryptographic hashing algorithm used by `rustc`. 2 | //! 3 | //! # Example 4 | //! 5 | //! ```rust 6 | //! # #[cfg(feature = "std")] 7 | //! # fn main() { 8 | //! use rustc_hash::FxHashMap; 9 | //! 10 | //! let mut map: FxHashMap = FxHashMap::default(); 11 | //! map.insert(22, 44); 12 | //! # } 13 | //! # #[cfg(not(feature = "std"))] 14 | //! # fn main() { } 15 | //! ``` 16 | 17 | #![no_std] 18 | #![cfg_attr(feature = "nightly", feature(hasher_prefixfree_extras))] 19 | 20 | #[cfg(feature = "std")] 21 | extern crate std; 22 | 23 | #[cfg(feature = "rand")] 24 | extern crate rand; 25 | 26 | #[cfg(feature = "rand")] 27 | mod random_state; 28 | 29 | mod seeded_state; 30 | 31 | use core::default::Default; 32 | use core::hash::{BuildHasher, Hasher}; 33 | #[cfg(feature = "std")] 34 | use std::collections::{HashMap, HashSet}; 35 | 36 | /// Type alias for a hash map that uses the Fx hashing algorithm. 37 | #[cfg(feature = "std")] 38 | pub type FxHashMap = HashMap; 39 | 40 | /// Type alias for a hash set that uses the Fx hashing algorithm. 41 | #[cfg(feature = "std")] 42 | pub type FxHashSet = HashSet; 43 | 44 | #[cfg(feature = "rand")] 45 | pub use random_state::{FxHashMapRand, FxHashSetRand, FxRandomState}; 46 | 47 | pub use seeded_state::FxSeededState; 48 | #[cfg(feature = "std")] 49 | pub use seeded_state::{FxHashMapSeed, FxHashSetSeed}; 50 | 51 | /// A speedy hash algorithm for use within rustc. The hashmap in liballoc 52 | /// by default uses SipHash which isn't quite as speedy as we want. In the 53 | /// compiler we're not really worried about DOS attempts, so we use a fast 54 | /// non-cryptographic hash. 55 | /// 56 | /// The current implementation is a fast polynomial hash with a single 57 | /// bit rotation as a finishing step designed by Orson Peters. 58 | #[derive(Clone)] 59 | pub struct FxHasher { 60 | hash: usize, 61 | } 62 | 63 | // One might view a polynomial hash 64 | // m[0] * k + m[1] * k^2 + m[2] * k^3 + ... 65 | // as a multilinear hash with keystream k[..] 66 | // m[0] * k[0] + m[1] * k[1] + m[2] * k[2] + ... 67 | // where keystream k just happens to be generated using a multiplicative 68 | // congruential pseudorandom number generator (MCG). For that reason we chose a 69 | // constant that was found to be good for a MCG in: 70 | // "Computationally Easy, Spectrally Good Multipliers for Congruential 71 | // Pseudorandom Number Generators" by Guy Steele and Sebastiano Vigna. 72 | #[cfg(target_pointer_width = "64")] 73 | const K: usize = 0xf1357aea2e62a9c5; 74 | #[cfg(target_pointer_width = "32")] 75 | const K: usize = 0x93d765dd; 76 | 77 | impl FxHasher { 78 | /// Creates a `fx` hasher with a given seed. 79 | pub const fn with_seed(seed: usize) -> FxHasher { 80 | FxHasher { hash: seed } 81 | } 82 | 83 | /// Creates a default `fx` hasher. 84 | pub const fn default() -> FxHasher { 85 | FxHasher { hash: 0 } 86 | } 87 | } 88 | 89 | impl Default for FxHasher { 90 | #[inline] 91 | fn default() -> FxHasher { 92 | Self::default() 93 | } 94 | } 95 | 96 | impl FxHasher { 97 | #[inline] 98 | fn add_to_hash(&mut self, i: usize) { 99 | self.hash = self.hash.wrapping_add(i).wrapping_mul(K); 100 | } 101 | } 102 | 103 | impl Hasher for FxHasher { 104 | #[inline] 105 | fn write(&mut self, bytes: &[u8]) { 106 | // Compress the byte string to a single u64 and add to our hash. 107 | self.write_u64(hash_bytes(bytes)); 108 | } 109 | 110 | #[inline] 111 | fn write_u8(&mut self, i: u8) { 112 | self.add_to_hash(i as usize); 113 | } 114 | 115 | #[inline] 116 | fn write_u16(&mut self, i: u16) { 117 | self.add_to_hash(i as usize); 118 | } 119 | 120 | #[inline] 121 | fn write_u32(&mut self, i: u32) { 122 | self.add_to_hash(i as usize); 123 | } 124 | 125 | #[inline] 126 | fn write_u64(&mut self, i: u64) { 127 | self.add_to_hash(i as usize); 128 | #[cfg(target_pointer_width = "32")] 129 | self.add_to_hash((i >> 32) as usize); 130 | } 131 | 132 | #[inline] 133 | fn write_u128(&mut self, i: u128) { 134 | self.add_to_hash(i as usize); 135 | #[cfg(target_pointer_width = "32")] 136 | self.add_to_hash((i >> 32) as usize); 137 | self.add_to_hash((i >> 64) as usize); 138 | #[cfg(target_pointer_width = "32")] 139 | self.add_to_hash((i >> 96) as usize); 140 | } 141 | 142 | #[inline] 143 | fn write_usize(&mut self, i: usize) { 144 | self.add_to_hash(i); 145 | } 146 | 147 | #[cfg(feature = "nightly")] 148 | #[inline] 149 | fn write_length_prefix(&mut self, _len: usize) { 150 | // Most cases will specialize hash_slice to call write(), which encodes 151 | // the length already in a more efficient manner than we could here. For 152 | // HashDoS-resistance you would still need to include this for the 153 | // non-slice collection hashes, but for the purposes of rustc we do not 154 | // care and do not wish to pay the performance penalty of mixing in len 155 | // for those collections. 156 | } 157 | 158 | #[cfg(feature = "nightly")] 159 | #[inline] 160 | fn write_str(&mut self, s: &str) { 161 | // Similarly here, write already encodes the length, so nothing special 162 | // is needed. 163 | self.write(s.as_bytes()) 164 | } 165 | 166 | #[inline] 167 | fn finish(&self) -> u64 { 168 | // Since we used a multiplicative hash our top bits have the most 169 | // entropy (with the top bit having the most, decreasing as you go). 170 | // As most hash table implementations (including hashbrown) compute 171 | // the bucket index from the bottom bits we want to move bits from the 172 | // top to the bottom. Ideally we'd rotate left by exactly the hash table 173 | // size, but as we don't know this we'll choose 26 bits, giving decent 174 | // entropy up until 2^26 table sizes. On 32-bit hosts we'll dial it 175 | // back down a bit to 15 bits. 176 | 177 | #[cfg(target_pointer_width = "64")] 178 | const ROTATE: u32 = 26; 179 | #[cfg(target_pointer_width = "32")] 180 | const ROTATE: u32 = 15; 181 | 182 | self.hash.rotate_left(ROTATE) as u64 183 | 184 | // A bit reversal would be even better, except hashbrown also expects 185 | // good entropy in the top 7 bits and a bit reverse would fill those 186 | // bits with low entropy. More importantly, bit reversals are very slow 187 | // on x86-64. A byte reversal is relatively fast, but still has a 2 188 | // cycle latency on x86-64 compared to the 1 cycle latency of a rotate. 189 | // It also suffers from the hashbrown-top-7-bit-issue. 190 | } 191 | } 192 | 193 | // Nothing special, digits of pi. 194 | const SEED1: u64 = 0x243f6a8885a308d3; 195 | const SEED2: u64 = 0x13198a2e03707344; 196 | const PREVENT_TRIVIAL_ZERO_COLLAPSE: u64 = 0xa4093822299f31d0; 197 | 198 | #[inline] 199 | fn multiply_mix(x: u64, y: u64) -> u64 { 200 | #[cfg(target_pointer_width = "64")] 201 | { 202 | // We compute the full u64 x u64 -> u128 product, this is a single mul 203 | // instruction on x86-64, one mul plus one mulhi on ARM64. 204 | let full = (x as u128) * (y as u128); 205 | let lo = full as u64; 206 | let hi = (full >> 64) as u64; 207 | 208 | // The middle bits of the full product fluctuate the most with small 209 | // changes in the input. This is the top bits of lo and the bottom bits 210 | // of hi. We can thus make the entire output fluctuate with small 211 | // changes to the input by XOR'ing these two halves. 212 | lo ^ hi 213 | 214 | // Unfortunately both 2^64 + 1 and 2^64 - 1 have small prime factors, 215 | // otherwise combining with + or - could result in a really strong hash, as: 216 | // x * y = 2^64 * hi + lo = (-1) * hi + lo = lo - hi, (mod 2^64 + 1) 217 | // x * y = 2^64 * hi + lo = 1 * hi + lo = lo + hi, (mod 2^64 - 1) 218 | // Multiplicative hashing is universal in a field (like mod p). 219 | } 220 | 221 | #[cfg(target_pointer_width = "32")] 222 | { 223 | // u64 x u64 -> u128 product is prohibitively expensive on 32-bit. 224 | // Decompose into 32-bit parts. 225 | let lx = x as u32; 226 | let ly = y as u32; 227 | let hx = (x >> 32) as u32; 228 | let hy = (y >> 32) as u32; 229 | 230 | // u32 x u32 -> u64 the low bits of one with the high bits of the other. 231 | let afull = (lx as u64) * (hy as u64); 232 | let bfull = (hx as u64) * (ly as u64); 233 | 234 | // Combine, swapping low/high of one of them so the upper bits of the 235 | // product of one combine with the lower bits of the other. 236 | afull ^ bfull.rotate_right(32) 237 | } 238 | } 239 | 240 | /// A wyhash-inspired non-collision-resistant hash for strings/slices designed 241 | /// by Orson Peters, with a focus on small strings and small codesize. 242 | /// 243 | /// The 64-bit version of this hash passes the SMHasher3 test suite on the full 244 | /// 64-bit output, that is, f(hash_bytes(b) ^ f(seed)) for some good avalanching 245 | /// permutation f() passed all tests with zero failures. When using the 32-bit 246 | /// version of multiply_mix this hash has a few non-catastrophic failures where 247 | /// there are a handful more collisions than an optimal hash would give. 248 | /// 249 | /// We don't bother avalanching here as we'll feed this hash into a 250 | /// multiplication after which we take the high bits, which avalanches for us. 251 | #[inline] 252 | fn hash_bytes(bytes: &[u8]) -> u64 { 253 | let len = bytes.len(); 254 | let mut s0 = SEED1; 255 | let mut s1 = SEED2; 256 | 257 | if len <= 16 { 258 | // XOR the input into s0, s1. 259 | if len >= 8 { 260 | s0 ^= u64::from_le_bytes(bytes[0..8].try_into().unwrap()); 261 | s1 ^= u64::from_le_bytes(bytes[len - 8..].try_into().unwrap()); 262 | } else if len >= 4 { 263 | s0 ^= u32::from_le_bytes(bytes[0..4].try_into().unwrap()) as u64; 264 | s1 ^= u32::from_le_bytes(bytes[len - 4..].try_into().unwrap()) as u64; 265 | } else if len > 0 { 266 | let lo = bytes[0]; 267 | let mid = bytes[len / 2]; 268 | let hi = bytes[len - 1]; 269 | s0 ^= lo as u64; 270 | s1 ^= ((hi as u64) << 8) | mid as u64; 271 | } 272 | } else { 273 | // Handle bulk (can partially overlap with suffix). 274 | let mut off = 0; 275 | while off < len - 16 { 276 | let x = u64::from_le_bytes(bytes[off..off + 8].try_into().unwrap()); 277 | let y = u64::from_le_bytes(bytes[off + 8..off + 16].try_into().unwrap()); 278 | 279 | // Replace s1 with a mix of s0, x, and y, and s0 with s1. 280 | // This ensures the compiler can unroll this loop into two 281 | // independent streams, one operating on s0, the other on s1. 282 | // 283 | // Since zeroes are a common input we prevent an immediate trivial 284 | // collapse of the hash function by XOR'ing a constant with y. 285 | let t = multiply_mix(s0 ^ x, PREVENT_TRIVIAL_ZERO_COLLAPSE ^ y); 286 | s0 = s1; 287 | s1 = t; 288 | off += 16; 289 | } 290 | 291 | let suffix = &bytes[len - 16..]; 292 | s0 ^= u64::from_le_bytes(suffix[0..8].try_into().unwrap()); 293 | s1 ^= u64::from_le_bytes(suffix[8..16].try_into().unwrap()); 294 | } 295 | 296 | multiply_mix(s0, s1) ^ (len as u64) 297 | } 298 | 299 | /// An implementation of [`BuildHasher`] that produces [`FxHasher`]s. 300 | /// 301 | /// ``` 302 | /// use std::hash::BuildHasher; 303 | /// use rustc_hash::FxBuildHasher; 304 | /// assert_ne!(FxBuildHasher.hash_one(1), FxBuildHasher.hash_one(2)); 305 | /// ``` 306 | #[derive(Copy, Clone, Default)] 307 | pub struct FxBuildHasher; 308 | 309 | impl BuildHasher for FxBuildHasher { 310 | type Hasher = FxHasher; 311 | fn build_hasher(&self) -> FxHasher { 312 | FxHasher::default() 313 | } 314 | } 315 | 316 | #[cfg(test)] 317 | mod tests { 318 | #[cfg(not(any(target_pointer_width = "64", target_pointer_width = "32")))] 319 | compile_error!("The test suite only supports 64 bit and 32 bit usize"); 320 | 321 | use crate::{FxBuildHasher, FxHasher}; 322 | use core::hash::{BuildHasher, Hash, Hasher}; 323 | 324 | macro_rules! test_hash { 325 | ( 326 | $( 327 | hash($value:expr) == $result:expr, 328 | )* 329 | ) => { 330 | $( 331 | assert_eq!(FxBuildHasher.hash_one($value), $result); 332 | )* 333 | }; 334 | } 335 | 336 | const B32: bool = cfg!(target_pointer_width = "32"); 337 | 338 | #[test] 339 | fn unsigned() { 340 | test_hash! { 341 | hash(0_u8) == 0, 342 | hash(1_u8) == if B32 { 3001993707 } else { 12157901119326311915 }, 343 | hash(100_u8) == if B32 { 3844759569 } else { 16751747135202103309 }, 344 | hash(u8::MAX) == if B32 { 999399879 } else { 1211781028898739645 }, 345 | 346 | hash(0_u16) == 0, 347 | hash(1_u16) == if B32 { 3001993707 } else { 12157901119326311915 }, 348 | hash(100_u16) == if B32 { 3844759569 } else { 16751747135202103309 }, 349 | hash(u16::MAX) == if B32 { 3440503042 } else { 16279819243059860173 }, 350 | 351 | hash(0_u32) == 0, 352 | hash(1_u32) == if B32 { 3001993707 } else { 12157901119326311915 }, 353 | hash(100_u32) == if B32 { 3844759569 } else { 16751747135202103309 }, 354 | hash(u32::MAX) == if B32 { 1293006356 } else { 7729994835221066939 }, 355 | 356 | hash(0_u64) == 0, 357 | hash(1_u64) == if B32 { 275023839 } else { 12157901119326311915 }, 358 | hash(100_u64) == if B32 { 1732383522 } else { 16751747135202103309 }, 359 | hash(u64::MAX) == if B32 { 1017982517 } else { 6288842954450348564 }, 360 | 361 | hash(0_u128) == 0, 362 | hash(1_u128) == if B32 { 1860738631 } else { 13032756267696824044 }, 363 | hash(100_u128) == if B32 { 1389515751 } else { 12003541609544029302 }, 364 | hash(u128::MAX) == if B32 { 2156022013 } else { 11702830760530184999 }, 365 | 366 | hash(0_usize) == 0, 367 | hash(1_usize) == if B32 { 3001993707 } else { 12157901119326311915 }, 368 | hash(100_usize) == if B32 { 3844759569 } else { 16751747135202103309 }, 369 | hash(usize::MAX) == if B32 { 1293006356 } else { 6288842954450348564 }, 370 | } 371 | } 372 | 373 | #[test] 374 | fn signed() { 375 | test_hash! { 376 | hash(i8::MIN) == if B32 { 2000713177 } else { 6684841074112525780 }, 377 | hash(0_i8) == 0, 378 | hash(1_i8) == if B32 { 3001993707 } else { 12157901119326311915 }, 379 | hash(100_i8) == if B32 { 3844759569 } else { 16751747135202103309 }, 380 | hash(i8::MAX) == if B32 { 3293686765 } else { 12973684028562874344 }, 381 | 382 | hash(i16::MIN) == if B32 { 1073764727 } else { 14218860181193086044 }, 383 | hash(0_i16) == 0, 384 | hash(1_i16) == if B32 { 3001993707 } else { 12157901119326311915 }, 385 | hash(100_i16) == if B32 { 3844759569 } else { 16751747135202103309 }, 386 | hash(i16::MAX) == if B32 { 2366738315 } else { 2060959061933882993 }, 387 | 388 | hash(i32::MIN) == if B32 { 16384 } else { 9943947977240134995 }, 389 | hash(0_i32) == 0, 390 | hash(1_i32) == if B32 { 3001993707 } else { 12157901119326311915 }, 391 | hash(100_i32) == if B32 { 3844759569 } else { 16751747135202103309 }, 392 | hash(i32::MAX) == if B32 { 1293022740 } else { 16232790931690483559 }, 393 | 394 | hash(i64::MIN) == if B32 { 16384 } else { 33554432 }, 395 | hash(0_i64) == 0, 396 | hash(1_i64) == if B32 { 275023839 } else { 12157901119326311915 }, 397 | hash(100_i64) == if B32 { 1732383522 } else { 16751747135202103309 }, 398 | hash(i64::MAX) == if B32 { 1017998901 } else { 6288842954483902996 }, 399 | 400 | hash(i128::MIN) == if B32 { 16384 } else { 33554432 }, 401 | hash(0_i128) == 0, 402 | hash(1_i128) == if B32 { 1860738631 } else { 13032756267696824044 }, 403 | hash(100_i128) == if B32 { 1389515751 } else { 12003541609544029302 }, 404 | hash(i128::MAX) == if B32 { 2156005629 } else { 11702830760496630567 }, 405 | 406 | hash(isize::MIN) == if B32 { 16384 } else { 33554432 }, 407 | hash(0_isize) == 0, 408 | hash(1_isize) == if B32 { 3001993707 } else { 12157901119326311915 }, 409 | hash(100_isize) == if B32 { 3844759569 } else { 16751747135202103309 }, 410 | hash(isize::MAX) == if B32 { 1293022740 } else { 6288842954483902996 }, 411 | } 412 | } 413 | 414 | // Avoid relying on any `Hash` implementations in the standard library. 415 | struct HashBytes(&'static [u8]); 416 | impl Hash for HashBytes { 417 | fn hash(&self, state: &mut H) { 418 | state.write(self.0); 419 | } 420 | } 421 | 422 | #[test] 423 | fn bytes() { 424 | test_hash! { 425 | hash(HashBytes(&[])) == if B32 { 2673204745 } else { 17606491139363777937 }, 426 | hash(HashBytes(&[0])) == if B32 { 2948228584 } else { 5448590020104574886 }, 427 | hash(HashBytes(&[0, 0, 0, 0, 0, 0])) == if B32 { 3223252423 } else { 16766921560080789783 }, 428 | hash(HashBytes(&[1])) == if B32 { 2943445104 } else { 5922447956811044110 }, 429 | hash(HashBytes(&[2])) == if B32 { 1055423297 } else { 5229781508510959783 }, 430 | hash(HashBytes(b"uwu")) == if B32 { 2699662140 } else { 7168164714682931527 }, 431 | hash(HashBytes(b"These are some bytes for testing rustc_hash.")) == if B32 { 2303640537 } else { 2349210501944688211 }, 432 | } 433 | } 434 | 435 | #[test] 436 | fn with_seed_actually_different() { 437 | let seeds = [ 438 | [1, 2], 439 | [42, 17], 440 | [124436707, 99237], 441 | [usize::MIN, usize::MAX], 442 | ]; 443 | 444 | for [a_seed, b_seed] in seeds { 445 | let a = || FxHasher::with_seed(a_seed); 446 | let b = || FxHasher::with_seed(b_seed); 447 | 448 | for x in u8::MIN..=u8::MAX { 449 | let mut a = a(); 450 | let mut b = b(); 451 | 452 | x.hash(&mut a); 453 | x.hash(&mut b); 454 | 455 | assert_ne!(a.finish(), b.finish()) 456 | } 457 | } 458 | } 459 | } 460 | -------------------------------------------------------------------------------- /src/random_state.rs: -------------------------------------------------------------------------------- 1 | use std::collections::{HashMap, HashSet}; 2 | 3 | use crate::FxHasher; 4 | 5 | /// Type alias for a hashmap using the `fx` hash algorithm with [`FxRandomState`]. 6 | pub type FxHashMapRand = HashMap; 7 | 8 | /// Type alias for a hashmap using the `fx` hash algorithm with [`FxRandomState`]. 9 | pub type FxHashSetRand = HashSet; 10 | 11 | /// `FxRandomState` is an alternative state for `HashMap` types. 12 | /// 13 | /// A particular instance `FxRandomState` will create the same instances of 14 | /// [`Hasher`], but the hashers created by two different `FxRandomState` 15 | /// instances are unlikely to produce the same result for the same values. 16 | #[derive(Clone)] 17 | pub struct FxRandomState { 18 | seed: usize, 19 | } 20 | 21 | impl FxRandomState { 22 | /// Constructs a new `FxRandomState` that is initialized with random seed. 23 | pub fn new() -> FxRandomState { 24 | use rand::Rng; 25 | use std::{cell::Cell, thread_local}; 26 | 27 | // This mirrors what `std::collections::hash_map::RandomState` does, as of 2024-01-14. 28 | // 29 | // Basically 30 | // 1. Cache result of the rng in a thread local, so repeatedly 31 | // creating maps is cheaper 32 | // 2. Change the cached result on every creation, so maps created 33 | // on the same thread don't have the same iteration order 34 | thread_local!(static SEED: Cell = { 35 | Cell::new(rand::thread_rng().gen()) 36 | }); 37 | 38 | SEED.with(|seed| { 39 | let s = seed.get(); 40 | seed.set(s.wrapping_add(1)); 41 | FxRandomState { seed: s } 42 | }) 43 | } 44 | } 45 | 46 | impl core::hash::BuildHasher for FxRandomState { 47 | type Hasher = FxHasher; 48 | 49 | fn build_hasher(&self) -> Self::Hasher { 50 | FxHasher::with_seed(self.seed) 51 | } 52 | } 53 | 54 | impl Default for FxRandomState { 55 | fn default() -> Self { 56 | Self::new() 57 | } 58 | } 59 | 60 | #[cfg(test)] 61 | mod tests { 62 | use std::thread; 63 | 64 | use crate::FxHashMapRand; 65 | 66 | #[test] 67 | fn cloned_random_states_are_equal() { 68 | let a = FxHashMapRand::<&str, u32>::default(); 69 | let b = a.clone(); 70 | 71 | assert_eq!(a.hasher().seed, b.hasher().seed); 72 | } 73 | 74 | #[test] 75 | fn random_states_are_different() { 76 | let a = FxHashMapRand::<&str, u32>::default(); 77 | let b = FxHashMapRand::<&str, u32>::default(); 78 | 79 | // That's the whole point of them being random! 80 | // 81 | // N.B.: `FxRandomState` uses a thread-local set to a random value and then incremented, 82 | // which means that this is *guaranteed* to pass :> 83 | assert_ne!(a.hasher().seed, b.hasher().seed); 84 | } 85 | 86 | #[test] 87 | fn random_states_are_different_cross_thread() { 88 | // This is similar to the test above, but uses two different threads, so they both get 89 | // completely random, unrelated values. 90 | // 91 | // This means that this test is technically flaky, but the probability of it failing is 92 | // `1 / 2.pow(bit_size_of::())`. Or 1/1.7e19 for 64 bit platforms or 1/4294967295 93 | // for 32 bit platforms. I suppose this is acceptable. 94 | let a = FxHashMapRand::<&str, u32>::default(); 95 | let b = thread::spawn(|| FxHashMapRand::<&str, u32>::default()) 96 | .join() 97 | .unwrap(); 98 | 99 | assert_ne!(a.hasher().seed, b.hasher().seed); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/seeded_state.rs: -------------------------------------------------------------------------------- 1 | use crate::FxHasher; 2 | 3 | /// Type alias for a hashmap using the `fx` hash algorithm with [`FxSeededState`]. 4 | #[cfg(feature = "std")] 5 | pub type FxHashMapSeed = std::collections::HashMap; 6 | 7 | /// Type alias for a hashmap using the `fx` hash algorithm with [`FxSeededState`]. 8 | #[cfg(feature = "std")] 9 | pub type FxHashSetSeed = std::collections::HashSet; 10 | 11 | /// [`FxSeededState`] is an alternative state for `HashMap` types, allowing to use [`FxHasher`] with a set seed. 12 | /// 13 | /// ``` 14 | /// # use std::collections::HashMap; 15 | /// use rustc_hash::FxSeededState; 16 | /// 17 | /// let mut map = HashMap::with_hasher(FxSeededState::with_seed(12)); 18 | /// map.insert(15, 610); 19 | /// assert_eq!(map[&15], 610); 20 | /// ``` 21 | #[derive(Clone)] 22 | pub struct FxSeededState { 23 | seed: usize, 24 | } 25 | 26 | impl FxSeededState { 27 | /// Constructs a new `FxSeededState` that is initialized with a `seed`. 28 | pub const fn with_seed(seed: usize) -> FxSeededState { 29 | Self { seed } 30 | } 31 | } 32 | 33 | impl core::hash::BuildHasher for FxSeededState { 34 | type Hasher = FxHasher; 35 | 36 | fn build_hasher(&self) -> Self::Hasher { 37 | FxHasher::with_seed(self.seed) 38 | } 39 | } 40 | 41 | #[cfg(test)] 42 | mod tests { 43 | use core::hash::BuildHasher; 44 | 45 | use crate::FxSeededState; 46 | 47 | #[test] 48 | fn cloned_seeded_states_are_equal() { 49 | let seed = 2; 50 | let a = FxSeededState::with_seed(seed); 51 | let b = a.clone(); 52 | 53 | assert_eq!(a.seed, b.seed); 54 | assert_eq!(a.seed, seed); 55 | 56 | assert_eq!(a.build_hasher().hash, b.build_hasher().hash); 57 | } 58 | 59 | #[test] 60 | fn same_seed_produces_same_hasher() { 61 | let seed = 1; 62 | let a = FxSeededState::with_seed(seed); 63 | let b = FxSeededState::with_seed(seed); 64 | 65 | // The hashers should be the same, as they have the same seed. 66 | assert_eq!(a.build_hasher().hash, b.build_hasher().hash); 67 | } 68 | 69 | #[test] 70 | fn different_states_are_different() { 71 | let a = FxSeededState::with_seed(1); 72 | let b = FxSeededState::with_seed(2); 73 | 74 | assert_ne!(a.build_hasher().hash, b.build_hasher().hash); 75 | } 76 | } 77 | --------------------------------------------------------------------------------