Vendor asic-rs 0.8.1 (280 crates, offline builds) + wxWidgets 3.3.3 (pristine + patch queue); UI spec + ADR-0003; M1 on asic-rs
This commit is contained in:
+29
@@ -0,0 +1,29 @@
|
||||
// This file is part of ICU4X. For terms of use, please see the file
|
||||
// called LICENSE at the top level of the ICU4X source tree
|
||||
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
|
||||
|
||||
/// Intermediate metadata for a branch node under construction.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct BranchMeta {
|
||||
/// The lead byte for this branch. Formerly it was required to be an ASCII byte, but now
|
||||
/// it can be any byte.
|
||||
pub ascii: u8,
|
||||
/// The size in bytes of the trie data reachable from this branch.
|
||||
pub local_length: usize,
|
||||
/// The size in bytes of this and all later sibling branches.
|
||||
pub cumulative_length: usize,
|
||||
/// The number of later sibling branches, including this.
|
||||
pub count: usize,
|
||||
}
|
||||
|
||||
impl BranchMeta {
|
||||
/// Creates a new empty [`BranchMeta`].
|
||||
pub const fn default() -> Self {
|
||||
BranchMeta {
|
||||
ascii: 0,
|
||||
cumulative_length: 0,
|
||||
local_length: 0,
|
||||
count: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+204
@@ -0,0 +1,204 @@
|
||||
// This file is part of ICU4X. For terms of use, please see the file
|
||||
// called LICENSE at the top level of the ICU4X source tree
|
||||
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
|
||||
|
||||
use crate::dense::DenseType;
|
||||
use crate::dense::ZeroAsciiDenseSparse2dTrieOwned;
|
||||
use crate::ZeroTrieBuildError;
|
||||
use crate::ZeroTrieSimpleAscii;
|
||||
use alloc::collections::BTreeMap;
|
||||
use alloc::collections::BTreeSet;
|
||||
use alloc::string::String;
|
||||
use alloc::vec::Vec;
|
||||
use zerovec::ZeroVec;
|
||||
|
||||
#[derive(PartialEq, Eq, PartialOrd, Ord)]
|
||||
struct Row<'a> {
|
||||
prefix: &'a str,
|
||||
row_value_offset: usize,
|
||||
offsets: Vec<DenseType>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct DenseSparse2dAsciiWithFixedDelimiterBuilder<'a> {
|
||||
primary: Vec<(&'a str, &'a str, usize)>,
|
||||
suffixes: BTreeSet<&'a str>,
|
||||
dense: Vec<Row<'a>>,
|
||||
delimiter: u8,
|
||||
}
|
||||
|
||||
impl<'a> DenseSparse2dAsciiWithFixedDelimiterBuilder<'a> {
|
||||
/// Helper function: finds best row offset when value range too large for dense matrix
|
||||
#[allow(clippy::indexing_slicing)] // bot < top and top < sorted_vals.len()
|
||||
fn find_window(values: &BTreeMap<&'a str, usize>) -> usize {
|
||||
let mut sorted_vals: Vec<usize> = values.values().cloned().collect();
|
||||
let row_width = usize::from(DenseType::MAX);
|
||||
sorted_vals.sort_unstable();
|
||||
let mut bot = 0;
|
||||
let mut best = 0;
|
||||
let mut best_index = 0;
|
||||
for top in 0..sorted_vals.len() {
|
||||
while bot < top {
|
||||
let top_val = sorted_vals[top];
|
||||
let bot_val = sorted_vals[bot];
|
||||
if top_val - bot_val >= row_width {
|
||||
bot += 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (top - bot + 1) > best {
|
||||
best = top - bot + 1;
|
||||
best_index = bot;
|
||||
}
|
||||
}
|
||||
sorted_vals[best_index]
|
||||
}
|
||||
/// Add a prefix and all values associated with the prefix to the builder.
|
||||
pub(crate) fn add_prefix(&mut self, prefix: &'a str, values: &BTreeMap<&'a str, usize>) {
|
||||
// Is there a more Rusty way to compute min and max together?
|
||||
let mut min = usize::MAX;
|
||||
let mut max = 0;
|
||||
for value in values.values() {
|
||||
min = core::cmp::min(min, *value);
|
||||
max = core::cmp::max(max, *value);
|
||||
}
|
||||
// >= because DenseType::MAX is the sentinel
|
||||
let mut row_value_offset = min;
|
||||
if max - min >= usize::from(DenseType::MAX) {
|
||||
row_value_offset = Self::find_window(values);
|
||||
}
|
||||
let sentinel = row_value_offset + usize::from(DenseType::MAX);
|
||||
// Partition the entries based on whether they can be encoded as dense
|
||||
let (dense_or_sparse, sparse_only) = values
|
||||
.iter()
|
||||
.map(|(suffix, value)| (*suffix, *value))
|
||||
.partition::<BTreeMap<&'a str, usize>, _>(|(suffix, value)| {
|
||||
self.suffixes.contains(suffix)
|
||||
&& *value >= row_value_offset
|
||||
&& *value < row_value_offset + usize::from(DenseType::MAX)
|
||||
});
|
||||
// Check whether the sparse trie is smaller than the dense row
|
||||
let sub_trie = dense_or_sparse
|
||||
.iter()
|
||||
.map(|(suffix, value)| (*suffix, *value))
|
||||
.collect::<ZeroTrieSimpleAscii<Vec<u8>>>();
|
||||
if sub_trie.byte_len() > self.suffixes.len() * size_of::<DenseType>() {
|
||||
// Create a dense prefix
|
||||
let offsets = self
|
||||
.suffixes
|
||||
.iter()
|
||||
.map(|suffix| {
|
||||
let value = sub_trie.get(suffix).unwrap_or(sentinel);
|
||||
let Ok(offset) = DenseType::try_from(value - row_value_offset) else {
|
||||
unreachable!("this should have been handled earlier");
|
||||
};
|
||||
offset
|
||||
})
|
||||
.collect::<Vec<DenseType>>();
|
||||
self.dense.push(Row {
|
||||
prefix,
|
||||
row_value_offset,
|
||||
offsets,
|
||||
});
|
||||
for (suffix, value) in sparse_only.iter() {
|
||||
self.primary.push((prefix, *suffix, *value));
|
||||
}
|
||||
} else {
|
||||
// Create a sparse prefix
|
||||
for (suffix, value) in values.iter() {
|
||||
self.primary.push((prefix, *suffix, *value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Assemble the intermediate structures into the final layout.
|
||||
pub(crate) fn build(mut self) -> Result<ZeroAsciiDenseSparse2dTrieOwned, ZeroTrieBuildError> {
|
||||
self.dense.sort();
|
||||
let Ok(suffix_count) = DenseType::try_from(self.suffixes.len()) else {
|
||||
return Err(ZeroTrieBuildError::CapacityExceeded);
|
||||
};
|
||||
let delimiter = self.delimiter as char;
|
||||
let mut primary_contents = BTreeMap::new();
|
||||
for (prefix, suffix, value) in self.primary.iter() {
|
||||
if prefix.contains(delimiter) || suffix.contains(delimiter) {
|
||||
debug_assert!(false, "handled earlier");
|
||||
return Err(ZeroTrieBuildError::IllegalDelimiter);
|
||||
}
|
||||
let mut delimited = String::with_capacity(prefix.len() + suffix.len() + 1);
|
||||
delimited.push_str(prefix);
|
||||
delimited.push(delimiter);
|
||||
delimited.push_str(suffix);
|
||||
primary_contents.insert(delimited, *value);
|
||||
}
|
||||
let mut dense = Vec::<DenseType>::with_capacity(self.dense.len() * self.suffixes.len());
|
||||
for (
|
||||
row_index,
|
||||
Row {
|
||||
prefix,
|
||||
row_value_offset,
|
||||
offsets,
|
||||
},
|
||||
) in self.dense.iter().enumerate()
|
||||
{
|
||||
primary_contents.insert(String::from(*prefix), row_index);
|
||||
let mut prefix_with_delim = String::with_capacity(prefix.len() + 1);
|
||||
prefix_with_delim.push_str(prefix);
|
||||
prefix_with_delim.push(delimiter);
|
||||
primary_contents.insert(prefix_with_delim, *row_value_offset);
|
||||
dense.extend(offsets);
|
||||
}
|
||||
let suffixes = self
|
||||
.suffixes
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(column_index, suffix)| (*suffix, column_index))
|
||||
.collect::<BTreeMap<&str, usize>>();
|
||||
Ok(ZeroAsciiDenseSparse2dTrieOwned {
|
||||
primary: ZeroTrieSimpleAscii::try_from_btree_map_str(&primary_contents)?,
|
||||
suffixes: ZeroTrieSimpleAscii::try_from_btree_map_str(&suffixes)?,
|
||||
dense: ZeroVec::from_slice_or_alloc(dense.as_slice()).into_owned(),
|
||||
suffix_count,
|
||||
delimiter: self.delimiter,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ZeroAsciiDenseSparse2dTrieOwned {
|
||||
/// Builds one of these from a two-dimensional [`BTreeMap`] and a delimiter.
|
||||
///
|
||||
/// Keep in mind the recommendations for optimal data size described in
|
||||
/// the [class docs].
|
||||
///
|
||||
/// [class docs]: ZeroAsciiDenseSparse2dTrieOwned
|
||||
pub fn try_from_btree_map_str(
|
||||
entries: &BTreeMap<&str, BTreeMap<&str, usize>>,
|
||||
delimiter: u8,
|
||||
) -> Result<Self, ZeroTrieBuildError> {
|
||||
let mut builder = DenseSparse2dAsciiWithFixedDelimiterBuilder {
|
||||
delimiter,
|
||||
..Default::default()
|
||||
};
|
||||
// TODO(#7302): Prune low-frequency suffixes.
|
||||
// For now, build with all suffixes.
|
||||
builder.suffixes = entries
|
||||
.values()
|
||||
.flat_map(|inner| inner.keys())
|
||||
.copied()
|
||||
.map(|s| {
|
||||
if s.contains(delimiter as char) {
|
||||
Err(ZeroTrieBuildError::IllegalDelimiter)
|
||||
} else {
|
||||
Ok(s)
|
||||
}
|
||||
})
|
||||
.collect::<Result<_, ZeroTrieBuildError>>()?;
|
||||
for (prefix, values) in entries.iter() {
|
||||
if prefix.contains(delimiter as char) {
|
||||
return Err(ZeroTrieBuildError::IllegalDelimiter);
|
||||
}
|
||||
builder.add_prefix(prefix, values);
|
||||
}
|
||||
builder.build()
|
||||
}
|
||||
}
|
||||
+311
@@ -0,0 +1,311 @@
|
||||
// This file is part of ICU4X. For terms of use, please see the file
|
||||
// called LICENSE at the top level of the ICU4X source tree
|
||||
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
|
||||
|
||||
use super::super::branch_meta::BranchMeta;
|
||||
use super::super::slice_indices::{self, ByteSliceWithIndices};
|
||||
use super::store::ConstArrayBuilder;
|
||||
use super::store::ConstLengthsStack;
|
||||
use super::store::ConstSlice;
|
||||
use crate::varint;
|
||||
|
||||
/// A low-level builder for [`ZeroTrieSimpleAscii`]. Works in const contexts.
|
||||
///
|
||||
/// All methods that grow the trie will panic if the capacity N is not enough.
|
||||
pub(crate) struct ZeroTrieBuilderConst<const N: usize> {
|
||||
data: ConstArrayBuilder<N, u8>,
|
||||
}
|
||||
|
||||
impl<const N: usize> ZeroTrieBuilderConst<N> {
|
||||
/// Non-const function that returns the current trie data as a slice.
|
||||
#[cfg(feature = "litemap")]
|
||||
pub fn as_bytes(&self) -> &[u8] {
|
||||
self.data.as_const_slice().as_slice()
|
||||
}
|
||||
|
||||
/// Returns the trie data, panicking if the buffer is the wrong size.
|
||||
pub const fn build_or_panic(self) -> [u8; N] {
|
||||
self.data.const_build_or_panic()
|
||||
}
|
||||
|
||||
/// Creates a new empty builder.
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
data: ConstArrayBuilder::new_empty([0; N], N),
|
||||
}
|
||||
}
|
||||
|
||||
/// Prepends an ASCII node to the front of the builder. Returns the new builder
|
||||
/// and the delta in length, which is always 1.
|
||||
pub const fn prepend_ascii(&mut self, ascii: u8) -> usize {
|
||||
if ascii >= 128 {
|
||||
panic!("Non-ASCII not supported in ZeroTrieSimpleAscii");
|
||||
}
|
||||
self.data.const_push_front_or_panic(ascii);
|
||||
1
|
||||
}
|
||||
|
||||
/// Prepends a value node to the front of the builder. Returns the new builder
|
||||
/// and the delta in length, which depends on the size of the varint.
|
||||
pub const fn prepend_value(&mut self, value: usize) -> usize {
|
||||
let varint_array = varint::write_varint_meta3(value);
|
||||
// Can panic (as documented in class docs):
|
||||
self.data
|
||||
.const_extend_front_or_panic(varint_array.as_const_slice());
|
||||
// Shouldn't panic: index 0 is always a valid index, and the array is nonempty now
|
||||
self.data.const_bitor_assign_or_panic(0, 0b10000000);
|
||||
varint_array.len()
|
||||
}
|
||||
|
||||
/// Prepends a branch node to the front of the builder. Returns the new builder
|
||||
/// and the delta in length, which depends on the size of the varint.
|
||||
pub const fn prepend_branch(&mut self, value: usize) -> usize {
|
||||
let varint_array = varint::write_varint_meta2(value);
|
||||
// Can panic (as documented in type-level docs):
|
||||
self.data
|
||||
.const_extend_front_or_panic(varint_array.as_const_slice());
|
||||
// Shouldn't panic: index 0 is always a valid index, and the array is nonempty now
|
||||
self.data.const_bitor_assign_or_panic(0, 0b11000000);
|
||||
varint_array.len()
|
||||
}
|
||||
|
||||
/// Prepends multiple arbitrary bytes to the front of the builder. Returns the new builder
|
||||
/// and the delta in length, which is the length of the slice.
|
||||
pub const fn prepend_slice(&mut self, s: ConstSlice<u8>) -> usize {
|
||||
let mut i = s.len();
|
||||
while i > 0 {
|
||||
// Can panic (as documented in type-level docs):
|
||||
self.data.const_push_front_or_panic(*s.get_or_panic(i - 1));
|
||||
i -= 1;
|
||||
}
|
||||
s.len()
|
||||
}
|
||||
|
||||
/// Prepends multiple zeros to the front of the builder. Returns the new builder.
|
||||
pub const fn prepend_n_zeros(&mut self, n: usize) {
|
||||
let mut i = 0;
|
||||
while i < n {
|
||||
// Can panic (as documented in type-level docs):
|
||||
self.data.const_push_front_or_panic(0);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// Performs the operation `self[index] |= bits`
|
||||
pub const fn bitor_assign_at_or_panic(&mut self, index: usize, bits: u8) {
|
||||
self.data.const_bitor_assign_or_panic(index, bits);
|
||||
}
|
||||
|
||||
/// Creates a new builder containing the elements in the given slice of key/value pairs.
|
||||
///
|
||||
/// `K` is the stack size of the lengths stack. If you get an error such as
|
||||
/// `AsciiTrie Builder: Need more stack`, try increasing `K`.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if the items are not sorted
|
||||
pub const fn from_tuple_slice<'a, const K: usize>(items: ByteSliceWithIndices<'a>) -> Self {
|
||||
assert!(
|
||||
items.is_sorted(),
|
||||
"Strings in ZeroTrie constructor are not sorted"
|
||||
);
|
||||
Self::from_slice_with_indices::<K>(items)
|
||||
}
|
||||
|
||||
/// Creates a new builder containing the elements in the given slice of key/value pairs.
|
||||
///
|
||||
/// Assumes that the items are sorted. If they are not, unexpected behavior may occur.
|
||||
///
|
||||
/// `K` is the stack size of the lengths stack. If you get an error such as
|
||||
/// `AsciiTrie Builder: Need more stack`, try increasing `K`.
|
||||
pub const fn from_slice_with_indices<const K: usize>(items: ByteSliceWithIndices) -> Self {
|
||||
let mut result = Self::new();
|
||||
let total_size = result.create_or_panic::<K>(items);
|
||||
debug_assert!(total_size == result.data.len());
|
||||
result
|
||||
}
|
||||
|
||||
/// The actual builder algorithm. For an explanation, see [`crate::builder`].
|
||||
#[must_use]
|
||||
#[expect(
|
||||
clippy::indexing_slicing,
|
||||
reason = "all call sites are well-commented and will not panic"
|
||||
)]
|
||||
const fn create_or_panic<const K: usize>(&mut self, all_items: ByteSliceWithIndices) -> usize {
|
||||
let mut prefix_len = match all_items.last() {
|
||||
Some(x) => x.0.len(),
|
||||
// Empty slice:
|
||||
None => return 0,
|
||||
};
|
||||
// Initialize the main loop to point at the last string.
|
||||
let mut lengths_stack = ConstLengthsStack::<K>::new();
|
||||
let mut i = all_items.len() - 1;
|
||||
let mut j = all_items.len();
|
||||
let mut current_len = 0;
|
||||
// Start the main loop.
|
||||
loop {
|
||||
let item_i = all_items.get_or_panic(i);
|
||||
let item_j = all_items.get_or_panic(j - 1);
|
||||
debug_assert!(slice_indices::prefix_eq_or_panic(
|
||||
item_i.0, item_j.0, prefix_len
|
||||
));
|
||||
// Check if we need to add a value node here.
|
||||
if item_i.0.len() == prefix_len {
|
||||
current_len += self.prepend_value(item_i.1);
|
||||
}
|
||||
if prefix_len == 0 {
|
||||
// All done! Leave the main loop.
|
||||
break;
|
||||
}
|
||||
// Reduce the prefix length by 1 and recalculate i and j.
|
||||
prefix_len -= 1;
|
||||
let mut new_i = i;
|
||||
let mut new_j = j;
|
||||
// `prefix_len` is guaranteed to be in bounds for `item_i` since it is
|
||||
// instantiated and updated based on the length of `item_i`, and then only decremented.
|
||||
// This is a bit harder to prove for `item_j`, but it is a loop invariant
|
||||
// TODO(sffc): Consider proving this or perhaps using a checked get.
|
||||
let mut ascii_i = item_i.0[prefix_len];
|
||||
let mut ascii_j = item_j.0[prefix_len];
|
||||
debug_assert!(ascii_i == ascii_j);
|
||||
let key_ascii = ascii_i;
|
||||
loop {
|
||||
if new_i == 0 {
|
||||
break;
|
||||
}
|
||||
let candidate = all_items.get_or_panic(new_i - 1).0;
|
||||
if candidate.len() < prefix_len {
|
||||
// Too short
|
||||
break;
|
||||
}
|
||||
if slice_indices::prefix_eq_or_panic(item_i.0, candidate, prefix_len) {
|
||||
new_i -= 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
|
||||
if candidate.len() == prefix_len {
|
||||
// A string that equals the prefix does not take part in the branch node.
|
||||
break;
|
||||
}
|
||||
let candidate = candidate[prefix_len];
|
||||
if candidate != ascii_i {
|
||||
ascii_i = candidate;
|
||||
}
|
||||
}
|
||||
loop {
|
||||
if new_j == all_items.len() {
|
||||
break;
|
||||
}
|
||||
let candidate = all_items.get_or_panic(new_j).0;
|
||||
if candidate.len() < prefix_len {
|
||||
// Too short
|
||||
break;
|
||||
}
|
||||
if slice_indices::prefix_eq_or_panic(item_j.0, candidate, prefix_len) {
|
||||
new_j += 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
if candidate.len() == prefix_len {
|
||||
panic!("A shorter string should be earlier in the sequence");
|
||||
}
|
||||
let candidate = candidate[prefix_len];
|
||||
if candidate != ascii_j {
|
||||
ascii_j = candidate;
|
||||
}
|
||||
}
|
||||
// If there are no different bytes at this prefix level, we can add an ASCII or Span
|
||||
// node and then continue to the next iteration of the main loop.
|
||||
if ascii_i == key_ascii && ascii_j == key_ascii {
|
||||
current_len += self.prepend_ascii(ascii_i);
|
||||
debug_assert!(i == new_i || i == new_i + 1);
|
||||
i = new_i;
|
||||
debug_assert!(j == new_j);
|
||||
continue;
|
||||
}
|
||||
// If i and j changed, we are a target of a branch node.
|
||||
if ascii_j == key_ascii {
|
||||
// We are the _last_ target of a branch node.
|
||||
lengths_stack.push_or_panic(BranchMeta {
|
||||
ascii: key_ascii,
|
||||
cumulative_length: current_len,
|
||||
local_length: current_len,
|
||||
count: 1,
|
||||
});
|
||||
} else {
|
||||
// We are the _not the last_ target of a branch node.
|
||||
let BranchMeta {
|
||||
cumulative_length,
|
||||
count,
|
||||
..
|
||||
} = lengths_stack.peek_or_panic();
|
||||
lengths_stack.push_or_panic(BranchMeta {
|
||||
ascii: key_ascii,
|
||||
cumulative_length: cumulative_length + current_len,
|
||||
local_length: current_len,
|
||||
count: count + 1,
|
||||
});
|
||||
}
|
||||
if ascii_i != key_ascii {
|
||||
// We are _not the first_ target of a branch node.
|
||||
// Set the cursor to the previous string and continue the loop.
|
||||
j = i;
|
||||
i -= 1;
|
||||
prefix_len = all_items.get_or_panic(i).0.len();
|
||||
current_len = 0;
|
||||
continue;
|
||||
}
|
||||
// Branch (first)
|
||||
let (total_length, total_count) = {
|
||||
let BranchMeta {
|
||||
cumulative_length,
|
||||
count,
|
||||
..
|
||||
} = lengths_stack.peek_or_panic();
|
||||
(cumulative_length, count)
|
||||
};
|
||||
let branch_metas = lengths_stack.pop_many_or_panic(total_count);
|
||||
let original_keys = branch_metas.map_to_ascii_bytes();
|
||||
// Write out the offset table
|
||||
current_len = total_length;
|
||||
let w = (usize::BITS as usize - (total_length.leading_zeros() as usize) - 1) / 8;
|
||||
if w > 3 {
|
||||
panic!("ZeroTrie capacity exceeded");
|
||||
}
|
||||
let mut k = 0;
|
||||
while k <= w {
|
||||
self.prepend_n_zeros(total_count - 1);
|
||||
current_len += total_count - 1;
|
||||
let mut l = 0;
|
||||
let mut length_to_write = 0;
|
||||
while l < total_count {
|
||||
let BranchMeta { local_length, .. } = *branch_metas
|
||||
.as_const_slice()
|
||||
.get_or_panic(total_count - l - 1);
|
||||
let mut adjusted_length = length_to_write;
|
||||
let mut m = 0;
|
||||
while m < k {
|
||||
adjusted_length >>= 8;
|
||||
m += 1;
|
||||
}
|
||||
if l > 0 {
|
||||
self.bitor_assign_at_or_panic(l - 1, adjusted_length as u8);
|
||||
}
|
||||
l += 1;
|
||||
length_to_write += local_length;
|
||||
}
|
||||
k += 1;
|
||||
}
|
||||
// Write out the lookup table
|
||||
assert!(0 < total_count && total_count <= 256);
|
||||
let branch_value = (w << 8) + (total_count & 0xff);
|
||||
current_len += self.prepend_slice(original_keys.as_const_slice());
|
||||
current_len += self.prepend_branch(branch_value);
|
||||
i = new_i;
|
||||
j = new_j;
|
||||
}
|
||||
assert!(lengths_stack.is_empty());
|
||||
current_len
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
// This file is part of ICU4X. For terms of use, please see the file
|
||||
// called LICENSE at the top level of the ICU4X source tree
|
||||
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
|
||||
|
||||
mod builder;
|
||||
mod store;
|
||||
|
||||
pub(crate) use builder::*;
|
||||
pub(crate) use store::ConstArrayBuilder;
|
||||
+333
@@ -0,0 +1,333 @@
|
||||
// This file is part of ICU4X. For terms of use, please see the file
|
||||
// called LICENSE at the top level of the ICU4X source tree
|
||||
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
|
||||
|
||||
//! This module contains internal collections for the const builder.
|
||||
|
||||
use super::super::branch_meta::BranchMeta;
|
||||
|
||||
/// A const-friendly slice type. It is backed by a full slice but is primarily intended
|
||||
/// to represent subslices of the full slice. We need this only because we can't take
|
||||
/// subslices in const Rust.
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub(crate) struct ConstSlice<'a, T> {
|
||||
/// The full slice.
|
||||
full_slice: &'a [T],
|
||||
/// The start index of the slice represented by this [`ConstSlice`].
|
||||
start: usize,
|
||||
/// The non-inclusive end index of the slice represented by this [`ConstSlice`].
|
||||
limit: usize,
|
||||
}
|
||||
|
||||
impl<'a, T> ConstSlice<'a, T> {
|
||||
/// Creates a [`ConstSlice`] representing an entire slice.
|
||||
pub const fn from_slice(other: &'a [T]) -> Self {
|
||||
ConstSlice {
|
||||
full_slice: other,
|
||||
start: 0,
|
||||
limit: other.len(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a [`ConstSlice`] with the given start and limit.
|
||||
pub const fn from_manual_slice(full_slice: &'a [T], start: usize, limit: usize) -> Self {
|
||||
ConstSlice {
|
||||
full_slice,
|
||||
start,
|
||||
limit,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the length of the [`ConstSlice`].
|
||||
pub const fn len(&self) -> usize {
|
||||
self.limit - self.start
|
||||
}
|
||||
|
||||
/// Gets the element at `index`, panicking if not present.
|
||||
pub const fn get_or_panic(&self, index: usize) -> &T {
|
||||
#[allow(clippy::indexing_slicing)] // documented
|
||||
&self.full_slice[index + self.start]
|
||||
}
|
||||
|
||||
/// Gets the first element or `None` if empty.
|
||||
#[cfg(test)]
|
||||
pub const fn first(&self) -> Option<&T> {
|
||||
if self.len() == 0 {
|
||||
None
|
||||
} else {
|
||||
// Won't panic: we already handled an empty slice
|
||||
Some(self.get_or_panic(0))
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets a subslice of this slice.
|
||||
#[cfg(test)]
|
||||
pub const fn get_subslice_or_panic(
|
||||
&self,
|
||||
new_start: usize,
|
||||
new_limit: usize,
|
||||
) -> ConstSlice<'a, T> {
|
||||
assert!(new_start <= new_limit);
|
||||
assert!(new_limit <= self.len());
|
||||
ConstSlice {
|
||||
full_slice: self.full_slice,
|
||||
start: self.start + new_start,
|
||||
limit: self.start + new_limit,
|
||||
}
|
||||
}
|
||||
|
||||
/// Non-const function that returns this [`ConstSlice`] as a regular slice.
|
||||
#[cfg(any(test, feature = "alloc"))]
|
||||
#[allow(clippy::indexing_slicing)] // indices in range by struct invariant
|
||||
pub fn as_slice(&self) -> &'a [T] {
|
||||
&self.full_slice[self.start..self.limit]
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> From<&'a [T]> for ConstSlice<'a, T> {
|
||||
fn from(other: &'a [T]) -> Self {
|
||||
Self::from_slice(other)
|
||||
}
|
||||
}
|
||||
|
||||
/// A const-friendly mutable data structure backed by an array.
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub(crate) struct ConstArrayBuilder<const N: usize, T> {
|
||||
full_array: [T; N],
|
||||
start: usize,
|
||||
limit: usize,
|
||||
}
|
||||
|
||||
impl<const N: usize, T: Default> Default for ConstArrayBuilder<N, T> {
|
||||
fn default() -> Self {
|
||||
Self::new_empty([(); N].map(|_| Default::default()), 0)
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize, T> ConstArrayBuilder<N, T> {
|
||||
/// Creates a new, empty builder of the given size. `cursor` indicates where in the
|
||||
/// array new elements will be inserted first. Since we use a lot of prepend operations,
|
||||
/// it is common to set `cursor` to `N`.
|
||||
pub const fn new_empty(full_array: [T; N], cursor: usize) -> Self {
|
||||
assert!(cursor <= N);
|
||||
Self {
|
||||
full_array,
|
||||
start: cursor,
|
||||
limit: cursor,
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a new builder with some initial content in `[start, limit)`.
|
||||
pub const fn from_manual_slice(full_array: [T; N], start: usize, limit: usize) -> Self {
|
||||
assert!(start <= limit);
|
||||
assert!(limit <= N);
|
||||
Self {
|
||||
full_array,
|
||||
start,
|
||||
limit,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the number of initialized elements in the builder.
|
||||
pub const fn len(&self) -> usize {
|
||||
self.limit - self.start
|
||||
}
|
||||
|
||||
/// Whether there are no initialized elements in the builder.
|
||||
#[allow(dead_code)]
|
||||
pub const fn is_empty(&self) -> bool {
|
||||
self.len() == 0
|
||||
}
|
||||
|
||||
/// Returns the initialized elements as a [`ConstSlice`].
|
||||
pub const fn as_const_slice(&self) -> ConstSlice<'_, T> {
|
||||
ConstSlice::from_manual_slice(&self.full_array, self.start, self.limit)
|
||||
}
|
||||
|
||||
/// Non-const function that returns a slice of the initialized elements.
|
||||
#[cfg(any(test, feature = "alloc"))]
|
||||
pub fn as_slice(&self) -> &[T] {
|
||||
&self.full_array[self.start..self.limit]
|
||||
}
|
||||
}
|
||||
|
||||
// Certain functions that involve dropping `T` require that it be `Copy`
|
||||
impl<const N: usize, T: Copy> ConstArrayBuilder<N, T> {
|
||||
/// Takes a fully initialized builder as an array. Panics if the builder is not
|
||||
/// fully initialized.
|
||||
pub const fn const_build_or_panic(self) -> [T; N] {
|
||||
if self.start != 0 || self.limit != N {
|
||||
let actual_len = self.limit - self.start;
|
||||
const PREFIX: &[u8; 31] = b"Buffer too large. Size needed: ";
|
||||
let len_bytes: [u8; PREFIX.len() + crate::helpers::MAX_USIZE_LEN_AS_DIGITS] =
|
||||
crate::helpers::const_fmt_int(*PREFIX, actual_len);
|
||||
let Ok(len_str) = core::str::from_utf8(&len_bytes) else {
|
||||
unreachable!()
|
||||
};
|
||||
panic!("{}", len_str);
|
||||
}
|
||||
self.full_array
|
||||
}
|
||||
|
||||
/// Prepends an element to the front of the builder, panicking if there is no room.
|
||||
#[allow(clippy::indexing_slicing)] // documented
|
||||
pub const fn const_push_front_or_panic(&mut self, value: T) {
|
||||
if self.start == 0 {
|
||||
panic!("Buffer too small");
|
||||
}
|
||||
self.start -= 1;
|
||||
self.full_array[self.start] = value;
|
||||
}
|
||||
|
||||
/// Prepends multiple elements to the front of the builder, panicking if there is no room.
|
||||
#[allow(clippy::indexing_slicing)] // documented
|
||||
pub const fn const_extend_front_or_panic(&mut self, other: ConstSlice<T>) {
|
||||
if self.start < other.len() {
|
||||
panic!("Buffer too small");
|
||||
}
|
||||
self.start -= other.len();
|
||||
let mut i = self.start;
|
||||
const_for_each!(other, byte, {
|
||||
self.full_array[i] = *byte;
|
||||
i += 1;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> ConstArrayBuilder<N, u8> {
|
||||
/// Specialized function that performs `self[index] |= bits`
|
||||
#[allow(clippy::indexing_slicing)] // documented
|
||||
pub(crate) const fn const_bitor_assign_or_panic(&mut self, index: usize, bits: u8) {
|
||||
self.full_array[self.start + index] |= bits;
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize, T: Copy> ConstArrayBuilder<N, T> {
|
||||
/// Swaps the elements at positions `i` and `j`.
|
||||
#[cfg(feature = "alloc")]
|
||||
pub fn swap_or_panic(&mut self, i: usize, j: usize) {
|
||||
self.full_array.swap(self.start + i, self.start + j);
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluates a block over each element of a const slice. Takes three arguments:
|
||||
///
|
||||
/// 1. Expression that resolves to the [`ConstSlice`].
|
||||
/// 2. Token that will be assigned the value of the element.
|
||||
/// 3. Block to evaluate for each element.
|
||||
macro_rules! const_for_each {
|
||||
($safe_const_slice:expr, $item:tt, $inner:expr) => {{
|
||||
let mut i = 0;
|
||||
while i < $safe_const_slice.len() {
|
||||
// Won't panic: in-range loop condition
|
||||
let $item = $safe_const_slice.get_or_panic(i);
|
||||
$inner;
|
||||
i += 1;
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
pub(crate) use const_for_each;
|
||||
|
||||
/// A data structure that holds up to K [`BranchMeta`] items.
|
||||
///
|
||||
/// Note: It should be possible to store the required data in the builder buffer itself,
|
||||
/// which would eliminate the need for this helper struct and the limit it imposes.
|
||||
pub(crate) struct ConstLengthsStack<const K: usize> {
|
||||
data: [Option<BranchMeta>; K],
|
||||
idx: usize,
|
||||
}
|
||||
|
||||
impl<const K: usize> core::fmt::Debug for ConstLengthsStack<K> {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
self.as_slice().fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
impl<const K: usize> ConstLengthsStack<K> {
|
||||
/// Creates a new empty [`ConstLengthsStack`].
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
data: [None; K],
|
||||
idx: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns whether the stack is empty.
|
||||
pub const fn is_empty(&self) -> bool {
|
||||
self.idx == 0
|
||||
}
|
||||
|
||||
/// Adds a [`BranchMeta`] to the stack, panicking if there is no room.
|
||||
#[allow(clippy::indexing_slicing)] // documented
|
||||
pub const fn push_or_panic(&mut self, meta: BranchMeta) {
|
||||
if self.idx >= K {
|
||||
panic!(concat!(
|
||||
"AsciiTrie Builder: Need more stack (max ",
|
||||
stringify!(K),
|
||||
")"
|
||||
));
|
||||
}
|
||||
self.data[self.idx] = Some(meta);
|
||||
self.idx += 1;
|
||||
}
|
||||
|
||||
/// Returns a copy of the [`BranchMeta`] on the top of the stack, panicking if
|
||||
/// the stack is empty.
|
||||
pub const fn peek_or_panic(&self) -> BranchMeta {
|
||||
if self.idx == 0 {
|
||||
panic!("AsciiTrie Builder: Attempted to peek from an empty stack");
|
||||
}
|
||||
self.get_or_panic(0)
|
||||
}
|
||||
|
||||
/// Returns a copy of the [`BranchMeta`] at the specified index.
|
||||
#[allow(clippy::indexing_slicing)] // documented
|
||||
const fn get_or_panic(&self, index: usize) -> BranchMeta {
|
||||
if self.idx <= index {
|
||||
panic!("AsciiTrie Builder: Attempted to get too deep in a stack");
|
||||
}
|
||||
match self.data[self.idx - index - 1] {
|
||||
Some(x) => x,
|
||||
None => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes many [`BranchMeta`]s from the stack, returning them in a [`ConstArrayBuilder`].
|
||||
#[allow(clippy::indexing_slicing)] // documented
|
||||
pub const fn pop_many_or_panic(&mut self, len: usize) -> ConstArrayBuilder<256, BranchMeta> {
|
||||
debug_assert!(len <= 256);
|
||||
let mut result = ConstArrayBuilder::new_empty([BranchMeta::default(); 256], 256);
|
||||
let mut ix = 0;
|
||||
loop {
|
||||
if ix == len {
|
||||
break;
|
||||
}
|
||||
let i = self.idx - ix - 1;
|
||||
result.const_push_front_or_panic(match self.data[i] {
|
||||
Some(x) => x,
|
||||
None => panic!("Not enough items in the ConstLengthsStack"),
|
||||
});
|
||||
ix += 1;
|
||||
}
|
||||
self.idx -= len;
|
||||
result
|
||||
}
|
||||
|
||||
/// Non-const function that returns the initialized elements as a slice.
|
||||
fn as_slice(&self) -> &[Option<BranchMeta>] {
|
||||
&self.data[0..self.idx]
|
||||
}
|
||||
}
|
||||
|
||||
impl<const K: usize> ConstArrayBuilder<K, BranchMeta> {
|
||||
/// Converts this builder-array of [`BranchMeta`] to one of the `ascii` fields.
|
||||
pub const fn map_to_ascii_bytes(&self) -> ConstArrayBuilder<K, u8> {
|
||||
let mut result = ConstArrayBuilder::new_empty([0; K], K);
|
||||
let self_as_slice = self.as_const_slice();
|
||||
const_for_each!(self_as_slice, value, {
|
||||
result.const_push_front_or_panic(value.ascii);
|
||||
});
|
||||
result
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
// This file is part of ICU4X. For terms of use, please see the file
|
||||
// called LICENSE at the top level of the ICU4X source tree
|
||||
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
|
||||
|
||||
//! Impls for functions gated on the "litemap" feature.
|
||||
|
||||
use super::konst::*;
|
||||
use crate::builder::slice_indices::ByteSliceWithIndices;
|
||||
use crate::error::ZeroTrieBuildError;
|
||||
use crate::zerotrie::ZeroTrieSimpleAscii;
|
||||
use crate::ZeroTrie;
|
||||
use alloc::vec::Vec;
|
||||
use core::borrow::Borrow;
|
||||
use litemap::LiteMap;
|
||||
|
||||
impl ZeroTrieSimpleAscii<Vec<u8>> {
|
||||
#[doc(hidden)]
|
||||
pub fn try_from_litemap_with_const_builder<'a, S>(
|
||||
items: &LiteMap<&'a [u8], usize, S>,
|
||||
) -> Result<Self, ZeroTrieBuildError>
|
||||
where
|
||||
S: litemap::store::StoreSlice<&'a [u8], usize, Slice = [(&'a [u8], usize)]>,
|
||||
{
|
||||
let tuples = items.as_slice();
|
||||
let byte_str_slice = ByteSliceWithIndices::from_byte_slice(tuples);
|
||||
|
||||
Ok(Self {
|
||||
store: ZeroTrieBuilderConst::<10000>::from_slice_with_indices::<100>(byte_str_slice)
|
||||
.as_bytes()
|
||||
.to_vec(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<K, S> TryFrom<&LiteMap<K, usize, S>> for ZeroTrie<Vec<u8>>
|
||||
where
|
||||
// Borrow, not AsRef, because we rely on Ord being the same. Unfortunately
|
||||
// this means `LiteMap<&str, usize>` does not work.
|
||||
K: Borrow<[u8]>,
|
||||
S: litemap::store::StoreSlice<K, usize, Slice = [(K, usize)]>,
|
||||
{
|
||||
type Error = ZeroTrieBuildError;
|
||||
fn try_from(items: &LiteMap<K, usize, S>) -> Result<Self, ZeroTrieBuildError> {
|
||||
let byte_litemap = items.to_borrowed_keys::<[u8], Vec<_>>();
|
||||
let byte_slice = byte_litemap.as_slice();
|
||||
let byte_str_slice = ByteSliceWithIndices::from_byte_slice(byte_slice);
|
||||
Self::try_from_tuple_slice(byte_str_slice)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
impl TryFrom<&LiteMap<crate::serde::SerdeByteStrOwned, usize>> for ZeroTrie<Vec<u8>> {
|
||||
type Error = ZeroTrieBuildError;
|
||||
fn try_from(
|
||||
items: &LiteMap<crate::serde::SerdeByteStrOwned, usize>,
|
||||
) -> Result<Self, ZeroTrieBuildError> {
|
||||
let tuples: Vec<(&[u8], usize)> = items.iter().map(|(k, v)| (k.as_bytes(), *v)).collect();
|
||||
let byte_str_slice = ByteSliceWithIndices::from_byte_slice(&tuples);
|
||||
Self::try_from_tuple_slice(byte_str_slice)
|
||||
}
|
||||
}
|
||||
|
||||
// TODO(#7084): Make this more infallible by calculating the required length,
|
||||
// heap-allocating the required capacity, and pointing ConstAsciiTrieBuilderStore
|
||||
// to the heap buffer.
|
||||
Vendored
+301
@@ -0,0 +1,301 @@
|
||||
// This file is part of ICU4X. For terms of use, please see the file
|
||||
// called LICENSE at the top level of the ICU4X source tree
|
||||
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
|
||||
|
||||
//! # [`ZeroTrie`](crate::ZeroTrie) Builder
|
||||
//!
|
||||
//! There are two implementations of the [`ZeroTrie`](crate::ZeroTrie) Builder:
|
||||
//!
|
||||
//! - [`konst::ZeroTrieBuilderConst`] allows for human-readable const construction
|
||||
//! - [`nonconst::ZeroTrieBuilder`] has the full feaure set but requires `alloc`
|
||||
//!
|
||||
//! The two builders follow the same algorithm but have different capabilities.
|
||||
//!
|
||||
//! ## Builder Algorithm Overview
|
||||
//!
|
||||
//! The tries are built backwards, from the last node to the first node. The key step of the
|
||||
//! algorithm is **determining what is the next node to prepend.**
|
||||
//!
|
||||
//! In the simple case of [`ZeroTrieSimpleAscii`], all nodes are binary-search, so if the input
|
||||
//! strings are provided in lexicographic order, there is a simple, deterministic method for
|
||||
//! identifying the next node. This insight is what enables us to make the const builder.
|
||||
//!
|
||||
//! The builder works with the following intermediate state variables:
|
||||
//!
|
||||
//! - `prefix_len` indicates the byte index we are currently processing.
|
||||
//! - `i` and `j` bracket a window of strings in the input that share the same prefix.
|
||||
//! - `current_len` is the length in bytes of the current self-contained trie.
|
||||
//! - `lengths_stack` contains metadata for branch nodes.
|
||||
//!
|
||||
//! Consider a trie containing the following strings and values:
|
||||
//!
|
||||
//! - "" → 11
|
||||
//! - "ad" → 22
|
||||
//! - "adef" → 33
|
||||
//! - "adghk" → 44
|
||||
//!
|
||||
//! Suppose `prefix_len = 2`, `i = 1`, and `j = 4`. This would indicate that we
|
||||
//! have are evaluating the strings with the "ad" prefix, which extend from
|
||||
//! index 1 (inclusive) to index 4 (exclusive).
|
||||
//!
|
||||
//! What follows is a verbal explanation of the build steps for the above trie.
|
||||
//! When a node is prepended, it is shown in **boldface**.
|
||||
//!
|
||||
//! 1. Initialize the builder by setting `i=3`, `j=4`, `prefix_len=5` (the last string),
|
||||
//! `current_len=0`, and `lengths_stack` empty. Start the main loop.
|
||||
//! 2. Top of loop. The string at `i` is equal in length to `prefix_len`, so we prepend
|
||||
//! our first node: a **value node 44**, which requires a 2-byte varint. Increase
|
||||
//! `current_len` to 2.
|
||||
//! 3. Reduce `prefix_len` to 4, read our `key_ascii="k"`, and recalculate `i` and `j`
|
||||
//! _(this calculation is a long chunk of code in the builder impls)_. Since there is no
|
||||
//! other string with the prefix "adgh", `i` and `j` stay the same, we prepend an
|
||||
//! **ASCII node "k"**, increase `current_len` to 3, and continue the main loop.
|
||||
//! 4. Top of loop. The string at `i` is of length 5, but `prefix_len` is 4, so there is
|
||||
//! no value node to prepend.
|
||||
//! 5. Reduce `prefix_len` to 3, read our `key_ascii="h"`, and recalculate `i` and `j`.
|
||||
//! There are no other strings sharing the prefix "abg", so we prepend an
|
||||
//! **ASCII node "h"**, increase `current_len` to 4, and continue the main loop.
|
||||
//! 6. Top of loop. There is still no value node to prepend.
|
||||
//! 7. Reduce `prefix_len` to 2, read our `key_ascii="g"`, and recalculate `i` and `j`.
|
||||
//! We find that `i=1` and `j=4`, the range of strings sharing the prefix "ad". Since
|
||||
//! `i` or `j` changed, proceed to evaluate the branch node.
|
||||
//! 8. The last branch byte `ascii_j` for this prefix is "g", which is the same as `key_ascii`,
|
||||
//! so we are the _last_ target of a branch node. Push an entry onto `lengths_stack`:
|
||||
//! `BranchMeta { ascii: "g", cumulative_length: 4, local_length: 4, count: 1 }`.
|
||||
//! 9. The first branch byte `ascii_i` for this prefix is "e", which is NOT equal to `key_ascii`,
|
||||
//! so we are _not the first_ target of a branch node. We therefore start evaluating the
|
||||
//! string preceding where we were at the top of the current loop. We set `i=2`, `j=3`,
|
||||
//! `prefix_len=4` (length of the string at `i`), and continue the main loop.
|
||||
//! 10. Top of loop. Since the string at `i` is equal in length to `prefix_len`, we prepend a
|
||||
//! **value node 33** (which requires a 2-byte varint) and increase `current_len` to 2.
|
||||
//! 11. Reduce `prefix_len` to 3, read our `key_ascii="f"`, and recalculate `i` and `j`.
|
||||
//! They stay the same, so we prepend an **ASCII node "f"**, increase `current_len` to 3,
|
||||
//! and continue the main loop.
|
||||
//! 12. Top of loop. No value node this time.
|
||||
//! 13. Reduce `prefix_len` to 2, read our `key_ascii="e"`, and recalculate `i` and `j`.
|
||||
//! They go back to `i=1` and `j=4`.
|
||||
//! 14. The last branch byte `ascii_j` for this prefix is "g", which is NOT equal to `key_ascii`,
|
||||
//! so we are _not the last_ target of a branch node. We peek at the entry at the front of
|
||||
//! the lengths stack and use it to push another entry onto the stack:
|
||||
//! `BranchMeta { ascii: "e", cumulative_length: 7, local_length: 3, count: 2 }`
|
||||
//! 15. The first branch byte `ascii_i` for this prefix is "e", which is the same as `key_ascii`,
|
||||
//! wo we are the _first_ target of a branch node. We can therefore proceed to prepend the
|
||||
//! metadata for the branch node. We peek at the top of the stack and find that there are 2
|
||||
//! tries reachable from this branch and they have a total byte length of 5. We then pull off
|
||||
//! 2 entries from the stack into a local variable `branch_metas`. From here, we write out
|
||||
//! the **offset table**, **lookup table**, and **branch head node**, which are determined
|
||||
//! from the metadata entries. We set `current_len` to the length of the two tries plus the
|
||||
//! metadata, which happens to be 11. Then we return to the top of the main loop.
|
||||
//! 16. Top of loop. The string at `i` is length 2, which is the same as `prefix_len`, so we
|
||||
//! prepend a **value node 22** (2-byte varint) and increase `current_len` to 13.
|
||||
//! 17. Reduce `prefix_len` to 1, read our `key_ascii="d"`, and recalculate `i` and `j`.
|
||||
//! They stay the same, so we prepend an **ASCII node "d"**, increase `current_len` to 14,
|
||||
//! and continue the main loop.
|
||||
//! 18. Top of loop. No value node this time.
|
||||
//! 19. Reduce `prefix_len` to 0, read our `key_ascii="a"`, and recalculate `i` and `j`.
|
||||
//! They change to `i=0` and `j=4`, since all strings have the empty string as a prefix.
|
||||
//! However, `ascii_i` and `ascii_j` both equal `key_ascii`, so we prepend **ASCII node "a"**,
|
||||
//! increase `current_len` to 15, and continue the main loop.
|
||||
//! 16. Top of loop. The string at `i` is length 0, which is the same as `prefix_len`, so we
|
||||
//! prepend a **value node 11** and increase `current_len` to 16.
|
||||
//! 17. We can no longer reduce `prefix_len`, so our trie is complete.
|
||||
//!
|
||||
//! ## Perfect Hash Reordering
|
||||
//!
|
||||
//! When the PHF is added to the mix, the main change is that the strings are no longer in sorted
|
||||
//! order when they are in the trie. To resolve this issue, when adding a branch node, the target
|
||||
//! tries are rearranged in-place in the buffer to be in the correct order for the PHF.
|
||||
//!
|
||||
//! ## Example
|
||||
//!
|
||||
//! Here is the output of the trie described above.
|
||||
//!
|
||||
//! ```
|
||||
//! use zerotrie::ZeroTrieSimpleAscii;
|
||||
//!
|
||||
//! const DATA: [(&str, usize); 4] =
|
||||
//! [("", 11), ("ad", 22), ("adef", 33), ("adghk", 44)];
|
||||
//!
|
||||
//! // As demonstrated above, the required capacity for this trie is 16 bytes
|
||||
//! const TRIE: ZeroTrieSimpleAscii<[u8; 16]> =
|
||||
//! ZeroTrieSimpleAscii::from_sorted_str_tuples(&DATA);
|
||||
//!
|
||||
//! assert_eq!(
|
||||
//! TRIE.as_bytes(),
|
||||
//! &[
|
||||
//! 0x8B, // value node 11
|
||||
//! b'a', // ASCII node 'a'
|
||||
//! b'd', // ASCII node 'd'
|
||||
//! 0x90, // value node 22 lead byte
|
||||
//! 0x06, // value node 22 trail byte
|
||||
//! 0xC2, // branch node 2
|
||||
//! b'e', // first target of branch
|
||||
//! b'g', // second target of branch
|
||||
//! 3, // offset
|
||||
//! b'f', // ASCII node 'f'
|
||||
//! 0x90, // value node 33 lead byte
|
||||
//! 0x11, // value node 33 trail byte
|
||||
//! b'h', // ASCII node 'h'
|
||||
//! b'k', // ASCII node 'k'
|
||||
//! 0x90, // value node 44 lead byte
|
||||
//! 0x1C, // value node 44 trail byte
|
||||
//! ]
|
||||
//! );
|
||||
//!
|
||||
//! assert_eq!(TRIE.get(b""), Some(11));
|
||||
//! assert_eq!(TRIE.get(b"ad"), Some(22));
|
||||
//! assert_eq!(TRIE.get(b"adef"), Some(33));
|
||||
//! assert_eq!(TRIE.get(b"adghk"), Some(44));
|
||||
//! assert_eq!(TRIE.get(b"unknown"), None);
|
||||
//! ```
|
||||
|
||||
#![allow(clippy::panic)]
|
||||
|
||||
mod branch_meta;
|
||||
#[cfg(all(feature = "alloc", feature = "dense"))]
|
||||
pub(crate) mod dense;
|
||||
pub(crate) mod konst;
|
||||
#[cfg(feature = "litemap")]
|
||||
mod litemap;
|
||||
#[cfg(feature = "alloc")]
|
||||
pub(crate) mod nonconst;
|
||||
pub(crate) mod slice_indices;
|
||||
|
||||
use slice_indices::ByteSliceWithIndices;
|
||||
|
||||
use super::ZeroTrieSimpleAscii;
|
||||
|
||||
impl<const N: usize> ZeroTrieSimpleAscii<[u8; N]> {
|
||||
/// **Const Constructor:** Creates an [`ZeroTrieSimpleAscii`] from a sorted slice of keys and values.
|
||||
///
|
||||
/// This function needs to know the exact length of the resulting trie at compile time. To
|
||||
/// figure out `N`, first set `N` to be too large (say 0xFFFF), then look at the resulting
|
||||
/// compile error which will tell you how to set `N`, like this:
|
||||
///
|
||||
/// > the evaluated program panicked at 'Buffer too large. Size needed: 17'
|
||||
///
|
||||
/// That error message says you need to set `N` to 17.
|
||||
///
|
||||
/// Also see [`Self::from_sorted_str_tuples`].
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if `items` is not sorted or if `N` is not correct.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// Create a `const` [`ZeroTrieSimpleAscii`](crate::ZeroTrieSimpleAscii) at compile time:
|
||||
///
|
||||
/// ```
|
||||
/// use zerotrie::ZeroTrieSimpleAscii;
|
||||
///
|
||||
/// // The required capacity for this trie happens to be 17 bytes
|
||||
/// const TRIE: ZeroTrieSimpleAscii<[u8; 17]> =
|
||||
/// ZeroTrieSimpleAscii::from_sorted_u8_tuples(&[
|
||||
/// (b"bar", 2),
|
||||
/// (b"bazzoo", 3),
|
||||
/// (b"foo", 1),
|
||||
/// ]);
|
||||
///
|
||||
/// assert_eq!(TRIE.get(b"foo"), Some(1));
|
||||
/// assert_eq!(TRIE.get(b"bar"), Some(2));
|
||||
/// assert_eq!(TRIE.get(b"bazzoo"), Some(3));
|
||||
/// assert_eq!(TRIE.get(b"unknown"), None);
|
||||
/// ```
|
||||
///
|
||||
/// Panics if strings are not sorted:
|
||||
///
|
||||
/// ```compile_fail,E0080
|
||||
/// # use zerotrie::ZeroTrieSimpleAscii;
|
||||
/// const TRIE: ZeroTrieSimpleAscii<[u8; 17]> = ZeroTrieSimpleAscii::from_sorted_u8_tuples(&[
|
||||
/// (b"foo", 1),
|
||||
/// (b"bar", 2),
|
||||
/// (b"bazzoo", 3),
|
||||
/// ]);
|
||||
/// ```
|
||||
///
|
||||
/// Panics if capacity is too small:
|
||||
///
|
||||
/// ```compile_fail,E0080
|
||||
/// # use zerotrie::ZeroTrieSimpleAscii;
|
||||
/// const TRIE: ZeroTrieSimpleAscii<[u8; 15]> = ZeroTrieSimpleAscii::from_sorted_u8_tuples(&[
|
||||
/// (b"bar", 2),
|
||||
/// (b"bazzoo", 3),
|
||||
/// (b"foo", 1),
|
||||
/// ]);
|
||||
/// ```
|
||||
///
|
||||
/// Panics if capacity is too large:
|
||||
///
|
||||
/// ```compile_fail,E0080
|
||||
/// # use zerotrie::ZeroTrieSimpleAscii;
|
||||
/// const TRIE: ZeroTrieSimpleAscii<[u8; 20]> = ZeroTrieSimpleAscii::from_sorted_u8_tuples(&[
|
||||
/// (b"bar", 2),
|
||||
/// (b"bazzoo", 3),
|
||||
/// (b"foo", 1),
|
||||
/// ]);
|
||||
/// ```
|
||||
pub const fn from_sorted_u8_tuples(tuples: &[(&[u8], usize)]) -> Self {
|
||||
use konst::*;
|
||||
let byte_str_slice = ByteSliceWithIndices::from_byte_slice(tuples);
|
||||
let s = ZeroTrieBuilderConst::<N>::from_tuple_slice::<100>(byte_str_slice);
|
||||
Self::from_store(s.build_or_panic())
|
||||
}
|
||||
|
||||
/// **Const Constructor:** Creates an [`ZeroTrieSimpleAscii`] from a sorted slice of keys and values.
|
||||
///
|
||||
/// This function needs to know the exact length of the resulting trie at compile time. To
|
||||
/// figure out `N`, first set `N` to be too large (say 0xFFFF), then look at the resulting
|
||||
/// compile error which will tell you how to set `N`, like this:
|
||||
///
|
||||
/// > the evaluated program panicked at 'Buffer too large. Size needed: 17'
|
||||
///
|
||||
/// That error message says you need to set `N` to 17.
|
||||
///
|
||||
/// Also see [`Self::from_sorted_u8_tuples`].
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if `items` is not sorted, if `N` is not correct, or if any of the strings contain
|
||||
/// non-ASCII characters.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// Create a `const` [`ZeroTrieSimpleAscii`](crate::ZeroTrieSimpleAscii) at compile time:
|
||||
///
|
||||
/// ```
|
||||
/// use zerotrie::ZeroTrieSimpleAscii;
|
||||
///
|
||||
/// // The required capacity for this trie happens to be 17 bytes
|
||||
/// const TRIE: ZeroTrieSimpleAscii<[u8; 17]> =
|
||||
/// ZeroTrieSimpleAscii::from_sorted_str_tuples(&[
|
||||
/// ("bar", 2),
|
||||
/// ("bazzoo", 3),
|
||||
/// ("foo", 1),
|
||||
/// ]);
|
||||
///
|
||||
/// assert_eq!(TRIE.get(b"foo"), Some(1));
|
||||
/// assert_eq!(TRIE.get(b"bar"), Some(2));
|
||||
/// assert_eq!(TRIE.get(b"bazzoo"), Some(3));
|
||||
/// assert_eq!(TRIE.get(b"unknown"), None);
|
||||
/// ```
|
||||
///
|
||||
/// Panics if the strings are not ASCII:
|
||||
///
|
||||
/// ```compile_fail,E0080
|
||||
/// # use zerotrie::ZeroTrieSimpleAscii;
|
||||
/// const TRIE: ZeroTrieSimpleAscii<[u8; 100]> = ZeroTrieSimpleAscii::from_sorted_str_tuples(&[
|
||||
/// ("bár", 2),
|
||||
/// ("båzzöo", 3),
|
||||
/// ("foo", 1),
|
||||
/// ]);
|
||||
/// ```
|
||||
pub const fn from_sorted_str_tuples(tuples: &[(&str, usize)]) -> Self {
|
||||
use konst::*;
|
||||
let byte_str_slice = ByteSliceWithIndices::from_str_slice(tuples);
|
||||
// 100 is the value of `K`, the size of the lengths stack. If compile errors are
|
||||
// encountered, this number may need to be increased.
|
||||
let s = ZeroTrieBuilderConst::<N>::from_tuple_slice::<100>(byte_str_slice);
|
||||
Self::from_store(s.build_or_panic())
|
||||
}
|
||||
}
|
||||
+427
@@ -0,0 +1,427 @@
|
||||
// This file is part of ICU4X. For terms of use, please see the file
|
||||
// called LICENSE at the top level of the ICU4X source tree
|
||||
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
|
||||
|
||||
use core::cmp::Ordering;
|
||||
|
||||
use super::super::branch_meta::BranchMeta;
|
||||
use super::store::NonConstLengthsStack;
|
||||
use super::store::TrieBuilderStore;
|
||||
use crate::builder::slice_indices::ByteSliceWithIndices;
|
||||
use crate::byte_phf::PerfectByteHashMapCacheOwned;
|
||||
use crate::error::ZeroTrieBuildError;
|
||||
use crate::options::*;
|
||||
use crate::varint;
|
||||
use alloc::vec::Vec;
|
||||
|
||||
/// A low-level builder for [`ZeroTrie`](crate::ZeroTrie). Supports all options.
|
||||
pub(crate) struct ZeroTrieBuilder<S> {
|
||||
data: S,
|
||||
phf_cache: PerfectByteHashMapCacheOwned,
|
||||
options: ZeroTrieBuilderOptions,
|
||||
}
|
||||
|
||||
impl<S: TrieBuilderStore> ZeroTrieBuilder<S> {
|
||||
/// Returns the trie data as a `Vec<u8>`.
|
||||
pub fn to_bytes(&self) -> Vec<u8> {
|
||||
self.data.atbs_to_bytes()
|
||||
}
|
||||
|
||||
/// Prepends a byte value to the front of the builder. If it is ASCII, an ASCII
|
||||
/// node is prepended. If it is non-ASCII, if there is already a span node at
|
||||
/// the front, we modify the span node to add the new byte; otherwise, we create
|
||||
/// a new span node. Returns the delta in length, which is either 1 or 2.
|
||||
fn prepend_ascii(&mut self, ascii: u8) -> Result<usize, ZeroTrieBuildError> {
|
||||
if ascii <= 127 {
|
||||
self.data.atbs_push_front(ascii);
|
||||
Ok(1)
|
||||
} else if matches!(self.options.ascii_mode, AsciiMode::BinarySpans) {
|
||||
if let Some(old_front) = self.data.atbs_pop_front() {
|
||||
let old_byte_len = self.data.atbs_len() + 1;
|
||||
if old_front & 0b11100000 == 0b10100000 {
|
||||
// Extend an existing span
|
||||
// Unwrap OK: there is a varint at this location in the buffer
|
||||
#[expect(clippy::unwrap_used)]
|
||||
let old_span_size =
|
||||
varint::try_read_varint_meta3_from_tstore(old_front, &mut self.data)
|
||||
.unwrap();
|
||||
self.data.atbs_push_front(ascii);
|
||||
let varint_array = varint::write_varint_meta3(old_span_size + 1);
|
||||
self.data.atbs_extend_front(varint_array.as_slice());
|
||||
self.data.atbs_bitor_assign(0, 0b10100000);
|
||||
let new_byte_len = self.data.atbs_len();
|
||||
return Ok(new_byte_len - old_byte_len);
|
||||
} else {
|
||||
self.data.atbs_push_front(old_front);
|
||||
}
|
||||
}
|
||||
// Create a new span
|
||||
self.data.atbs_push_front(ascii);
|
||||
self.data.atbs_push_front(0b10100001);
|
||||
Ok(2)
|
||||
} else {
|
||||
Err(ZeroTrieBuildError::NonAsciiError)
|
||||
}
|
||||
}
|
||||
|
||||
/// Prepends a value node to the front of the builder. Returns the
|
||||
/// delta in length, which depends on the size of the varint.
|
||||
#[must_use]
|
||||
fn prepend_value(&mut self, value: usize) -> usize {
|
||||
let varint_array = varint::write_varint_meta3(value);
|
||||
self.data.atbs_extend_front(varint_array.as_slice());
|
||||
self.data.atbs_bitor_assign(0, 0b10000000);
|
||||
varint_array.len()
|
||||
}
|
||||
|
||||
/// Prepends a branch node to the front of the builder. Returns the
|
||||
/// delta in length, which depends on the size of the varint.
|
||||
#[must_use]
|
||||
fn prepend_branch(&mut self, value: usize) -> usize {
|
||||
let varint_array = varint::write_varint_meta2(value);
|
||||
self.data.atbs_extend_front(varint_array.as_slice());
|
||||
self.data.atbs_bitor_assign(0, 0b11000000);
|
||||
varint_array.len()
|
||||
}
|
||||
|
||||
/// Prepends multiple arbitrary bytes to the front of the builder. Returns the
|
||||
/// delta in length, which is the length of the slice.
|
||||
#[must_use]
|
||||
fn prepend_slice(&mut self, s: &[u8]) -> usize {
|
||||
self.data.atbs_extend_front(s);
|
||||
s.len()
|
||||
}
|
||||
|
||||
/// Builds a [`ZeroTrie`](crate::ZeroTrie) from an iterator of bytes. It first collects and sorts the iterator.
|
||||
pub fn from_bytes_iter<K: AsRef<[u8]>, I: IntoIterator<Item = (K, usize)>>(
|
||||
iter: I,
|
||||
options: ZeroTrieBuilderOptions,
|
||||
) -> Result<Self, ZeroTrieBuildError> {
|
||||
let items = Vec::<(K, usize)>::from_iter(iter);
|
||||
let mut items = items
|
||||
.iter()
|
||||
.map(|(k, v)| (k.as_ref(), *v))
|
||||
.collect::<Vec<(&[u8], usize)>>();
|
||||
items.sort_by(|a, b| cmp_keys_values(options, *a, *b));
|
||||
let ascii_str_slice = items.as_slice();
|
||||
let byte_str_slice = ByteSliceWithIndices::from_byte_slice(ascii_str_slice);
|
||||
Self::from_sorted_tuple_slice_impl(byte_str_slice, options)
|
||||
}
|
||||
|
||||
/// Builds a [`ZeroTrie`](crate::ZeroTrie) with the given items and options. Assumes that the items are sorted,
|
||||
/// except for a case-insensitive trie where the items are re-sorted.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// May panic if the items are not sorted.
|
||||
pub fn from_sorted_tuple_slice(
|
||||
items: ByteSliceWithIndices,
|
||||
options: ZeroTrieBuilderOptions,
|
||||
) -> Result<Self, ZeroTrieBuildError> {
|
||||
if matches!(options.case_sensitivity, CaseSensitivity::IgnoreCase) {
|
||||
// We need to re-sort the items with our custom comparator.
|
||||
let mut items_vec = items.to_vec_u8();
|
||||
items_vec.sort_by(|a, b| cmp_keys_values(options, *a, *b));
|
||||
Self::from_sorted_tuple_slice_impl(
|
||||
ByteSliceWithIndices::from_byte_slice(&items_vec),
|
||||
options,
|
||||
)
|
||||
} else {
|
||||
Self::from_sorted_tuple_slice_impl(items, options)
|
||||
}
|
||||
}
|
||||
|
||||
/// Internal constructor that does not re-sort the items.
|
||||
fn from_sorted_tuple_slice_impl(
|
||||
items: ByteSliceWithIndices,
|
||||
options: ZeroTrieBuilderOptions,
|
||||
) -> Result<Self, ZeroTrieBuildError> {
|
||||
#[allow(clippy::indexing_slicing)] // a debug assertion only
|
||||
let mut i = 0;
|
||||
while i + 1 < items.len() {
|
||||
let ab0 = items.get_or_panic(i);
|
||||
let ab1 = items.get_or_panic(i + 1);
|
||||
debug_assert!(cmp_keys_values(options, (ab0.0, ab0.1), (ab1.0, ab1.1)).is_lt());
|
||||
i += 1;
|
||||
}
|
||||
|
||||
let mut result = Self {
|
||||
data: S::atbs_new_empty(),
|
||||
phf_cache: PerfectByteHashMapCacheOwned::new_empty(),
|
||||
options,
|
||||
};
|
||||
let total_size = result.create(items)?;
|
||||
debug_assert!(total_size == result.data.atbs_len());
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// The actual builder algorithm. For an explanation, see [`crate::builder`].
|
||||
#[expect(clippy::unwrap_used, clippy::indexing_slicing)] // lots of indexing, but all indexes should be in range
|
||||
fn create(&mut self, all_items: ByteSliceWithIndices) -> Result<usize, ZeroTrieBuildError> {
|
||||
let mut prefix_len = match all_items.last() {
|
||||
Some(x) => x.0.len(),
|
||||
// Empty slice:
|
||||
None => return Ok(0),
|
||||
};
|
||||
// Initialize the main loop to point at the last string.
|
||||
let mut lengths_stack = NonConstLengthsStack::new();
|
||||
let mut i = all_items.len() - 1;
|
||||
let mut j = all_items.len();
|
||||
let mut current_len = 0;
|
||||
// Start the main loop.
|
||||
loop {
|
||||
let item_i = all_items.get_or_panic(i);
|
||||
let item_j = all_items.get_or_panic(j - 1);
|
||||
debug_assert!(crate::builder::slice_indices::prefix_eq_or_panic(
|
||||
item_i.0, item_j.0, prefix_len
|
||||
));
|
||||
// Check if we need to add a value node here.
|
||||
if item_i.0.len() == prefix_len {
|
||||
let len = self.prepend_value(item_i.1);
|
||||
current_len += len;
|
||||
}
|
||||
if prefix_len == 0 {
|
||||
// All done! Leave the main loop.
|
||||
break;
|
||||
}
|
||||
// Reduce the prefix length by 1 and recalculate i and j.
|
||||
prefix_len -= 1;
|
||||
let mut new_i = i;
|
||||
let mut new_j = j;
|
||||
let mut ascii_i = item_i.0[prefix_len];
|
||||
let mut ascii_j = item_j.0[prefix_len];
|
||||
debug_assert_eq!(ascii_i, ascii_j);
|
||||
let key_ascii = ascii_i;
|
||||
loop {
|
||||
if new_i == 0 {
|
||||
break;
|
||||
}
|
||||
let candidate = all_items.get_or_panic(new_i - 1).0;
|
||||
if candidate.len() < prefix_len {
|
||||
// Too short
|
||||
break;
|
||||
}
|
||||
if crate::builder::slice_indices::prefix_eq_or_panic(
|
||||
item_i.0, candidate, prefix_len,
|
||||
) {
|
||||
new_i -= 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
if candidate.len() == prefix_len {
|
||||
// A string that equals the prefix does not take part in the branch node.
|
||||
break;
|
||||
}
|
||||
let candidate = candidate[prefix_len];
|
||||
if candidate != ascii_i {
|
||||
ascii_i = candidate;
|
||||
}
|
||||
}
|
||||
loop {
|
||||
if new_j == all_items.len() {
|
||||
break;
|
||||
}
|
||||
let candidate = all_items.get_or_panic(new_j).0;
|
||||
if candidate.len() < prefix_len {
|
||||
// Too short
|
||||
break;
|
||||
}
|
||||
if crate::builder::slice_indices::prefix_eq_or_panic(
|
||||
item_j.0, candidate, prefix_len,
|
||||
) {
|
||||
new_j += 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
if candidate.len() == prefix_len {
|
||||
unreachable!("A shorter string should be earlier in the sequence");
|
||||
}
|
||||
let candidate = candidate[prefix_len];
|
||||
if candidate != ascii_j {
|
||||
ascii_j = candidate;
|
||||
}
|
||||
}
|
||||
// If there are no different bytes at this prefix level, we can add an ASCII or Span
|
||||
// node and then continue to the next iteration of the main loop.
|
||||
if ascii_i == key_ascii && ascii_j == key_ascii {
|
||||
let len = self.prepend_ascii(key_ascii)?;
|
||||
current_len += len;
|
||||
if matches!(self.options.case_sensitivity, CaseSensitivity::IgnoreCase)
|
||||
&& i == new_i + 2
|
||||
{
|
||||
// This can happen if two strings were picked up, each with a different case
|
||||
return Err(ZeroTrieBuildError::MixedCase);
|
||||
}
|
||||
debug_assert!(
|
||||
i == new_i || i == new_i + 1,
|
||||
"only the exact prefix string can be picked up at this level: {key_ascii}"
|
||||
);
|
||||
i = new_i;
|
||||
debug_assert_eq!(j, new_j);
|
||||
continue;
|
||||
}
|
||||
// If i and j changed, we are a target of a branch node.
|
||||
if ascii_j == key_ascii {
|
||||
// We are the _last_ target of a branch node.
|
||||
lengths_stack.push(BranchMeta {
|
||||
ascii: key_ascii,
|
||||
cumulative_length: current_len,
|
||||
local_length: current_len,
|
||||
count: 1,
|
||||
});
|
||||
} else {
|
||||
// We are the _not the last_ target of a branch node.
|
||||
let BranchMeta {
|
||||
cumulative_length,
|
||||
count,
|
||||
..
|
||||
} = lengths_stack.peek_or_panic();
|
||||
lengths_stack.push(BranchMeta {
|
||||
ascii: key_ascii,
|
||||
cumulative_length: cumulative_length + current_len,
|
||||
local_length: current_len,
|
||||
count: count + 1,
|
||||
});
|
||||
}
|
||||
if ascii_i != key_ascii {
|
||||
// We are _not the first_ target of a branch node.
|
||||
// Set the cursor to the previous string and continue the loop.
|
||||
j = i;
|
||||
i -= 1;
|
||||
prefix_len = all_items.get_or_panic(i).0.len();
|
||||
current_len = 0;
|
||||
continue;
|
||||
}
|
||||
// Branch (first)
|
||||
// std::println!("lengths_stack: {lengths_stack:?}");
|
||||
let (total_length, total_count) = {
|
||||
let BranchMeta {
|
||||
cumulative_length,
|
||||
count,
|
||||
..
|
||||
} = lengths_stack.peek_or_panic();
|
||||
(cumulative_length, count)
|
||||
};
|
||||
let mut branch_metas = lengths_stack.pop_many_or_panic(total_count);
|
||||
let original_keys = branch_metas.map_to_ascii_bytes();
|
||||
if matches!(self.options.case_sensitivity, CaseSensitivity::IgnoreCase) {
|
||||
// Check to see if we have the same letter in two different cases
|
||||
let mut seen_ascii_alpha = [false; 26];
|
||||
for c in original_keys.as_const_slice().as_slice() {
|
||||
if c.is_ascii_alphabetic() {
|
||||
let i = (c.to_ascii_lowercase() - b'a') as usize;
|
||||
#[allow(clippy::indexing_slicing)] // 26 letters
|
||||
if seen_ascii_alpha[i] {
|
||||
return Err(ZeroTrieBuildError::MixedCase);
|
||||
} else {
|
||||
seen_ascii_alpha[i] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let use_phf = matches!(self.options.phf_mode, PhfMode::UsePhf);
|
||||
let opt_phf_vec = if total_count > 15 && use_phf {
|
||||
let phf_vec = self
|
||||
.phf_cache
|
||||
.try_get_or_insert(original_keys.as_const_slice().as_slice().to_vec())?;
|
||||
// Put everything in order via bubble sort
|
||||
// Note: branch_metas is stored in reverse order (0 = last element)
|
||||
loop {
|
||||
let mut l = total_count - 1;
|
||||
let mut changes = 0;
|
||||
let mut start = 0;
|
||||
while l > 0 {
|
||||
let a = *branch_metas.as_const_slice().get_or_panic(l);
|
||||
let b = *branch_metas.as_const_slice().get_or_panic(l - 1);
|
||||
let a_idx = phf_vec.keys().iter().position(|x| x == &a.ascii).unwrap();
|
||||
let b_idx = phf_vec.keys().iter().position(|x| x == &b.ascii).unwrap();
|
||||
if a_idx > b_idx {
|
||||
// std::println!("{a:?} <=> {b:?} ({phf_vec:?})");
|
||||
// This method call won't panic because the ranges are valid.
|
||||
self.data.atbs_swap_ranges(
|
||||
start,
|
||||
start + a.local_length,
|
||||
start + a.local_length + b.local_length,
|
||||
);
|
||||
branch_metas.swap_or_panic(l - 1, l);
|
||||
start += b.local_length;
|
||||
changes += 1;
|
||||
// FIXME: fix the `length` field
|
||||
} else {
|
||||
start += a.local_length;
|
||||
}
|
||||
l -= 1;
|
||||
}
|
||||
if changes == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Some(phf_vec)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// Write out the offset table
|
||||
current_len = total_length;
|
||||
let w = (usize::BITS as usize - (total_length.leading_zeros() as usize) - 1) / 8;
|
||||
if w > 3 && matches!(self.options.capacity_mode, CapacityMode::Normal) {
|
||||
return Err(ZeroTrieBuildError::CapacityExceeded);
|
||||
}
|
||||
let mut k = 0;
|
||||
while k <= w {
|
||||
self.data.atbs_prepend_n_zeros(total_count - 1);
|
||||
current_len += total_count - 1;
|
||||
let mut l = 0;
|
||||
let mut length_to_write = 0;
|
||||
while l < total_count {
|
||||
let BranchMeta { local_length, .. } = *branch_metas
|
||||
.as_const_slice()
|
||||
.get_or_panic(total_count - l - 1);
|
||||
let mut adjusted_length = length_to_write;
|
||||
let mut m = 0;
|
||||
while m < k {
|
||||
adjusted_length >>= 8;
|
||||
m += 1;
|
||||
}
|
||||
if l > 0 {
|
||||
self.data.atbs_bitor_assign(l - 1, adjusted_length as u8);
|
||||
}
|
||||
l += 1;
|
||||
length_to_write += local_length;
|
||||
}
|
||||
k += 1;
|
||||
}
|
||||
// Write out the lookup table
|
||||
assert!(0 < total_count && total_count <= 256);
|
||||
let branch_value = (w << 8) + (total_count & 0xff);
|
||||
if let Some(phf_vec) = opt_phf_vec {
|
||||
self.data.atbs_extend_front(phf_vec.as_bytes());
|
||||
let phf_len = phf_vec.as_bytes().len();
|
||||
let branch_len = self.prepend_branch(branch_value);
|
||||
current_len += phf_len + branch_len;
|
||||
} else {
|
||||
let search_len = self.prepend_slice(original_keys.as_slice());
|
||||
let branch_len = self.prepend_branch(branch_value);
|
||||
current_len += search_len + branch_len;
|
||||
}
|
||||
i = new_i;
|
||||
j = new_j;
|
||||
}
|
||||
assert!(lengths_stack.is_empty());
|
||||
Ok(current_len)
|
||||
}
|
||||
}
|
||||
|
||||
fn cmp_keys_values(
|
||||
options: ZeroTrieBuilderOptions,
|
||||
a: (&[u8], usize),
|
||||
b: (&[u8], usize),
|
||||
) -> Ordering {
|
||||
if matches!(options.case_sensitivity, CaseSensitivity::Sensitive) {
|
||||
a.0.cmp(b.0)
|
||||
} else {
|
||||
let a_iter = a.0.iter().map(|x| x.to_ascii_lowercase());
|
||||
let b_iter = b.0.iter().map(|x| x.to_ascii_lowercase());
|
||||
Iterator::cmp(a_iter, b_iter)
|
||||
}
|
||||
.then_with(|| a.1.cmp(&b.1))
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
// This file is part of ICU4X. For terms of use, please see the file
|
||||
// called LICENSE at the top level of the ICU4X source tree
|
||||
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
|
||||
|
||||
mod builder;
|
||||
mod store;
|
||||
|
||||
pub(crate) use builder::*;
|
||||
pub(crate) use store::TrieBuilderStore;
|
||||
+192
@@ -0,0 +1,192 @@
|
||||
// This file is part of ICU4X. For terms of use, please see the file
|
||||
// called LICENSE at the top level of the ICU4X source tree
|
||||
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
|
||||
|
||||
//! This module contains internal collections for the non-const builder.
|
||||
|
||||
use super::super::branch_meta::BranchMeta;
|
||||
use super::super::konst::ConstArrayBuilder;
|
||||
use alloc::collections::VecDeque;
|
||||
use alloc::vec::Vec;
|
||||
|
||||
/// A trait applied to a data structure for building a [`ZeroTrie`](crate::ZeroTrie).
|
||||
pub(crate) trait TrieBuilderStore {
|
||||
/// Create a new empty store.
|
||||
fn atbs_new_empty() -> Self;
|
||||
|
||||
/// Return the length in bytes of the store.
|
||||
fn atbs_len(&self) -> usize;
|
||||
|
||||
/// Push a byte to the front of the store.
|
||||
fn atbs_push_front(&mut self, byte: u8);
|
||||
|
||||
/// Push multiple bytes to the front of the store.
|
||||
fn atbs_extend_front(&mut self, other: &[u8]);
|
||||
|
||||
/// Read the store into a `Vec<u8>`.
|
||||
fn atbs_to_bytes(&self) -> Vec<u8>;
|
||||
|
||||
/// Perform the operation `self[index] |= bits`
|
||||
fn atbs_bitor_assign(&mut self, index: usize, bits: u8);
|
||||
|
||||
/// Swap the adjacent ranges `self[start..mid]` and `self[mid..limit]`.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if the specified ranges are invalid.
|
||||
fn atbs_swap_ranges(&mut self, start: usize, mid: usize, limit: usize);
|
||||
|
||||
/// Remove and return the first element in the store, or `None` if empty.
|
||||
fn atbs_pop_front(&mut self) -> Option<u8>;
|
||||
|
||||
/// Prepend `n` zeros to the front of the store.
|
||||
fn atbs_prepend_n_zeros(&mut self, n: usize) {
|
||||
let mut i = 0;
|
||||
while i < n {
|
||||
self.atbs_push_front(0);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TrieBuilderStore for VecDeque<u8> {
|
||||
fn atbs_new_empty() -> Self {
|
||||
VecDeque::new()
|
||||
}
|
||||
fn atbs_len(&self) -> usize {
|
||||
self.len()
|
||||
}
|
||||
fn atbs_push_front(&mut self, byte: u8) {
|
||||
self.push_front(byte);
|
||||
}
|
||||
fn atbs_extend_front(&mut self, other: &[u8]) {
|
||||
self.reserve(other.len());
|
||||
for b in other.iter().rev() {
|
||||
self.push_front(*b);
|
||||
}
|
||||
}
|
||||
fn atbs_to_bytes(&self) -> Vec<u8> {
|
||||
let mut v = Vec::with_capacity(self.len());
|
||||
let (a, b) = self.as_slices();
|
||||
v.extend(a);
|
||||
v.extend(b);
|
||||
v
|
||||
}
|
||||
fn atbs_bitor_assign(&mut self, index: usize, bits: u8) {
|
||||
self[index] |= bits;
|
||||
}
|
||||
/// # Panics
|
||||
/// Panics if the specified ranges are invalid.
|
||||
#[allow(clippy::panic)] // documented
|
||||
fn atbs_swap_ranges(&mut self, mut start: usize, mut mid: usize, mut limit: usize) {
|
||||
if start > mid || mid > limit {
|
||||
panic!("Invalid args to atbs_swap_ranges(): start > mid || mid > limit");
|
||||
}
|
||||
if limit > self.len() {
|
||||
panic!(
|
||||
"Invalid args to atbs_swap_ranges(): limit out of range: {limit} > {}",
|
||||
self.len()
|
||||
);
|
||||
}
|
||||
// The following algorithm is an in-place swap of two adjacent ranges of potentially
|
||||
// different lengths. Would make a good coding interview question.
|
||||
loop {
|
||||
if start == mid || mid == limit {
|
||||
return;
|
||||
}
|
||||
let len0 = mid - start;
|
||||
let len1 = limit - mid;
|
||||
let mut i = start;
|
||||
let mut j = limit - core::cmp::min(len0, len1);
|
||||
while j < limit {
|
||||
self.swap(i, j);
|
||||
i += 1;
|
||||
j += 1;
|
||||
}
|
||||
if len0 < len1 {
|
||||
mid = start + len0;
|
||||
limit -= len0;
|
||||
} else {
|
||||
start += len1;
|
||||
mid = limit - len1;
|
||||
}
|
||||
}
|
||||
}
|
||||
fn atbs_pop_front(&mut self) -> Option<u8> {
|
||||
self.pop_front()
|
||||
}
|
||||
}
|
||||
|
||||
/// A data structure that holds any number of [`BranchMeta`] items.
|
||||
pub(crate) struct NonConstLengthsStack {
|
||||
data: Vec<BranchMeta>,
|
||||
}
|
||||
|
||||
impl core::fmt::Debug for NonConstLengthsStack {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
self.as_slice().fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
impl NonConstLengthsStack {
|
||||
/// Creates a new empty [`NonConstLengthsStack`].
|
||||
pub const fn new() -> Self {
|
||||
Self { data: Vec::new() }
|
||||
}
|
||||
|
||||
/// Returns whether the stack is empty.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.data.is_empty()
|
||||
}
|
||||
|
||||
/// Adds a [`BranchMeta`] to the stack.
|
||||
pub fn push(&mut self, meta: BranchMeta) {
|
||||
self.data.push(meta);
|
||||
}
|
||||
|
||||
/// Returns a copy of the [`BranchMeta`] on the top of the stack, panicking if
|
||||
/// the stack is empty.
|
||||
#[allow(clippy::unwrap_used)] // "panic" is in the method name
|
||||
pub fn peek_or_panic(&self) -> BranchMeta {
|
||||
*self.data.last().unwrap()
|
||||
}
|
||||
|
||||
/// Removes many [`BranchMeta`]s from the stack, returning them in a [`ConstArrayBuilder`].
|
||||
pub fn pop_many_or_panic(&mut self, len: usize) -> ConstArrayBuilder<256, BranchMeta> {
|
||||
debug_assert!(len <= 256);
|
||||
let mut result = ConstArrayBuilder::new_empty([BranchMeta::default(); 256], 256);
|
||||
let mut ix = 0;
|
||||
loop {
|
||||
if ix == len {
|
||||
break;
|
||||
}
|
||||
let i = self.data.len() - ix - 1;
|
||||
// Won't panic because len <= 256
|
||||
result.const_push_front_or_panic(match self.data.get(i) {
|
||||
Some(x) => *x,
|
||||
None => unreachable!("Not enough items in the ConstLengthsStack"),
|
||||
});
|
||||
ix += 1;
|
||||
}
|
||||
self.data.truncate(self.data.len() - len);
|
||||
result
|
||||
}
|
||||
|
||||
/// Non-const function that returns the initialized elements as a slice.
|
||||
fn as_slice(&self) -> &[BranchMeta] {
|
||||
&self.data
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_swap_ranges() {
|
||||
let s = b"..abcdefghijkl=";
|
||||
let mut s = s.iter().copied().collect::<VecDeque<u8>>();
|
||||
s.atbs_swap_ranges(2, 7, 14);
|
||||
assert_eq!(s.atbs_to_bytes(), b"..fghijklabcde=");
|
||||
}
|
||||
}
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
// This file is part of ICU4X. For terms of use, please see the file
|
||||
// called LICENSE at the top level of the ICU4X source tree
|
||||
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
|
||||
|
||||
#[cfg(feature = "alloc")]
|
||||
use alloc::vec::Vec;
|
||||
|
||||
/// Const function to evaluate `a < b` lexicographically.
|
||||
const fn is_less_than(a: &[u8], b: &[u8]) -> bool {
|
||||
let mut i = 0;
|
||||
#[allow(clippy::indexing_slicing, reason = "bounds checked in while loop")]
|
||||
while i < a.len() && i < b.len() {
|
||||
if a[i] < b[i] {
|
||||
return true;
|
||||
}
|
||||
if a[i] > b[i] {
|
||||
return false;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
a.len() < b.len()
|
||||
}
|
||||
|
||||
/// Const function to evaluate `a[..prefix_len] == b[..prefix_len]`
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if `prefix_len` is longer than either `a` or `b`.
|
||||
pub(crate) const fn prefix_eq_or_panic(a: &[u8], b: &[u8], prefix_len: usize) -> bool {
|
||||
let mut i = 0;
|
||||
#[allow(clippy::indexing_slicing, reason = "documented panic")]
|
||||
while i < prefix_len {
|
||||
if a[i] != b[i] {
|
||||
return false;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// An abstraction over a slice of key-value pairs that can have either `&[u8]`
|
||||
/// or `&str` keys. This is used in the builder to avoid unsound casts.
|
||||
#[derive(Copy, Clone)]
|
||||
pub(crate) enum ByteSliceWithIndices<'a> {
|
||||
Bytes(&'a [(&'a [u8], usize)]),
|
||||
Str(&'a [(&'a str, usize)]),
|
||||
}
|
||||
|
||||
impl<'a> ByteSliceWithIndices<'a> {
|
||||
pub const fn from_byte_slice(s: &'a [(&'a [u8], usize)]) -> Self {
|
||||
Self::Bytes(s)
|
||||
}
|
||||
|
||||
pub const fn from_str_slice(s: &'a [(&'a str, usize)]) -> Self {
|
||||
Self::Str(s)
|
||||
}
|
||||
|
||||
pub const fn len(&self) -> usize {
|
||||
match self {
|
||||
Self::Bytes(s) => s.len(),
|
||||
Self::Str(s) => s.len(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets the bytes and index at `index`
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics when `index >= self.len()`
|
||||
#[allow(clippy::indexing_slicing, reason = "documented")]
|
||||
pub const fn get_or_panic(&self, index: usize) -> (&'a [u8], usize) {
|
||||
match self {
|
||||
Self::Bytes(s) => s[index],
|
||||
Self::Str(s) => {
|
||||
let (key, value) = s[index];
|
||||
(key.as_bytes(), value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn last(&self) -> Option<(&'a [u8], usize)> {
|
||||
if self.len() == 0 {
|
||||
None
|
||||
} else {
|
||||
Some(self.get_or_panic(self.len() - 1))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "alloc")]
|
||||
pub fn to_vec_u8(self) -> Vec<(&'a [u8], usize)> {
|
||||
match self {
|
||||
Self::Bytes(s) => s.to_vec(),
|
||||
Self::Str(s) => s.iter().map(|(k, v)| (k.as_bytes(), *v)).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn is_sorted(self) -> bool {
|
||||
let mut i = 0;
|
||||
let mut prev: Option<&'a [u8]> = None;
|
||||
|
||||
while i < self.len() {
|
||||
let (ascii_str, _) = self.get_or_panic(i);
|
||||
if let Some(prev) = prev {
|
||||
if !is_less_than(prev, ascii_str) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
prev = Some(ascii_str);
|
||||
i += 1;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(feature = "alloc")]
|
||||
pub fn is_all_ascii(&self) -> bool {
|
||||
match self {
|
||||
Self::Bytes(s) => s
|
||||
.iter()
|
||||
.all(|(slice, _)| slice.iter().all(|c| c.is_ascii())),
|
||||
Self::Str(s) => s
|
||||
.iter()
|
||||
.all(|(slice, _)| slice.as_bytes().iter().all(|c| c.is_ascii())),
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user