|
| 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 | + |
1 | 36 | #[cfg(feature = "std")]
|
2 | 37 | #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
|
3 | 38 | #[macro_export]
|
@@ -35,6 +70,41 @@ macro_rules! indexmap {
|
35 | 70 | };
|
36 | 71 | }
|
37 | 72 |
|
| 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 | + |
38 | 108 | #[cfg(feature = "std")]
|
39 | 109 | #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
|
40 | 110 | #[macro_export]
|
|
0 commit comments