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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
#[cfg(feature = "std")]
use std::collections::{btree_map, hash_map};

/// Extends map entries with `or_try_insert_with` and `or_try_insert_with_key`.
pub trait EntryInsertExt<'a, K, V> {
    /// If empty, computes the value from the default function. If the function
    /// returns `Ok`, inserts the value. If `f` returns `Err`, returns the
    /// error. If there is no error, returns a mutable reference to the value in
    /// the entry.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::collections::HashMap;
    ///
    /// use try_insert_ext::EntryInsertExt;
    ///
    /// let mut map: HashMap<&str, String> = HashMap::new();
    /// let s = "hoho".to_string();
    ///
    /// let e: Result<&mut String, ()> = map
    ///     .entry("poneyland")
    ///     .or_try_insert_with(|| Err(()));
    /// assert!(e.is_err());
    /// map.entry("poneyland").or_try_insert_with::<_, ()>(|| Ok(s));
    ///
    /// assert_eq!(map["poneyland"], "hoho".to_string());
    /// ```
    fn or_try_insert_with<F: FnOnce() -> Result<V, E>, E>(self, default: F)
        -> Result<&'a mut V, E>;

    /// If empty, computes the value from the default function. If the function
    /// returns `Ok`, inserts the value. If `f` returns `Err`, returns the
    /// error. If there is no error, returns a mutable reference to the value in
    /// the entry. This method allows for generating key-derived values for
    /// insertion by providing the default function a reference to the key
    /// that was moved during the `.entry(key)` method call.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::collections::HashMap;
    ///
    /// use try_insert_ext::EntryInsertExt;
    ///
    /// let mut map: HashMap<&str, usize> = HashMap::new();
    ///
    /// let e: Result<&mut usize, ()> = map
    ///     .entry("poneyland")
    ///     .or_try_insert_with_key(|_| Err(()));
    /// assert!(e.is_err());
    /// map
    ///     .entry("poneyland")
    ///     .or_try_insert_with_key::<_, ()>(|key| Ok(key.chars().count()));
    ///
    /// assert_eq!(map["poneyland"], 9);
    /// ```
    fn or_try_insert_with_key<F: FnOnce(&K) -> Result<V, E>, E>(
        self,
        default: F,
    ) -> Result<&'a mut V, E>;
}

#[cfg(feature = "std")]
impl<'a, K, V> EntryInsertExt<'a, K, V> for btree_map::Entry<'a, K, V>
where
    K: Ord,
{
    #[inline]
    fn or_try_insert_with<F: FnOnce() -> Result<V, E>, E>(
        self,
        default: F,
    ) -> Result<&'a mut V, E> {
        match self {
            Self::Occupied(entry) => Ok(entry.into_mut()),
            Self::Vacant(entry) => default().map(|default| entry.insert(default)),
        }
    }

    #[inline]
    fn or_try_insert_with_key<F: FnOnce(&K) -> Result<V, E>, E>(
        self,
        default: F,
    ) -> Result<&'a mut V, E> {
        match self {
            Self::Occupied(entry) => Ok(entry.into_mut()),
            Self::Vacant(entry) => default(entry.key()).map(|default| entry.insert(default)),
        }
    }
}

#[cfg(feature = "std")]
impl<'a, K, V> EntryInsertExt<'a, K, V> for hash_map::Entry<'a, K, V> {
    #[inline]
    fn or_try_insert_with<F: FnOnce() -> Result<V, E>, E>(
        self,
        default: F,
    ) -> Result<&'a mut V, E> {
        match self {
            Self::Occupied(entry) => Ok(entry.into_mut()),
            Self::Vacant(entry) => default().map(|default| entry.insert(default)),
        }
    }

    #[inline]
    fn or_try_insert_with_key<F: FnOnce(&K) -> Result<V, E>, E>(
        self,
        default: F,
    ) -> Result<&'a mut V, E> {
        match self {
            Self::Occupied(entry) => Ok(entry.into_mut()),
            Self::Vacant(entry) => default(entry.key()).map(|default| entry.insert(default)),
        }
    }
}

#[cfg(test)]
mod tests {
    #[cfg(feature = "std")]
    mod btree_map {
        use std::collections::BTreeMap;

        use crate::EntryInsertExt;

        #[test]
        fn it_works_when_occupied() {
            let mut map = BTreeMap::new();
            map.insert(0, 0);
            *map.entry(0).or_try_insert_with::<_, ()>(|| Ok(3)).unwrap() += 1;
            *map.entry(0).or_try_insert_with(|| Err(())).unwrap() += 1;
            assert_eq!(map.get(&0), Some(&2));
        }

        #[test]
        fn it_works_when_vacant() {
            let mut map = BTreeMap::new();
            map.entry(0).or_try_insert_with::<_, ()>(|| Ok(1)).unwrap();
            assert_eq!(map.get(&0), Some(&1));
        }

        #[test]
        fn it_errors() {
            let mut map = BTreeMap::<i32, i32>::new();
            assert_eq!(map.entry(0).or_try_insert_with(|| Err(())), Err(()));
        }
    }

    #[cfg(feature = "std")]
    mod hash_map {
        use std::collections::HashMap;

        use crate::EntryInsertExt;

        #[test]
        fn it_works_when_occupied() {
            let mut map = HashMap::new();
            map.insert(0, 0);
            *map.entry(0).or_try_insert_with::<_, ()>(|| Ok(3)).unwrap() += 1;
            *map.entry(0).or_try_insert_with(|| Err(())).unwrap() += 1;
            assert_eq!(map.get(&0), Some(&2));
        }

        #[test]
        fn it_works_when_vacant() {
            let mut map = HashMap::new();
            map.entry(0).or_try_insert_with::<_, ()>(|| Ok(1)).unwrap();
            assert_eq!(map.get(&0), Some(&1));
        }

        #[test]
        fn it_errors() {
            let mut map = HashMap::<i32, i32>::new();
            assert_eq!(map.entry(0).or_try_insert_with(|| Err(())), Err(()));
        }
    }
}