1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
use std::collections::btree_map;
use std::collections::BTreeMap;
#[derive(Debug)]
pub struct LazyBTreeMap<K, V>(Option<BTreeMap<K, V>>);
impl<K, V> LazyBTreeMap<K, V> {
pub fn new() -> LazyBTreeMap<K, V> {
LazyBTreeMap(None)
}
pub fn iter(&self) -> Iter<K, V> {
Iter(self.0.as_ref().map(|btm| btm.iter()))
}
pub fn is_empty(&self) -> bool {
self.0.as_ref().map_or(true, |btm| btm.is_empty())
}
}
impl<K: Ord, V> LazyBTreeMap<K, V> {
fn instantiate(&mut self) -> &mut BTreeMap<K, V> {
if let Some(ref mut btm) = self.0 {
btm
} else {
let btm = BTreeMap::new();
self.0 = Some(btm);
self.0.as_mut().unwrap()
}
}
pub fn insert(&mut self, key: K, value: V) -> Option<V> {
self.instantiate().insert(key, value)
}
pub fn entry(&mut self, key: K) -> btree_map::Entry<K, V> {
self.instantiate().entry(key)
}
pub fn values<'a>(&'a self) -> Values<'a, K, V> {
Values(self.0.as_ref().map(|btm| btm.values()))
}
}
impl<K: Ord, V> Default for LazyBTreeMap<K, V> {
fn default() -> LazyBTreeMap<K, V> {
LazyBTreeMap::new()
}
}
impl<'a, K: 'a, V: 'a> IntoIterator for &'a LazyBTreeMap<K, V> {
type Item = (&'a K, &'a V);
type IntoIter = Iter<'a, K, V>;
fn into_iter(self) -> Iter<'a, K, V> {
self.iter()
}
}
pub struct Iter<'a, K: 'a, V: 'a>(Option<btree_map::Iter<'a, K, V>>);
impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
type Item = (&'a K, &'a V);
fn next(&mut self) -> Option<(&'a K, &'a V)> {
self.0.as_mut().and_then(|iter| iter.next())
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.as_ref().map_or_else(|| (0, Some(0)), |iter| iter.size_hint())
}
}
pub struct Values<'a, K: 'a, V: 'a>(Option<btree_map::Values<'a, K, V>>);
impl<'a, K, V> Iterator for Values<'a, K, V> {
type Item = &'a V;
fn next(&mut self) -> Option<&'a V> {
self.0.as_mut().and_then(|values| values.next())
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.as_ref().map_or_else(|| (0, Some(0)), |values| values.size_hint())
}
}