rustc-hash-2.0.0/.cargo_vcs_info.json0000644000000001360000000000100131140ustar { "git": { "sha1": "8f258eec1f9e4a328fa0f7d370fcf7d51251ce96" }, "path_in_vcs": "" }rustc-hash-2.0.0/.github/workflows/rust.yml000064400000000000000000000007501046102023000170230ustar 00000000000000name: Rust on: [push, pull_request] jobs: build: runs-on: ${{ matrix.os }}-latest steps: - uses: actions/checkout@v4 - uses: rust-lang/simpleinfra/github-actions/simple-ci@master - name: "32-bit cross testing" run: | rustup toolchain install nightly rustup override set nightly rustup component add miri cargo +nightly miri test --target i686-unknown-linux-gnu strategy: matrix: os: [ubuntu, windows, macos] rustc-hash-2.0.0/.gitignore000064400000000000000000000000371046102023000136740ustar 00000000000000/target **/*.rs.bk /Cargo.lock rustc-hash-2.0.0/CHANGELOG.md000064400000000000000000000014311046102023000135140ustar 00000000000000## 2.0.0 - Replace hash with faster and better finalized hash. This replaces the previous "fxhash" algorithm originating in Firefox with a custom hasher designed and implemented by Orson Peters ([`@orlp`](https://github.com/orlp)). It was measured to have slightly better performance for rustc, has better theoretical properties and also includes a signficantly better string hasher. - Fix `no_std` builds ## 1.2.0 (**YANKED**) **Note: This version has been yanked due to issues with the `no_std` feature!** - Add a `FxBuildHasher` unit struct - Improve documentation - Add seed API for supplying custom seeds other than 0 - Add `FxRandomState` based on `rand` (behind the `rand` feature) for random seeds - Make many functions `const fn` - Implement `Clone` for `FxHasher` struct rustc-hash-2.0.0/CODE_OF_CONDUCT.md000064400000000000000000000002021046102023000144750ustar 00000000000000# The Rust Code of Conduct The Code of Conduct for this repository [can be found online](https://www.rust-lang.org/conduct.html).rustc-hash-2.0.0/Cargo.toml0000644000000017040000000000100111140ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" name = "rustc-hash" version = "2.0.0" authors = ["The Rust Project Developers"] description = "A speedy, non-cryptographic hashing algorithm used by rustc" readme = "README.md" keywords = [ "hash", "hasher", "fxhash", "rustc", ] license = "Apache-2.0/MIT" repository = "https://github.com/rust-lang/rustc-hash" [dependencies.rand] version = "0.8" optional = true [features] default = ["std"] nightly = [] rand = [ "dep:rand", "std", ] std = [] rustc-hash-2.0.0/Cargo.toml.orig000064400000000000000000000007321046102023000145750ustar 00000000000000[package] name = "rustc-hash" version = "2.0.0" authors = ["The Rust Project Developers"] description = "A speedy, non-cryptographic hashing algorithm used by rustc" license = "Apache-2.0/MIT" readme = "README.md" keywords = ["hash", "hasher", "fxhash", "rustc"] repository = "https://github.com/rust-lang/rustc-hash" edition = "2021" [features] default = ["std"] std = [] nightly = [] rand = ["dep:rand", "std"] [dependencies] rand = { version = "0.8", optional = true } rustc-hash-2.0.0/LICENSE-APACHE000064400000000000000000000227721046102023000136420ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONSrustc-hash-2.0.0/LICENSE-MIT000064400000000000000000000017761046102023000133530ustar 00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.rustc-hash-2.0.0/README.md000064400000000000000000000032361046102023000131670ustar 00000000000000# rustc-hash [![crates.io](https://img.shields.io/crates/v/rustc-hash.svg)](https://crates.io/crates/rustc-hash) [![Documentation](https://docs.rs/rustc-hash/badge.svg)](https://docs.rs/rustc-hash) A speedy, non-cryptographic hashing algorithm used by `rustc`. 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. These attacks aren't a concern in the compiler so we prefer to use a quicker, non-cryptographic hash algorithm. The original hash algorithm provided by this crate was one taken from Firefox, hence the hasher it provides is called FxHasher. This name is kept for backwards compatibility, but the underlying hash has since been replaced. The current design for the hasher is a polynomial hash finished with a single bit rotation, together with a wyhash-inspired compression function for strings/slices, both designed by Orson Peters. For `rustc` we have tried many different hashing algorithms. Hashing speed is critical, especially for single integers. Spending more CPU cycles on a higher quality hash does not reduce hash collisions enough to make the compiler faster on real-world benchmarks. ## Usage This crate provides `FxHashMap` and `FxHashSet` as collections. They are simply type aliases for their `std::collection` counterparts using the Fx hasher. ```rust use rustc_hash::FxHashMap; let mut map: FxHashMap = FxHashMap::default(); map.insert(22, 44); ``` ### `no_std` The `std` feature is on by default to enable collections. It can be turned off in `Cargo.toml` like so: ```toml rustc-hash = { version = "2.0", default-features = false } ``` rustc-hash-2.0.0/src/lib.rs000064400000000000000000000410521046102023000136110ustar 00000000000000//! A speedy, non-cryptographic hashing algorithm used by `rustc`. //! //! # Example //! //! ```rust //! # #[cfg(feature = "std")] //! # fn main() { //! use rustc_hash::FxHashMap; //! //! let mut map: FxHashMap = FxHashMap::default(); //! map.insert(22, 44); //! # } //! # #[cfg(not(feature = "std"))] //! # fn main() { } //! ``` #![no_std] #![cfg_attr(feature = "nightly", feature(hasher_prefixfree_extras))] #[cfg(feature = "std")] extern crate std; #[cfg(feature = "rand")] extern crate rand; #[cfg(feature = "rand")] mod random_state; mod seeded_state; use core::default::Default; use core::hash::{BuildHasher, Hasher}; #[cfg(feature = "std")] use std::collections::{HashMap, HashSet}; /// Type alias for a hash map that uses the Fx hashing algorithm. #[cfg(feature = "std")] pub type FxHashMap = HashMap; /// Type alias for a hash set that uses the Fx hashing algorithm. #[cfg(feature = "std")] pub type FxHashSet = HashSet; #[cfg(feature = "rand")] pub use random_state::{FxHashMapRand, FxHashSetRand, FxRandomState}; pub use seeded_state::FxSeededState; #[cfg(feature = "std")] pub use seeded_state::{FxHashMapSeed, FxHashSetSeed}; /// A speedy hash algorithm for use within rustc. The hashmap in liballoc /// by default uses SipHash which isn't quite as speedy as we want. In the /// compiler we're not really worried about DOS attempts, so we use a fast /// non-cryptographic hash. /// /// The current implementation is a fast polynomial hash with a single /// bit rotation as a finishing step designed by Orson Peters. #[derive(Clone)] pub struct FxHasher { hash: usize, } // One might view a polynomial hash // m[0] * k + m[1] * k^2 + m[2] * k^3 + ... // as a multilinear hash with keystream k[..] // m[0] * k[0] + m[1] * k[1] + m[2] * k[2] + ... // where keystream k just happens to be generated using a multiplicative // congrential pseudorandom number generator (MCG). For that reason we chose a // constant that was found to be good for a MCG in: // "Computationally Easy, Spectrally Good Multipliers for Congruential // Pseudorandom Number Generators" by Guy Steele and Sebastiano Vigna. #[cfg(target_pointer_width = "64")] const K: usize = 0xf1357aea2e62a9c5; #[cfg(target_pointer_width = "32")] const K: usize = 0x93d765dd; impl FxHasher { /// Creates a `fx` hasher with a given seed. pub const fn with_seed(seed: usize) -> FxHasher { FxHasher { hash: seed } } /// Creates a default `fx` hasher. pub const fn default() -> FxHasher { FxHasher { hash: 0 } } } impl Default for FxHasher { #[inline] fn default() -> FxHasher { Self::default() } } impl FxHasher { #[inline] fn add_to_hash(&mut self, i: usize) { self.hash = self.hash.wrapping_add(i).wrapping_mul(K); } } impl Hasher for FxHasher { #[inline] fn write(&mut self, bytes: &[u8]) { // Compress the byte string to a single u64 and add to our hash. self.write_u64(hash_bytes(bytes)); } #[inline] fn write_u8(&mut self, i: u8) { self.add_to_hash(i as usize); } #[inline] fn write_u16(&mut self, i: u16) { self.add_to_hash(i as usize); } #[inline] fn write_u32(&mut self, i: u32) { self.add_to_hash(i as usize); } #[inline] fn write_u64(&mut self, i: u64) { self.add_to_hash(i as usize); #[cfg(target_pointer_width = "32")] self.add_to_hash((i >> 32) as usize); } #[inline] fn write_u128(&mut self, i: u128) { self.add_to_hash(i as usize); #[cfg(target_pointer_width = "32")] self.add_to_hash((i >> 32) as usize); self.add_to_hash((i >> 64) as usize); #[cfg(target_pointer_width = "32")] self.add_to_hash((i >> 96) as usize); } #[inline] fn write_usize(&mut self, i: usize) { self.add_to_hash(i); } #[cfg(feature = "nightly")] #[inline] fn write_length_prefix(&mut self, _len: usize) { // Most cases will specialize hash_slice to call write(), which encodes // the length already in a more efficient manner than we could here. For // HashDoS-resistance you would still need to include this for the // non-slice collection hashes, but for the purposes of rustc we do not // care and do not wish to pay the performance penalty of mixing in len // for those collections. } #[cfg(feature = "nightly")] #[inline] fn write_str(&mut self, s: &str) { // Similarly here, write already encodes the length, so nothing special // is needed. self.write(s.as_bytes()) } #[inline] fn finish(&self) -> u64 { // Since we used a multiplicative hash our top bits have the most // entropy (with the top bit having the most, decreasing as you go). // As most hash table implementations (including hashbrown) compute // the bucket index from the bottom bits we want to move bits from the // top to the bottom. Ideally we'd rotate left by exactly the hash table // size, but as we don't know this we'll choose 20 bits, giving decent // entropy up until 2^20 table sizes. On 32-bit hosts we'll dial it // back down a bit to 15 bits. #[cfg(target_pointer_width = "64")] const ROTATE: u32 = 20; #[cfg(target_pointer_width = "32")] const ROTATE: u32 = 15; self.hash.rotate_left(ROTATE) as u64 // A bit reversal would be even better, except hashbrown also expects // good entropy in the top 7 bits and a bit reverse would fill those // bits with low entropy. More importantly, bit reversals are very slow // on x86-64. A byte reversal is relatively fast, but still has a 2 // cycle latency on x86-64 compared to the 1 cycle latency of a rotate. // It also suffers from the hashbrown-top-7-bit-issue. } } // Nothing special, digits of pi. const SEED1: u64 = 0x243f6a8885a308d3; const SEED2: u64 = 0x13198a2e03707344; const PREVENT_TRIVIAL_ZERO_COLLAPSE: u64 = 0xa4093822299f31d0; #[inline] fn multiply_mix(x: u64, y: u64) -> u64 { #[cfg(target_pointer_width = "64")] { // We compute the full u64 x u64 -> u128 product, this is a single mul // instruction on x86-64, one mul plus one mulhi on ARM64. let full = (x as u128) * (y as u128); let lo = full as u64; let hi = (full >> 64) as u64; // The middle bits of the full product fluctuate the most with small // changes in the input. This is the top bits of lo and the bottom bits // of hi. We can thus make the entire output fluctuate with small // changes to the input by XOR'ing these two halves. lo ^ hi // Unfortunately both 2^64 + 1 and 2^64 - 1 have small prime factors, // otherwise combining with + or - could result in a really strong hash, as: // x * y = 2^64 * hi + lo = (-1) * hi + lo = lo - hi, (mod 2^64 + 1) // x * y = 2^64 * hi + lo = 1 * hi + lo = lo + hi, (mod 2^64 - 1) // Multiplicative hashing is universal in a field (like mod p). } #[cfg(target_pointer_width = "32")] { // u64 x u64 -> u128 product is prohibitively expensive on 32-bit. // Decompose into 32-bit parts. let lx = x as u32; let ly = y as u32; let hx = (x >> 32) as u32; let hy = (y >> 32) as u32; // u32 x u32 -> u64 the low bits of one with the high bits of the other. let afull = (lx as u64) * (hy as u64); let bfull = (hx as u64) * (ly as u64); // Combine, swapping low/high of one of them so the upper bits of the // product of one combine with the lower bits of the other. afull ^ bfull.rotate_right(32) } } /// A wyhash-inspired non-collision-resistant hash for strings/slices designed /// by Orson Peters, with a focus on small strings and small codesize. /// /// The 64-bit version of this hash passes the SMHasher3 test suite on the full /// 64-bit output, that is, f(hash_bytes(b) ^ f(seed)) for some good avalanching /// permutation f() passed all tests with zero failures. When using the 32-bit /// version of multiply_mix this hash has a few non-catastrophic failures where /// there are a handful more collisions than an optimal hash would give. /// /// We don't bother avalanching here as we'll feed this hash into a /// multiplication after which we take the high bits, which avalanches for us. #[inline] fn hash_bytes(bytes: &[u8]) -> u64 { let len = bytes.len(); let mut s0 = SEED1; let mut s1 = SEED2; if len <= 16 { // XOR the input into s0, s1. if len >= 8 { s0 ^= u64::from_le_bytes(bytes[0..8].try_into().unwrap()); s1 ^= u64::from_le_bytes(bytes[len - 8..].try_into().unwrap()); } else if len >= 4 { s0 ^= u32::from_le_bytes(bytes[0..4].try_into().unwrap()) as u64; s1 ^= u32::from_le_bytes(bytes[len - 4..].try_into().unwrap()) as u64; } else if len > 0 { let lo = bytes[0]; let mid = bytes[len / 2]; let hi = bytes[len - 1]; s0 ^= lo as u64; s1 ^= ((hi as u64) << 8) | mid as u64; } } else { // Handle bulk (can partially overlap with suffix). let mut off = 0; while off < len - 16 { let x = u64::from_le_bytes(bytes[off..off + 8].try_into().unwrap()); let y = u64::from_le_bytes(bytes[off + 8..off + 16].try_into().unwrap()); // Replace s1 with a mix of s0, x, and y, and s0 with s1. // This ensures the compiler can unroll this loop into two // independent streams, one operating on s0, the other on s1. // // Since zeroes are a common input we prevent an immediate trivial // collapse of the hash function by XOR'ing a constant with y. let t = multiply_mix(s0 ^ x, PREVENT_TRIVIAL_ZERO_COLLAPSE ^ y); s0 = s1; s1 = t; off += 16; } let suffix = &bytes[len - 16..]; s0 ^= u64::from_le_bytes(suffix[0..8].try_into().unwrap()); s1 ^= u64::from_le_bytes(suffix[8..16].try_into().unwrap()); } multiply_mix(s0, s1) ^ (len as u64) } /// An implementation of [`BuildHasher`] that produces [`FxHasher`]s. /// /// ``` /// use std::hash::BuildHasher; /// use rustc_hash::FxBuildHasher; /// assert_ne!(FxBuildHasher.hash_one(1), FxBuildHasher.hash_one(2)); /// ``` #[derive(Copy, Clone, Default)] pub struct FxBuildHasher; impl BuildHasher for FxBuildHasher { type Hasher = FxHasher; fn build_hasher(&self) -> FxHasher { FxHasher::default() } } #[cfg(test)] mod tests { #[cfg(not(any(target_pointer_width = "64", target_pointer_width = "32")))] compile_error!("The test suite only supports 64 bit and 32 bit usize"); use crate::{FxBuildHasher, FxHasher}; use core::hash::{BuildHasher, Hash, Hasher}; macro_rules! test_hash { ( $( hash($value:expr) == $result:expr, )* ) => { $( assert_eq!(FxBuildHasher.hash_one($value), $result); )* }; } const B32: bool = cfg!(target_pointer_width = "32"); #[test] fn unsigned() { test_hash! { hash(0_u8) == 0, hash(1_u8) == if B32 { 3001993707 } else { 12583873379513078615 }, hash(100_u8) == if B32 { 3844759569 } else { 4008740938959785536 }, hash(u8::MAX) == if B32 { 999399879 } else { 17600987023830959190 }, hash(0_u16) == 0, hash(1_u16) == if B32 { 3001993707 } else { 12583873379513078615 }, hash(100_u16) == if B32 { 3844759569 } else { 4008740938959785536 }, hash(u16::MAX) == if B32 { 3440503042 } else { 4001367065645062987 }, hash(0_u32) == 0, hash(1_u32) == if B32 { 3001993707 } else { 12583873379513078615 }, hash(100_u32) == if B32 { 3844759569 } else { 4008740938959785536 }, hash(u32::MAX) == if B32 { 1293006356 } else { 17126373362251322066 }, hash(0_u64) == 0, hash(1_u64) == if B32 { 275023839 } else { 12583873379513078615 }, hash(100_u64) == if B32 { 1732383522 } else { 4008740938959785536 }, hash(u64::MAX) == if B32 { 1017982517 } else { 5862870694197521576 }, hash(0_u128) == 0, hash(1_u128) == if B32 { 1860738631 } else { 12885773367358079611 }, hash(100_u128) == if B32 { 1389515751 } else { 15751995649841559633 }, hash(u128::MAX) == if B32 { 2156022013 } else { 11423841400550042156 }, hash(0_usize) == 0, hash(1_usize) == if B32 { 3001993707 } else { 12583873379513078615 }, hash(100_usize) == if B32 { 3844759569 } else { 4008740938959785536 }, hash(usize::MAX) == if B32 { 1293006356 } else { 5862870694197521576 }, } } #[test] fn signed() { test_hash! { hash(i8::MIN) == if B32 { 2000713177 } else { 5869058164817243095 }, hash(0_i8) == 0, hash(1_i8) == if B32 { 3001993707 } else { 12583873379513078615 }, hash(100_i8) == if B32 { 3844759569 } else { 4008740938959785536 }, hash(i8::MAX) == if B32 { 3293686765 } else { 11731928859014764671 }, hash(i16::MIN) == if B32 { 1073764727 } else { 8292620222579070801 }, hash(0_i16) == 0, hash(1_i16) == if B32 { 3001993707 } else { 12583873379513078615 }, hash(100_i16) == if B32 { 3844759569 } else { 4008740938959785536 }, hash(i16::MAX) == if B32 { 2366738315 } else { 14155490916776592377 }, hash(i32::MIN) == if B32 { 16384 } else { 5631751334026900245 }, hash(0_i32) == 0, hash(1_i32) == if B32 { 3001993707 } else { 12583873379513078615 }, hash(100_i32) == if B32 { 3844759569 } else { 4008740938959785536 }, hash(i32::MAX) == if B32 { 1293022740 } else { 11494622028224421821 }, hash(i64::MIN) == if B32 { 16384 } else { 524288 }, hash(0_i64) == 0, hash(1_i64) == if B32 { 275023839 } else { 12583873379513078615 }, hash(100_i64) == if B32 { 1732383522 } else { 4008740938959785536 }, hash(i64::MAX) == if B32 { 1017998901 } else { 5862870694198045864 }, hash(i128::MIN) == if B32 { 16384 } else { 524288 }, hash(0_i128) == 0, hash(1_i128) == if B32 { 1860738631 } else { 12885773367358079611 }, hash(100_i128) == if B32 { 1389515751 } else { 15751995649841559633 }, hash(i128::MAX) == if B32 { 2156005629 } else { 11423841400549517868 }, hash(isize::MIN) == if B32 { 16384 } else { 524288 }, hash(0_isize) == 0, hash(1_isize) == if B32 { 3001993707 } else { 12583873379513078615 }, hash(100_isize) == if B32 { 3844759569 } else { 4008740938959785536 }, hash(isize::MAX) == if B32 { 1293022740 } else { 5862870694198045864 }, } } // Avoid relying on any `Hash` implementations in the standard library. struct HashBytes(&'static [u8]); impl Hash for HashBytes { fn hash(&self, state: &mut H) { state.write(self.0); } } #[test] fn bytes() { test_hash! { hash(HashBytes(&[])) == if B32 { 2673204745 } else { 5175017818631658678 }, hash(HashBytes(&[0])) == if B32 { 2948228584 } else { 11037888512829180254 }, hash(HashBytes(&[0, 0, 0, 0, 0, 0])) == if B32 { 3223252423 } else { 6891281800865632452 }, hash(HashBytes(&[1])) == if B32 { 2943445104 } else { 4127763515449136980 }, hash(HashBytes(&[2])) == if B32 { 1055423297 } else { 11322700005987241762 }, hash(HashBytes(b"uwu")) == if B32 { 2699662140 } else { 2129615206728903013 }, hash(HashBytes(b"These are some bytes for testing rustc_hash.")) == if B32 { 2303640537 } else { 5513083560975408889 }, } } #[test] fn with_seed_actually_different() { let seeds = [ [1, 2], [42, 17], [124436707, 99237], [usize::MIN, usize::MAX], ]; for [a_seed, b_seed] in seeds { let a = || FxHasher::with_seed(a_seed); let b = || FxHasher::with_seed(b_seed); for x in u8::MIN..=u8::MAX { let mut a = a(); let mut b = b(); x.hash(&mut a); x.hash(&mut b); assert_ne!(a.finish(), b.finish()) } } } } rustc-hash-2.0.0/src/random_state.rs000064400000000000000000000057421046102023000155310ustar 00000000000000use std::collections::{HashMap, HashSet}; use crate::FxHasher; /// Type alias for a hashmap using the `fx` hash algorithm with [`FxRandomState`]. pub type FxHashMapRand = HashMap; /// Type alias for a hashmap using the `fx` hash algorithm with [`FxRandomState`]. pub type FxHashSetRand = HashSet; /// `FxRandomState` is an alternative state for `HashMap` types. /// /// A particular instance `FxRandomState` will create the same instances of /// [`Hasher`], but the hashers created by two different `FxRandomState` /// instances are unlikely to produce the same result for the same values. pub struct FxRandomState { seed: usize, } impl FxRandomState { /// Constructs a new `FxRandomState` that is initialized with random seed. pub fn new() -> FxRandomState { use rand::Rng; use std::{cell::Cell, thread_local}; // This mirrors what `std::collections::hash_map::RandomState` does, as of 2024-01-14. // // Basically // 1. Cache result of the rng in a thread local, so repeatedly // creating maps is cheaper // 2. Change the cached result on every creation, so maps created // on the same thread don't have the same iteration order thread_local!(static SEED: Cell = { Cell::new(rand::thread_rng().gen()) }); SEED.with(|seed| { let s = seed.get(); seed.set(s.wrapping_add(1)); FxRandomState { seed: s } }) } } impl core::hash::BuildHasher for FxRandomState { type Hasher = FxHasher; fn build_hasher(&self) -> Self::Hasher { FxHasher::with_seed(self.seed) } } impl Default for FxRandomState { fn default() -> Self { Self::new() } } #[cfg(test)] mod tests { use std::thread; use crate::FxHashMapRand; #[test] fn random_states_are_different() { let a = FxHashMapRand::<&str, u32>::default(); let b = FxHashMapRand::<&str, u32>::default(); // That's the whole point of them being random! // // N.B.: `FxRandomState` uses a thread-local set to a random value and then incremented, // which means that this is *guaranteed* to pass :> assert_ne!(a.hasher().seed, b.hasher().seed); } #[test] fn random_states_are_different_cross_thread() { // This is similar to the test above, but uses two different threads, so they both get // completely random, unrelated values. // // This means that this test is technically flaky, but the probability of it failing is // `1 / 2.pow(bit_size_of::())`. Or 1/1.7e19 for 64 bit platforms or 1/4294967295 // for 32 bit platforms. I suppose this is acceptable. let a = FxHashMapRand::<&str, u32>::default(); let b = thread::spawn(|| FxHashMapRand::<&str, u32>::default()) .join() .unwrap(); assert_ne!(a.hasher().seed, b.hasher().seed); } } rustc-hash-2.0.0/src/seeded_state.rs000064400000000000000000000026341046102023000154770ustar 00000000000000use crate::FxHasher; /// Type alias for a hashmap using the `fx` hash algorithm with [`FxSeededState`]. #[cfg(feature = "std")] pub type FxHashMapSeed = std::collections::HashMap; /// Type alias for a hashmap using the `fx` hash algorithm with [`FxSeededState`]. #[cfg(feature = "std")] pub type FxHashSetSeed = std::collections::HashSet; /// [`FxSetState`] is an alternative state for `HashMap` types, allowing to use [`FxHasher`] with a set seed. /// /// ``` /// # use std::collections::HashMap; /// use rustc_hash::FxSeededState; /// /// let mut map = HashMap::with_hasher(FxSeededState::with_seed(12)); /// map.insert(15, 610); /// assert_eq!(map[&15], 610); /// ``` pub struct FxSeededState { seed: usize, } impl FxSeededState { /// Constructs a new `FxSeededState` that is initialized with a `seed`. pub const fn with_seed(seed: usize) -> FxSeededState { Self { seed } } } impl core::hash::BuildHasher for FxSeededState { type Hasher = FxHasher; fn build_hasher(&self) -> Self::Hasher { FxHasher::with_seed(self.seed) } } #[cfg(test)] mod tests { use core::hash::BuildHasher; use crate::FxSeededState; #[test] fn different_states_are_different() { let a = FxSeededState::with_seed(1); let b = FxSeededState::with_seed(2); assert_ne!(a.build_hasher().hash, b.build_hasher().hash); } }