Debian Codegraph @

debian/missing-sources/zerotrie/src/byte_phf/cached_owned.rs

raw
1 // This file is part of ICU4X. For terms of use, please see the file
2 // called LICENSE at the top level of the ICU4X source tree
3 // (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
4
5 use super::*;
6 use crate::error::ZeroTrieBuildError;
7 use alloc::collections::btree_map::Entry;
8 use alloc::collections::BTreeMap;
9 use alloc::vec::Vec;
10
11 /// Helper class for caching the results of multiple [`PerfectByteHashMap`] calculations.
12 pub struct PerfectByteHashMapCacheOwned {
13 // Note: This should probably be a HashMap but that isn't in `alloc`
14 data: BTreeMap<Vec<u8>, PerfectByteHashMap<Vec<u8>>>,
15 }
16
17 impl PerfectByteHashMapCacheOwned {
18 /// Creates a new empty instance.
19 pub fn new_empty() -> Self {
20 Self {
21 data: BTreeMap::new(),
22 }
23 }
24
25 /// Gets the [`PerfectByteHashMap`] for the given bytes, calculating it if necessary.
26 pub fn try_get_or_insert(
27 &mut self,
28 keys: Vec<u8>,
29 ) -> Result<&PerfectByteHashMap<[u8]>, ZeroTrieBuildError> {
30 let mut_phf = match self.data.entry(keys) {
31 Entry::Vacant(entry) => {
32 let value = PerfectByteHashMap::try_new(entry.key())?;
33 entry.insert(value)
34 }
35 Entry::Occupied(entry) => entry.into_mut(),
36 };
37 Ok(mut_phf.as_borrowed())
38 }
39 }