defaultmap/
lib.rs

1//! It can be useful to not have to worry about missing keys in a map.
2//! If a key is requested that doesn't have a value a default value is simply returned.
3//! This is exactly what this library provides.
4//!
5//! ## Examples
6
7//! ### Counter
8//! A clear use case of this is when counting the unique elements in a list.
9//! Here you want to add one to the existing value in the map for that key.
10//! This is a problem for the first addition when there's no value for the key yet.
11//! With this library you can specify when creating the map that the default value should be zero.
12//!
13
14//! ```rust
15//! # use defaultmap::*;
16//!
17//! let nums = [1, 4, 3, 3, 4, 2, 4];
18//! let mut counts: DefaultHashMap<i32, i32> = defaulthashmap!();
19//! // DefaultHashMap::new() is equivalent.
20//!
21//! for num in nums.into_iter() {
22//!     counts[num] += 1;
23//! }
24//!
25//! println!("{:?}", counts);
26//! // DefaultHashMap { map: {1: 1, 3: 2, 2: 1, 4: 3}, default: 0 }
27//!
28//! # assert_eq!(1, counts[1]);
29//! # assert_eq!(1, counts[2]);
30//! # assert_eq!(2, counts[3]);
31//! # assert_eq!(3, counts[4]);
32//!
33//! ```
34//!
35
36//! ### Synonym lists
37//!
38//! Another way the default map can be used is using a map filled with other collections, such as a
39//! `Vec`, a `HashMap` or even another default map.
40//! Next follows some code to create a map where we start with tuples of synonyms and we end with a
41//! map that contains the list of synonyms for each word.
42//!
43//! ```rust
44//! # use defaultmap::*;
45//!
46//! let synonym_tuples = [
47//!     ("nice", "sweet"),
48//!     ("sweet", "candy"),
49//!     ("nice", "entertaining"),
50//!     ("nice", "good"),
51//!     ("entertaining", "absorbing"),
52//! ];
53//!
54//! let mut synonym_map: DefaultHashMap<&str, Vec<&str>> = defaulthashmap!();
55//! // DefaultHashMap::new() is equivalent.
56//!
57//! for (l, r) in synonym_tuples.into_iter() {
58//!     synonym_map[l].push(r);
59//!     synonym_map[r].push(l);
60//! }
61//!
62//! assert_eq!(synonym_map["good"], vec!["nice"]);
63//! assert_eq!(synonym_map["nice"], vec!["sweet", "entertaining", "good"]);
64//! assert_eq!(synonym_map["evil"], Vec::<&str>::new());
65//! ```
66
67#![cfg_attr(docsrs, feature(doc_auto_cfg))]
68#![cfg_attr(any(not(docsrs), ci), deny(rustdoc::all))]
69
70mod default_fn;
71
72pub use default_fn::DefaultFn;
73
74mod btreemap;
75mod hashmap;
76
77pub use btreemap::DefaultBTreeMap;
78pub use hashmap::DefaultHashMap;