starnix_ext/
map_ext.rs

1// Copyright 2025 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5/// Trait to add helper methods on map-like entry types.
6pub trait EntryExt<'a, K: 'a, V: 'a> {
7    fn or_insert_with_fallible<E, F: FnOnce() -> Result<V, E>>(
8        self,
9        default: F,
10    ) -> Result<&'a mut V, E>;
11}
12
13impl<'a, K: Ord + 'a, V: 'a> EntryExt<'a, K, V> for std::collections::btree_map::Entry<'a, K, V> {
14    fn or_insert_with_fallible<E, F: FnOnce() -> Result<V, E>>(
15        self,
16        default: F,
17    ) -> Result<&'a mut V, E> {
18        let r = match self {
19            std::collections::btree_map::Entry::Occupied(o) => o.into_mut(),
20            std::collections::btree_map::Entry::Vacant(v) => v.insert(default()?),
21        };
22        Ok(r)
23    }
24}
25
26impl<'a, K: 'a, V: 'a> EntryExt<'a, K, V> for std::collections::hash_map::Entry<'a, K, V> {
27    fn or_insert_with_fallible<E, F: FnOnce() -> Result<V, E>>(
28        self,
29        default: F,
30    ) -> Result<&'a mut V, E> {
31        let r = match self {
32            std::collections::hash_map::Entry::Occupied(o) => o.into_mut(),
33            std::collections::hash_map::Entry::Vacant(v) => v.insert(default()?),
34        };
35        Ok(r)
36    }
37}