Skip to main content

hashbrown/
lib.rs

1//! This crate is a Rust port of Google's high-performance [SwissTable] hash
2//! map, adapted to make it a drop-in replacement for Rust's standard `HashMap`
3//! and `HashSet` types.
4//!
5//! The original C++ version of [SwissTable] can be found [here], and this
6//! [CppCon talk] gives an overview of how the algorithm works.
7//!
8//! [SwissTable]: https://abseil.io/blog/20180927-swisstables
9//! [here]: https://github.com/abseil/abseil-cpp/blob/master/absl/container/internal/raw_hash_set.h
10//! [CppCon talk]: https://www.youtube.com/watch?v=ncHmEUmJZf4
11
12#![cfg_attr(not(doc), no_std)]
13#![cfg_attr(
14    feature = "nightly",
15    feature(
16        core_intrinsics,
17        dropck_eyepatch,
18        min_specialization,
19        trivial_clone,
20        extend_one,
21        strict_provenance_lints
22    )
23)]
24#![cfg_attr(feature = "nightly", warn(implicit_provenance_casts))]
25#![cfg_attr(feature = "rustc-dep-of-std", feature(rustc_attrs))]
26#![cfg_attr(feature = "nightly", expect(internal_features))]
27#![cfg_attr(
28    all(feature = "nightly", feature = "default-hasher"),
29    feature(hasher_prefixfree_extras)
30)]
31
32#[cfg(test)]
33#[macro_use]
34extern crate std;
35
36#[cfg_attr(test, macro_use)]
37#[cfg_attr(feature = "rustc-dep-of-std", allow(unused_extern_crates))]
38extern crate alloc as stdalloc;
39
40#[doc = include_str!("../README.md")]
41#[cfg(doctest)]
42pub struct ReadmeDoctests;
43
44#[macro_use]
45mod macros;
46
47mod alloc;
48mod control;
49mod hasher;
50mod raw;
51mod util;
52
53mod external_trait_impls;
54mod map;
55#[cfg(feature = "raw-entry")]
56mod raw_entry;
57#[cfg(feature = "rustc-internal-api")]
58mod rustc_entry;
59mod scopeguard;
60mod set;
61mod table;
62
63pub use crate::hasher::DefaultHashBuilder;
64#[cfg(feature = "default-hasher")]
65pub use crate::hasher::DefaultHasher;
66
67pub mod hash_map {
68    //! A hash map implemented with quadratic probing and SIMD lookup.
69    pub use crate::map::*;
70
71    #[cfg(feature = "rustc-internal-api")]
72    pub use crate::rustc_entry::*;
73
74    #[cfg(feature = "rayon")]
75    /// [rayon]-based parallel iterator types for hash maps.
76    /// You will rarely need to interact with it directly unless you have need
77    /// to name one of the iterator types.
78    ///
79    /// [rayon]: ::rayon
80    pub mod rayon {
81        pub use crate::external_trait_impls::rayon::map::*;
82    }
83}
84pub mod hash_set {
85    //! A hash set implemented as a `HashMap` where the value is `()`.
86    pub use crate::set::*;
87
88    #[cfg(feature = "rayon")]
89    /// [rayon]-based parallel iterator types for hash sets.
90    /// You will rarely need to interact with it directly unless you have need
91    /// to name one of the iterator types.
92    ///
93    /// [rayon]: ::rayon
94    pub mod rayon {
95        pub use crate::external_trait_impls::rayon::set::*;
96    }
97}
98pub mod hash_table {
99    //! A hash table implemented with quadratic probing and SIMD lookup.
100    pub use crate::table::*;
101
102    #[cfg(feature = "rayon")]
103    /// [rayon]-based parallel iterator types for hash tables.
104    /// You will rarely need to interact with it directly unless you have need
105    /// to name one of the iterator types.
106    ///
107    /// [rayon]: ::rayon
108    pub mod rayon {
109        pub use crate::external_trait_impls::rayon::table::*;
110    }
111}
112
113pub use crate::map::HashMap;
114pub use crate::set::HashSet;
115pub use crate::table::HashTable;
116
117#[cfg(feature = "equivalent")]
118pub use equivalent::Equivalent;
119
120// This is only used as a fallback when building as part of `std`.
121#[cfg(not(feature = "equivalent"))]
122/// Key equivalence trait.
123///
124/// This trait defines the function used to compare the input value with the
125/// map keys (or set values) during a lookup operation such as [`HashMap::get`]
126/// or [`HashSet::contains`].
127/// It is provided with a blanket implementation based on the
128/// [`Borrow`](core::borrow::Borrow) trait.
129///
130/// # Correctness
131///
132/// Equivalent values must hash to the same value.
133pub trait Equivalent<K: ?Sized> {
134    /// Checks if this value is equivalent to the given key.
135    ///
136    /// Returns `true` if both values are equivalent, and `false` otherwise.
137    ///
138    /// # Correctness
139    ///
140    /// When this function returns `true`, both `self` and `key` must hash to
141    /// the same value.
142    fn equivalent(&self, key: &K) -> bool;
143}
144
145#[cfg(not(feature = "equivalent"))]
146impl<Q: ?Sized, K: ?Sized> Equivalent<K> for Q
147where
148    Q: Eq,
149    K: core::borrow::Borrow<Q>,
150{
151    fn equivalent(&self, key: &K) -> bool {
152        self == key.borrow()
153    }
154}
155
156/// The error type for `try_reserve` methods.
157#[derive(Clone, PartialEq, Eq, Debug)]
158pub enum TryReserveError {
159    /// Error due to the computed capacity exceeding the collection's maximum
160    /// (usually `isize::MAX` bytes).
161    CapacityOverflow,
162
163    /// The memory allocator returned an error
164    AllocError {
165        /// The layout of the allocation request that failed.
166        layout: core::alloc::Layout,
167    },
168}
169
170// matches stdalloc::collections::TryReserveError
171impl core::fmt::Display for TryReserveError {
172    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
173        f.write_str("memory allocation failed")?;
174        let reason = match self {
175            TryReserveError::CapacityOverflow => {
176                " because the computed capacity exceeded the collection's maximum"
177            }
178            TryReserveError::AllocError { .. } => " because the memory allocator returned an error",
179        };
180        f.write_str(reason)
181    }
182}
183
184impl core::error::Error for TryReserveError {}