Debian Codegraph @

debian/rust-vendor/zerotrie/src/dense.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 //! Data structures combining [`ZeroTrie`] and [`ZeroVec`] to store data
6 //! more efficiently.
7 //!
8 //! [`ZeroTrie`]: crate::ZeroTrie
9
10 use crate::ZeroTrieSimpleAscii;
11 use zerovec::ule::tuplevar::Tuple3VarULE;
12 use zerovec::ule::vartuple::VarTuple;
13 use zerovec::ule::vartuple::VarTupleULE;
14 use zerovec::ule::EncodeAsVarULE;
15 use zerovec::vecs::Index32;
16 use zerovec::ZeroSlice;
17
18 #[cfg(feature = "alloc")]
19 use alloc::vec::Vec;
20 #[cfg(feature = "alloc")]
21 use zerovec::ZeroVec;
22
23 pub(crate) type DenseType = u16;
24
25 /// A data structure designed for 2-dimensional ASCII keys that exhibit a mix
26 /// of density and sparsity.
27 ///
28 /// This structure is best for data with the following properties:
29 ///
30 /// 1. Suffixes are commonly repeated. For example, the two-dimentional keys
31 /// "aa/ZZ" and "bb/ZZ" have the same suffix (second-level key).
32 /// 1. Some prefixes are sparse (contain just a few suffixes) while others are
33 /// dense (contain many/most of the suffixes).
34 /// 1. Values are mostly in a compact range within a prefix. For example, for
35 /// the keys "qq/AA", "qq/BB", and "qq/CC", the values 100, 101, and 103
36 /// are in a compact range, but the values 1, 500, and 7e8 are not.
37 ///
38 /// Instead of having a pluggable store like [`ZeroTrie`], there are three
39 /// separate versions of this type:
40 ///
41 /// 1. [`ZeroAsciiDenseSparse2dTrieOwned`], which owns its data
42 /// 1. [`ZeroAsciiDenseSparse2dTrieBorrowed`], which borrows its data
43 /// 1. [`ZeroAsciiDenseSparse2dTrieVarULE`], for zero-copy storage as bytes
44 ///
45 /// Internally, the structure stores prefixes and suffixes separated by a
46 /// delimiter, which must not occur in any of the prefix or suffix strings.
47 ///
48 /// ✨ *Enabled with the `alloc` and `dense` Cargo features.*
49 ///
50 /// # Examples
51 ///
52 /// ```
53 /// use std::collections::BTreeMap;
54 /// use zerotrie::dense::ZeroAsciiDenseSparse2dTrieOwned;
55 ///
56 /// let mut data: BTreeMap<&str, BTreeMap<&str, usize>> = BTreeMap::new();
57 ///
58 /// data.entry("aaa").or_default().insert("BBB", 1);
59 /// data.entry("aaa").or_default().insert("CCC", 2);
60 /// data.entry("ddd").or_default().insert("BBB", 3);
61 /// data.entry("ddd").or_default().insert("EEE", 4);
62 /// data.entry("fff").or_default().insert("BBB", 5);
63 ///
64 /// let trie =
65 /// ZeroAsciiDenseSparse2dTrieOwned::try_from_btree_map_str(&data, b'/')
66 /// .unwrap();
67 /// let trie = trie.as_borrowed();
68 ///
69 /// assert_eq!(trie.get("aaa", "CCC"), Some(2));
70 /// assert_eq!(trie.get("aaa", "EEE"), None);
71 /// ```
72 ///
73 /// [`ZeroTrie`]: crate::ZeroTrie
74 #[cfg(feature = "alloc")]
75 #[derive(Debug, PartialEq, Eq)]
76 pub struct ZeroAsciiDenseSparse2dTrieOwned {
77 /// The main trie, including all data that isn't in the dense matrix.
78 ///
79 /// There are three types of values stored here:
80 ///
81 /// 1. Prefix: value is row index
82 /// 2. Prefix followed by delimiter: value is row value offset
83 /// 3. Prefix followed by delimiter followed by suffix: a value not in the dense matrix
84 pub(crate) primary: ZeroTrieSimpleAscii<Vec<u8>>,
85 /// A trie mapping suffixes to column IDs in the dense matrix.
86 pub(crate) suffixes: ZeroTrieSimpleAscii<Vec<u8>>,
87 /// The dense matrix. To look up a value from the dense matrix:
88 ///
89 /// 1. Find the row index and row value offset from [`Self::primary`]
90 /// 2. Find the column index from [`Self::suffixes`]
91 /// 3. Find the number of columns from [`Self::suffix_count`]
92 /// 4. Select the entry from the matrix based on the row and column index.
93 /// 5. Add the row value offset to recover the original value.
94 ///
95 /// The row value offset exists in order to allow storage of rows with
96 /// values that are tight in a certain range, but when that range exceeds
97 /// the capacity of [`DenseType`], such as 100000, 100001, and 100002.
98 ///
99 /// For example: suppose you are looking up "ddd/ZZ".
100 ///
101 /// 1. Check the primary matrix. Row index is 4, row value offset 100.
102 /// 2. Check the suffixes matrix. Column index is 19.
103 /// 3. Check the number of columns. There are 30 columns.
104 /// 4. Select the value at index (30*4)+19 = 139. It is 15.
105 /// 5. Add 100 to recover the original value. Return 115.
106 pub(crate) dense: ZeroVec<'static, DenseType>,
107 /// The number of columns in the dense matrix.
108 pub(crate) suffix_count: u16,
109 /// The delimiter byte.
110 pub(crate) delimiter: u8,
111 }
112
113 /// A data structure designed for 2-dimensional ASCII keys that exhibit a mix
114 /// of density and sparsity.
115 ///
116 /// For more details, see [`ZeroAsciiDenseSparse2dTrieOwned`].
117 ///
118 /// ✨ *Enabled with the `dense` Cargo feature.*
119 pub type ZeroAsciiDenseSparse2dTrieVarULE = VarTupleULE<
120 (u16, u8),
121 Tuple3VarULE<ZeroSlice<u8>, ZeroSlice<u8>, ZeroSlice<DenseType>, Index32>,
122 >;
123
124 /// A data structure designed for 2-dimensional ASCII keys that exhibit a mix
125 /// of density and sparsity.
126 ///
127 /// For more details, see [`ZeroAsciiDenseSparse2dTrieOwned`].
128 ///
129 /// ✨ *Enabled with the `dense` Cargo feature.*
130 #[derive(Debug, PartialEq, Eq)]
131 pub struct ZeroAsciiDenseSparse2dTrieBorrowed<'a> {
132 primary: &'a ZeroTrieSimpleAscii<[u8]>,
133 suffixes: &'a ZeroTrieSimpleAscii<[u8]>,
134 dense: &'a ZeroSlice<DenseType>,
135 suffix_count: u16,
136 delimiter: u8,
137 }
138
139 #[cfg(feature = "alloc")]
140 impl ZeroAsciiDenseSparse2dTrieOwned {
141 /// Borrows the structure for querying.
142 pub fn as_borrowed(&self) -> ZeroAsciiDenseSparse2dTrieBorrowed<'_> {
143 ZeroAsciiDenseSparse2dTrieBorrowed {
144 primary: self.primary.as_borrowed(),
145 suffixes: self.suffixes.as_borrowed(),
146 dense: self.dense.as_slice(),
147 suffix_count: self.suffix_count,
148 delimiter: self.delimiter,
149 }
150 }
151 }
152
153 impl<'a> From<&'a ZeroAsciiDenseSparse2dTrieVarULE> for ZeroAsciiDenseSparse2dTrieBorrowed<'a> {
154 fn from(ule: &ZeroAsciiDenseSparse2dTrieVarULE) -> ZeroAsciiDenseSparse2dTrieBorrowed<'_> {
155 ZeroAsciiDenseSparse2dTrieBorrowed {
156 primary: ZeroTrieSimpleAscii::from_bytes(ule.variable.a().as_ule_slice()),
157 suffixes: ZeroTrieSimpleAscii::from_bytes(ule.variable.b().as_ule_slice()),
158 dense: ule.variable.c(),
159 suffix_count: ule.sized.0.as_unsigned_int(),
160 delimiter: ule.sized.1,
161 }
162 }
163 }
164
165 impl<'a> ZeroAsciiDenseSparse2dTrieBorrowed<'a> {
166 /// Queries the data structure for a value
167 pub fn get(&self, prefix: &str, suffix: &str) -> Option<usize> {
168 let mut cursor = self.primary.cursor();
169 for b in prefix.as_bytes().iter() {
170 if cursor.is_empty() {
171 return None;
172 }
173 cursor.step(*b);
174 }
175 let row_index = cursor.take_value();
176 cursor.step(self.delimiter);
177 let row_value_offset = cursor.take_value();
178 // Check for a sparse value
179 for b in suffix.as_bytes().iter() {
180 if cursor.is_empty() {
181 break;
182 }
183 cursor.step(*b);
184 }
185 if let Some(value) = cursor.take_value() {
186 // Found a sparse value
187 return Some(value);
188 }
189 let (Some(row_index), Some(row_value_offset)) = (row_index, row_value_offset) else {
190 // There is no dense row for this prefix
191 return None;
192 };
193 let Some(column_index) = self.suffixes.get(suffix) else {
194 // There is no dense column for this suffix
195 return None;
196 };
197 let suffix_count = usize::from(self.suffix_count);
198 let Some(offset) = row_index
199 .checked_mul(suffix_count)
200 .and_then(|v| v.checked_add(column_index))
201 .and_then(|index| self.dense.get(index))
202 else {
203 debug_assert!(
204 false,
205 "matrix index out of bounds: row={}, col={}, suffix_count={}",
206 row_index, column_index, suffix_count
207 );
208 return None;
209 };
210 if offset == DenseType::MAX {
211 // There is an entry in the dense matrix but it is a None value
212 return None;
213 }
214 let Some(result) = usize::from(offset).checked_add(row_value_offset) else {
215 debug_assert!(
216 false,
217 "overflow: offset={}, row_value_offset={}",
218 offset, row_value_offset
219 );
220 return None;
221 };
222 Some(result)
223 }
224
225 /// Borrows the structure for encoding into [`zerovec`].
226 pub fn as_encodeable(&self) -> impl EncodeAsVarULE<ZeroAsciiDenseSparse2dTrieVarULE> + '_ {
227 VarTuple {
228 sized: (self.suffix_count, self.delimiter),
229 variable: (
230 self.primary.as_bytes(),
231 self.suffixes.as_bytes(),
232 self.dense,
233 ),
234 }
235 }
236 }