icu_locale_core/shortvec/
litemap.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::ShortBoxSlice;
6use super::ShortBoxSliceInner;
7#[cfg(feature = "alloc")]
8use super::ShortBoxSliceIntoIter;
9use litemap::store::*;
10
11impl<K, V> StoreConstEmpty<K, V> for ShortBoxSlice<(K, V)> {
12    const EMPTY: ShortBoxSlice<(K, V)> = ShortBoxSlice::new();
13}
14
15impl<K, V> StoreSlice<K, V> for ShortBoxSlice<(K, V)> {
16    type Slice = [(K, V)];
17
18    #[inline]
19    fn lm_get_range(&self, range: core::ops::Range<usize>) -> Option<&Self::Slice> {
20        self.get(range)
21    }
22}
23
24impl<K, V> Store<K, V> for ShortBoxSlice<(K, V)> {
25    #[inline]
26    fn lm_len(&self) -> usize {
27        self.len()
28    }
29
30    #[inline]
31    fn lm_is_empty(&self) -> bool {
32        use ShortBoxSliceInner::*;
33        #[allow(non_exhaustive_omitted_patterns)] match self.0 {
    ZeroOne(None) => true,
    _ => false,
}matches!(self.0, ZeroOne(None))
34    }
35
36    #[inline]
37    fn lm_get(&self, index: usize) -> Option<(&K, &V)> {
38        self.get(index).map(|elt| (&elt.0, &elt.1))
39    }
40
41    #[inline]
42    fn lm_last(&self) -> Option<(&K, &V)> {
43        use ShortBoxSliceInner::*;
44        match self.0 {
45            ZeroOne(ref v) => v.as_ref(),
46            #[cfg(feature = "alloc")]
47            Multi(ref v) => v.last(),
48            #[cfg(not(feature = "alloc"))]
49            Two([_, ref v]) => Some(v),
50        }
51        .map(|elt| (&elt.0, &elt.1))
52    }
53
54    #[inline]
55    fn lm_binary_search_by<F>(&self, mut cmp: F) -> Result<usize, usize>
56    where
57        F: FnMut(&K) -> core::cmp::Ordering,
58    {
59        self.binary_search_by(|(k, _)| cmp(k))
60    }
61}
62
63#[cfg(feature = "alloc")]
64impl<K: Ord, V> StoreFromIterable<K, V> for ShortBoxSlice<(K, V)> {
65    fn lm_sort_from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
66        alloc::vec::Vec::lm_sort_from_iter(iter).into()
67    }
68}
69
70#[cfg(feature = "alloc")]
71impl<K, V> StoreMut<K, V> for ShortBoxSlice<(K, V)> {
72    fn lm_with_capacity(_capacity: usize) -> Self {
73        ShortBoxSlice::new()
74    }
75
76    fn lm_reserve(&mut self, _additional: usize) {}
77
78    fn lm_get_mut(&mut self, index: usize) -> Option<(&K, &mut V)> {
79        self.get_mut(index).map(|elt| (&elt.0, &mut elt.1))
80    }
81
82    fn lm_push(&mut self, key: K, value: V) {
83        self.push((key, value))
84    }
85
86    fn lm_insert(&mut self, index: usize, key: K, value: V) {
87        self.insert(index, (key, value))
88    }
89
90    fn lm_remove(&mut self, index: usize) -> (K, V) {
91        self.remove(index)
92    }
93
94    fn lm_clear(&mut self) {
95        self.clear();
96    }
97}
98
99#[cfg(feature = "alloc")]
100impl<K: Ord, V> StoreBulkMut<K, V> for ShortBoxSlice<(K, V)> {
101    fn lm_retain<F>(&mut self, mut predicate: F)
102    where
103        F: FnMut(&K, &V) -> bool,
104    {
105        self.retain(|(k, v)| predicate(k, v))
106    }
107
108    fn lm_extend<I>(&mut self, other: I)
109    where
110        I: IntoIterator<Item = (K, V)>,
111    {
112        let mut other = other.into_iter();
113        // Use an Option to hold the first item of the map and move it to
114        // items if there are more items. Meaning that if items is not
115        // empty, first is None.
116        let mut first = None;
117        let mut items = alloc::vec::Vec::new();
118        match core::mem::take(&mut self.0) {
119            ShortBoxSliceInner::ZeroOne(zo) => {
120                first = zo;
121                // Attempt to avoid the items allocation by advancing the iterator
122                // up to two times. If we eventually find a second item, we can
123                // lm_extend the Vec and with the first, next (second) and the rest
124                // of the iterator.
125                while let Some(next) = other.next() {
126                    if let Some(first) = first.take() {
127                        // lm_extend will take care of sorting and deduplicating
128                        // first, next and the rest of the other iterator.
129                        items.lm_extend([first, next].into_iter().chain(other));
130                        break;
131                    }
132                    first = Some(next);
133                }
134            }
135            ShortBoxSliceInner::Multi(existing_items) => {
136                items.reserve_exact(existing_items.len() + other.size_hint().0);
137                // We use a plain extend with existing items, which are already valid and
138                // lm_extend will fold over rest of the iterator sorting and deduplicating as needed.
139                items.extend(existing_items);
140                items.lm_extend(other);
141            }
142        }
143        if items.is_empty() {
144            debug_assert!(items.is_empty());
145            self.0 = ShortBoxSliceInner::ZeroOne(first);
146        } else {
147            debug_assert!(first.is_none());
148            self.0 = ShortBoxSliceInner::Multi(items.into_boxed_slice());
149        }
150    }
151}
152
153impl<'a, K: 'a, V: 'a> StoreIterable<'a, K, V> for ShortBoxSlice<(K, V)> {
154    type KeyValueIter =
155        core::iter::Map<core::slice::Iter<'a, (K, V)>, for<'r> fn(&'r (K, V)) -> (&'r K, &'r V)>;
156
157    fn lm_iter(&'a self) -> Self::KeyValueIter {
158        self.iter().map(|elt| (&elt.0, &elt.1))
159    }
160}
161
162#[cfg(feature = "alloc")]
163impl<K, V> StoreFromIterator<K, V> for ShortBoxSlice<(K, V)> {}
164
165#[cfg(feature = "alloc")]
166impl<'a, K: 'a, V: 'a> StoreIterableMut<'a, K, V> for ShortBoxSlice<(K, V)> {
167    type KeyValueIterMut = core::iter::Map<
168        core::slice::IterMut<'a, (K, V)>,
169        for<'r> fn(&'r mut (K, V)) -> (&'r K, &'r mut V),
170    >;
171
172    fn lm_iter_mut(
173        &'a mut self,
174    ) -> <Self as litemap::store::StoreIterableMut<'a, K, V>>::KeyValueIterMut {
175        self.iter_mut().map(|elt| (&elt.0, &mut elt.1))
176    }
177}
178
179#[cfg(feature = "alloc")]
180impl<K, V> StoreIntoIterator<K, V> for ShortBoxSlice<(K, V)> {
181    type KeyValueIntoIter = ShortBoxSliceIntoIter<(K, V)>;
182
183    fn lm_into_iter(self) -> Self::KeyValueIntoIter {
184        self.into_iter()
185    }
186
187    // leave lm_extend_end as default
188
189    // leave lm_extend_start as default
190}
191
192#[test]
193fn test_short_slice_impl() {
194    litemap::testing::check_store::<ShortBoxSlice<(u32, u64)>>();
195}
196
197#[test]
198fn test_short_slice_impl_full() {
199    litemap::testing::check_store_full::<ShortBoxSlice<(u32, u64)>>();
200}