Skip to content

Commit c94b22b

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

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

src/macros.rs

+70
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,38 @@
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+
map.insert($key, $value);
31+
)*
32+
map
33+
}};
34+
}
35+
136
#[cfg(feature = "std")]
237
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
338
#[macro_export]
@@ -35,6 +70,41 @@ macro_rules! indexmap {
3570
};
3671
}
3772

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

0 commit comments

Comments
 (0)