@@ -427,9 +427,29 @@ macro_rules! implement_as_any {
427
427
} ;
428
428
}
429
429
430
+ #[ macro_export( local_inner_macros) ]
431
+ macro_rules! hashmap {
432
+ ( ) => {
433
+ :: std:: collections:: HashMap :: new( )
434
+ } ;
435
+ ( $( $key: expr => $val: expr, ) +) => {
436
+ hashmap!( $( $key => $val) ,+)
437
+ } ;
438
+ ( $( $key: expr => $value: expr) ,+) => {
439
+ {
440
+ let mut _hm = :: std:: collections:: HashMap :: new( ) ;
441
+ $(
442
+ let _ = _hm. insert( $key, $value) ;
443
+ ) *
444
+ _hm
445
+ }
446
+ } ;
447
+ }
448
+
430
449
#[ cfg( test) ]
431
450
mod tests {
432
451
use super :: * ;
452
+ use std:: collections:: HashMap ;
433
453
use std:: env:: current_dir;
434
454
use std:: fmt:: Write ;
435
455
use std:: fs:: { create_dir_all, File , OpenOptions } ;
@@ -751,4 +771,37 @@ mod tests {
751
771
let result = type_name_of ( running_test) ;
752
772
assert_eq ! ( result, "masq_lib::utils::running_test" )
753
773
}
774
+
775
+ #[ test]
776
+ fn hashmap_macro_works ( ) {
777
+ let empty_hashmap: HashMap < i32 , i32 > = hashmap ! ( ) ;
778
+ let hashmap_with_one_element = hashmap ! ( 1 => 2 ) ;
779
+ let hashmap_with_multiple_elements = hashmap ! ( 1 => 2 , 10 => 20 , 12 => 42 ) ;
780
+ let hashmap_with_trailing_comma = hashmap ! ( 1 => 2 , 10 => 20 , ) ;
781
+ let hashmap_of_string = hashmap ! ( "key" => "val" ) ;
782
+
783
+ let expected_empty_hashmap: HashMap < i32 , i32 > = HashMap :: new ( ) ;
784
+ let mut expected_hashmap_with_one_element = HashMap :: new ( ) ;
785
+ expected_hashmap_with_one_element. insert ( 1 , 2 ) ;
786
+ let mut expected_hashmap_with_multiple_elements = HashMap :: new ( ) ;
787
+ expected_hashmap_with_multiple_elements. insert ( 1 , 2 ) ;
788
+ expected_hashmap_with_multiple_elements. insert ( 10 , 20 ) ;
789
+ expected_hashmap_with_multiple_elements. insert ( 12 , 42 ) ;
790
+ let mut expected_hashmap_with_trailing_comma = HashMap :: new ( ) ;
791
+ expected_hashmap_with_trailing_comma. insert ( 1 , 2 ) ;
792
+ expected_hashmap_with_trailing_comma. insert ( 10 , 20 ) ;
793
+ let mut expected_hashmap_of_string = HashMap :: new ( ) ;
794
+ expected_hashmap_of_string. insert ( "key" , "val" ) ;
795
+ assert_eq ! ( empty_hashmap, expected_empty_hashmap) ;
796
+ assert_eq ! ( hashmap_with_one_element, expected_hashmap_with_one_element) ;
797
+ assert_eq ! (
798
+ hashmap_with_multiple_elements,
799
+ expected_hashmap_with_multiple_elements
800
+ ) ;
801
+ assert_eq ! (
802
+ hashmap_with_trailing_comma,
803
+ expected_hashmap_with_trailing_comma
804
+ ) ;
805
+ assert_eq ! ( hashmap_of_string, expected_hashmap_of_string) ;
806
+ }
754
807
}
0 commit comments