indexmap/lib.rs
1// We *mostly* avoid unsafe code, but `Slice` allows it for DST casting.
2#![deny(unsafe_code)]
3#![warn(rust_2018_idioms)]
4#![no_std]
5
6//! [`IndexMap`] is a hash table where the iteration order of the key-value
7//! pairs is independent of the hash values of the keys.
8//!
9//! [`IndexSet`] is a corresponding hash set using the same implementation and
10//! with similar properties.
11//!
12//! ### Highlights
13//!
14//! [`IndexMap`] and [`IndexSet`] are drop-in compatible with the std `HashMap`
15//! and `HashSet`, but they also have some features of note:
16//!
17//! - The ordering semantics (see their documentation for details)
18//! - Sorting methods and the [`.pop()`][IndexMap::pop] methods.
19//! - The [`Equivalent`] trait, which offers more flexible equality definitions
20//! between borrowed and owned versions of keys.
21//! - The [`MutableKeys`][map::MutableKeys] trait, which gives opt-in mutable
22//! access to map keys, and [`MutableValues`][set::MutableValues] for sets.
23//!
24//! ### Feature Flags
25//!
26//! To reduce the amount of compiled code in the crate by default, certain
27//! features are gated behind [feature flags]. These allow you to opt in to (or
28//! out of) functionality. Below is a list of the features available in this
29//! crate.
30//!
31//! * `std`: Enables features which require the Rust standard library. For more
32//! information see the section on [`no_std`].
33//! * `rayon`: Enables parallel iteration and other parallel methods.
34//! * `serde`: Adds implementations for [`Serialize`] and [`Deserialize`]
35//! to [`IndexMap`] and [`IndexSet`]. Alternative implementations for
36//! (de)serializing [`IndexMap`] as an ordered sequence are available in the
37//! [`map::serde_seq`] module.
38//! * `borsh`: Adds implementations for [`BorshSerialize`] and [`BorshDeserialize`]
39//! to [`IndexMap`] and [`IndexSet`]. **Note:** When this feature is enabled,
40//! you cannot enable the `derive` feature of [`borsh`] due to a cyclic
41//! dependency. Instead, add the `borsh-derive` crate as an explicit
42//! dependency in your Cargo.toml and import as e.g.
43//! `use borsh_derive::{BorshSerialize, BorshDeserialize};`.
44//! * `arbitrary`: Adds implementations for the [`arbitrary::Arbitrary`] trait
45//! to [`IndexMap`] and [`IndexSet`].
46//! * `quickcheck`: Adds implementations for the [`quickcheck::Arbitrary`] trait
47//! to [`IndexMap`] and [`IndexSet`].
48//!
49//! _Note: only the `std` feature is enabled by default._
50//!
51//! [feature flags]: https://doc.rust-lang.org/cargo/reference/manifest.html#the-features-section
52//! [`no_std`]: #no-standard-library-targets
53//! [`Serialize`]: `::serde::Serialize`
54//! [`Deserialize`]: `::serde::Deserialize`
55//! [`BorshSerialize`]: `::borsh::BorshSerialize`
56//! [`BorshDeserialize`]: `::borsh::BorshDeserialize`
57//! [`borsh`]: `::borsh`
58//! [`arbitrary::Arbitrary`]: `::arbitrary::Arbitrary`
59//! [`quickcheck::Arbitrary`]: `::quickcheck::Arbitrary`
60//!
61//! ### Alternate Hashers
62//!
63//! [`IndexMap`] and [`IndexSet`] have a default hasher type
64//! [`S = RandomState`][std::collections::hash_map::RandomState],
65//! just like the standard `HashMap` and `HashSet`, which is resistant to
66//! HashDoS attacks but not the most performant. Type aliases can make it easier
67//! to use alternate hashers:
68//!
69//! ```
70//! use fnv::FnvBuildHasher;
71//! use indexmap::{IndexMap, IndexSet};
72//!
73//! type FnvIndexMap<K, V> = IndexMap<K, V, FnvBuildHasher>;
74//! type FnvIndexSet<T> = IndexSet<T, FnvBuildHasher>;
75//!
76//! let std: IndexSet<i32> = (0..100).collect();
77//! let fnv: FnvIndexSet<i32> = (0..100).collect();
78//! assert_eq!(std, fnv);
79//! ```
80//!
81//! ### Rust Version
82//!
83//! This version of indexmap requires Rust 1.63 or later.
84//!
85//! The indexmap 2.x release series will use a carefully considered version
86//! upgrade policy, where in a later 2.x version, we will raise the minimum
87//! required Rust version.
88//!
89//! ## No Standard Library Targets
90//!
91//! This crate supports being built without `std`, requiring `alloc` instead.
92//! This is chosen by disabling the default "std" cargo feature, by adding
93//! `default-features = false` to your dependency specification.
94//!
95//! - Creating maps and sets using [`new`][IndexMap::new] and
96//! [`with_capacity`][IndexMap::with_capacity] is unavailable without `std`.
97//! Use methods [`IndexMap::default`], [`with_hasher`][IndexMap::with_hasher],
98//! [`with_capacity_and_hasher`][IndexMap::with_capacity_and_hasher] instead.
99//! A no-std compatible hasher will be needed as well, for example
100//! from the crate `twox-hash`.
101//! - Macros [`indexmap!`] and [`indexset!`] are unavailable without `std`.
102
103#![cfg_attr(docsrs, feature(doc_cfg))]
104
105extern crate alloc;
106
107#[cfg(feature = "std")]
108#[macro_use]
109extern crate std;
110
111use alloc::vec::{self, Vec};
112
113mod arbitrary;
114#[macro_use]
115mod macros;
116#[cfg(feature = "borsh")]
117mod borsh;
118#[cfg(feature = "serde")]
119mod serde;
120mod util;
121
122pub mod map;
123pub mod set;
124
125// Placed after `map` and `set` so new `rayon` methods on the types
126// are documented after the "normal" methods.
127#[cfg(feature = "rayon")]
128mod rayon;
129
130#[cfg(feature = "rustc-rayon")]
131mod rustc;
132
133pub use crate::map::IndexMap;
134pub use crate::set::IndexSet;
135pub use equivalent::Equivalent;
136
137// shared private items
138
139/// Hash value newtype. Not larger than usize, since anything larger
140/// isn't used for selecting position anyway.
141#[derive(Clone, Copy, Debug, PartialEq)]
142struct HashValue(usize);
143
144impl HashValue {
145 #[inline(always)]
146 fn get(self) -> u64 {
147 self.0 as u64
148 }
149}
150
151#[derive(Copy, Debug)]
152struct Bucket<K, V> {
153 hash: HashValue,
154 key: K,
155 value: V,
156}
157
158impl<K, V> Clone for Bucket<K, V>
159where
160 K: Clone,
161 V: Clone,
162{
163 fn clone(&self) -> Self {
164 Bucket {
165 hash: self.hash,
166 key: self.key.clone(),
167 value: self.value.clone(),
168 }
169 }
170
171 fn clone_from(&mut self, other: &Self) {
172 self.hash = other.hash;
173 self.key.clone_from(&other.key);
174 self.value.clone_from(&other.value);
175 }
176}
177
178impl<K, V> Bucket<K, V> {
179 // field accessors -- used for `f` instead of closures in `.map(f)`
180 fn key_ref(&self) -> &K {
181 &self.key
182 }
183 fn value_ref(&self) -> &V {
184 &self.value
185 }
186 fn value_mut(&mut self) -> &mut V {
187 &mut self.value
188 }
189 fn key(self) -> K {
190 self.key
191 }
192 fn value(self) -> V {
193 self.value
194 }
195 fn key_value(self) -> (K, V) {
196 (self.key, self.value)
197 }
198 fn refs(&self) -> (&K, &V) {
199 (&self.key, &self.value)
200 }
201 fn ref_mut(&mut self) -> (&K, &mut V) {
202 (&self.key, &mut self.value)
203 }
204 fn muts(&mut self) -> (&mut K, &mut V) {
205 (&mut self.key, &mut self.value)
206 }
207}
208
209trait Entries {
210 type Entry;
211 fn into_entries(self) -> Vec<Self::Entry>;
212 fn as_entries(&self) -> &[Self::Entry];
213 fn as_entries_mut(&mut self) -> &mut [Self::Entry];
214 fn with_entries<F>(&mut self, f: F)
215 where
216 F: FnOnce(&mut [Self::Entry]);
217}
218
219/// The error type for [`try_reserve`][IndexMap::try_reserve] methods.
220#[derive(Clone, PartialEq, Eq, Debug)]
221pub struct TryReserveError {
222 kind: TryReserveErrorKind,
223}
224
225#[derive(Clone, PartialEq, Eq, Debug)]
226enum TryReserveErrorKind {
227 // The standard library's kind is currently opaque to us, otherwise we could unify this.
228 Std(alloc::collections::TryReserveError),
229 CapacityOverflow,
230 AllocError { layout: alloc::alloc::Layout },
231}
232
233// These are not `From` so we don't expose them in our public API.
234impl TryReserveError {
235 fn from_alloc(error: alloc::collections::TryReserveError) -> Self {
236 Self {
237 kind: TryReserveErrorKind::Std(error),
238 }
239 }
240
241 fn from_hashbrown(error: hashbrown::TryReserveError) -> Self {
242 Self {
243 kind: match error {
244 hashbrown::TryReserveError::CapacityOverflow => {
245 TryReserveErrorKind::CapacityOverflow
246 }
247 hashbrown::TryReserveError::AllocError { layout } => {
248 TryReserveErrorKind::AllocError { layout }
249 }
250 },
251 }
252 }
253}
254
255impl core::fmt::Display for TryReserveError {
256 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
257 let reason = match &self.kind {
258 TryReserveErrorKind::Std(e) => return core::fmt::Display::fmt(e, f),
259 TryReserveErrorKind::CapacityOverflow => {
260 " because the computed capacity exceeded the collection's maximum"
261 }
262 TryReserveErrorKind::AllocError { .. } => {
263 " because the memory allocator returned an error"
264 }
265 };
266 f.write_str("memory allocation failed")?;
267 f.write_str(reason)
268 }
269}
270
271#[cfg(feature = "std")]
272#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
273impl std::error::Error for TryReserveError {}