Skip to content

Commit a5bc09e

Browse files
committed
Merge pull request #19 from calebmer/macro
Add linear map convenience macro
2 parents d7b820c + 404750f commit a5bc09e

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

src/lib.rs

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -299,6 +299,41 @@ impl<K: Eq, V> Into<Vec<(K, V)>> for LinearMap<K, V> {
299299
}
300300
}
301301

302+
/// Creates a `LinearMap` from a list of key-value pairs. The created
303+
/// `LinearMap` has a capacity set to the number of entries provided.
304+
///
305+
/// ## Example
306+
///
307+
/// ```
308+
/// #[macro_use] extern crate linear_map;
309+
/// # fn main() {
310+
///
311+
/// let map = linear_map!{
312+
/// "a" => 1,
313+
/// "b" => 2,
314+
/// };
315+
/// assert_eq!(map["a"], 1);
316+
/// assert_eq!(map["b"], 2);
317+
/// assert_eq!(map.get("c"), None);
318+
/// # }
319+
/// ```
320+
#[macro_export]
321+
macro_rules! linear_map {
322+
(@single $($x:tt)*) => (());
323+
(@count $($rest:expr),*) => (<[()]>::len(&[$(linear_map!(@single $rest)),*]));
324+
($($key:expr => $value:expr,)+) => { linear_map!($($key => $value),+) };
325+
($($key:expr => $value:expr),*) => {
326+
{
327+
let _cap = linear_map!(@count $($key),*);
328+
let mut _map = $crate::LinearMap::with_capacity(_cap);
329+
$(
330+
_map.insert($key, $value);
331+
)*
332+
_map
333+
}
334+
};
335+
}
336+
302337
/// A view into a single occupied location in a LinearMap.
303338
pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
304339
map: &'a mut LinearMap<K, V>,
@@ -856,6 +891,28 @@ mod test {
856891
m1.remove(&'a');
857892
assert!(m1 != m2);
858893
}
894+
895+
#[test]
896+
fn test_macro() {
897+
let names = linear_map!{
898+
1 => "one",
899+
2 => "two",
900+
};
901+
assert_eq!(names.len(), 2);
902+
assert_eq!(names.capacity(), 2);
903+
assert_eq!(names[&1], "one");
904+
assert_eq!(names[&2], "two");
905+
assert_eq!(names.get(&3), None);
906+
907+
let empty: LinearMap<i32, i32> = linear_map!{};
908+
assert_eq!(empty.len(), 0);
909+
assert_eq!(empty.capacity(), 0);
910+
911+
let _nested_compiles = linear_map!{
912+
1 => linear_map!{0 => 1 + 2,},
913+
2 => linear_map!{1 => 1,},
914+
};
915+
}
859916
}
860917

861918
#[cfg(all(test, feature = "nightly"))]

0 commit comments

Comments
 (0)