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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
use crate::storage::Storage;
use std::mem;

/// Storage types that can only inhabit a single value (like `()`).
pub struct SingletonStorage<V> {
    inner: Option<V>,
}

impl<V> Clone for SingletonStorage<V>
where
    V: Clone,
{
    #[inline]
    fn clone(&self) -> Self {
        SingletonStorage {
            inner: self.inner.clone(),
        }
    }
}

impl<V> Default for SingletonStorage<V> {
    #[inline]
    fn default() -> Self {
        Self {
            inner: Default::default(),
        }
    }
}

impl<V> PartialEq for SingletonStorage<V>
where
    V: PartialEq,
{
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.inner == other.inner
    }
}

impl<V> Eq for SingletonStorage<V> where V: Eq {}

pub struct Iter<'a, K, V> {
    value: Option<(K, &'a V)>,
}

impl<'a, K, V> Clone for Iter<'a, K, V>
where
    K: Copy,
{
    #[inline]
    fn clone(&self) -> Self {
        Iter { value: self.value }
    }
}

impl<'a, K, V> Iterator for Iter<'a, K, V> {
    type Item = (K, &'a V);

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.value.take()
    }
}

pub struct IterMut<'a, K, V> {
    value: Option<(K, &'a mut V)>,
}

impl<'a, K, V> Iterator for IterMut<'a, K, V> {
    type Item = (K, &'a mut V);

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.value.take()
    }
}

impl<K, V> Storage<K, V> for SingletonStorage<V>
where
    K: Copy + Default,
{
    type Iter<'this> = Iter<'this, K, V> where Self: 'this, V: 'this;
    type IterMut<'this> = IterMut<'this, K, V> where Self: 'this, V: 'this;

    #[inline]
    fn insert(&mut self, _: K, value: V) -> Option<V> {
        mem::replace(&mut self.inner, Some(value))
    }

    #[inline]
    fn get(&self, _: K) -> Option<&V> {
        self.inner.as_ref()
    }

    #[inline]
    fn get_mut(&mut self, _: K) -> Option<&mut V> {
        self.inner.as_mut()
    }

    #[inline]
    fn remove(&mut self, _: K) -> Option<V> {
        mem::replace(&mut self.inner, None)
    }

    #[inline]
    fn clear(&mut self) {
        self.inner = None;
    }

    #[inline]
    fn iter(&self) -> Self::Iter<'_> {
        Iter {
            value: self.inner.as_ref().map(|v| (K::default(), v)),
        }
    }

    #[inline]
    fn iter_mut(&mut self) -> Self::IterMut<'_> {
        IterMut {
            value: self.inner.as_mut().map(|v| (K::default(), v)),
        }
    }
}