Skip to content

Commit 25d45d4

Browse files
committed
feat: add indexmap_with_hasher and indexset_with_hasher macros
1 parent b56f035 commit 25d45d4

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

src/macros.rs

+72
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,40 @@
1+
/// Create an [`IndexMap`][crate::IndexMap] from a list of key-value pairs and a custom hasher
2+
///
3+
/// ## Example
4+
///
5+
/// ```
6+
/// use indexmap::indexmap_with_hasher;
7+
/// use std::collections::hash_map::RandomState;
8+
///
9+
/// let map = indexmap_with_hasher!{
10+
/// RandomState;
11+
/// "a" => 1,
12+
/// "b" => 2,
13+
/// };
14+
/// assert_eq!(map["a"], 1);
15+
/// assert_eq!(map["b"], 2);
16+
/// assert_eq!(map.get("c"), None);
17+
///
18+
/// // "a" is the first key
19+
/// assert_eq!(map.keys().next(), Some(&"a"));
20+
/// ```
21+
#[macro_export]
22+
macro_rules! indexmap_with_hasher {
23+
($S:ty; $($key:expr => $value:expr,)+) => { $crate::indexmap_with_hasher!($S; $($key => $value),+) };
24+
($S:ty; $($key:expr => $value:expr),*) => {{
25+
const CAP: usize = <[()]>::len(&[$({ stringify!($key); }),*]);
26+
#[allow(unused_mut)]
27+
// Specify your custom S (must implement Default) as the hasher:
28+
let mut map = $crate::IndexMap::<_, _, $S>::with_capacity_and_hasher(CAP, <$S>::default());
29+
30+
$(
31+
map.insert($key, $value);
32+
)*
33+
34+
map
35+
}};
36+
}
37+
138
#[cfg(feature = "std")]
239
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
340
#[macro_export]
@@ -35,6 +72,41 @@ macro_rules! indexmap {
3572
};
3673
}
3774

75+
/// Create an [`IndexSet`][crate::IndexSet] from a list of key-value pairs and a custom hasher
76+
///
77+
/// ## Example
78+
///
79+
/// ```
80+
/// use indexmap::indexset_with_hasher;
81+
/// use std::collections::hash_map::RandomState;
82+
///
83+
/// let set = indexset_with_hasher!{
84+
/// RandomState;
85+
/// "a",
86+
/// "b",
87+
/// };
88+
/// assert!(set.contains("a"));
89+
/// assert!(set.contains("b"));
90+
/// assert!(!set.contains("c"));
91+
///
92+
/// // "a" is the first value
93+
/// assert_eq!(set.iter().next(), Some(&"a"));
94+
/// ```
95+
#[macro_export]
96+
macro_rules! indexset_with_hasher {
97+
($S:ty; $($value:expr,)+) => { $crate::indexset_with_hasher!($S; $($value),+) };
98+
($S:ty; $($value:expr),*) => {{
99+
const CAP: usize = <[()]>::len(&[$({ stringify!($value); }),*]);
100+
#[allow(unused_mut)]
101+
// Specify your custom S (must implement Default) as the hasher:
102+
let mut set = $crate::IndexSet::<_, $S>::with_capacity_and_hasher(CAP, <$S>::default());
103+
$(
104+
set.insert($value);
105+
)*
106+
set
107+
}};
108+
}
109+
38110
#[cfg(feature = "std")]
39111
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
40112
#[macro_export]

0 commit comments

Comments
 (0)