Skip to main content

zerotrie/byte_phf/
cached_owned.rs

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
5use super::*;
6use crate::error::ZeroTrieBuildError;
7use alloc::collections::btree_map::Entry;
8use alloc::collections::BTreeMap;
9use alloc::vec::Vec;
10
11/// Helper class for caching the results of multiple [`PerfectByteHashMap`] calculations.
12pub 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
17impl 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}