Coverage Report

Created: 2026-01-25 06:52

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