| 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 |
//! Impls for functions gated on the "litemap" feature. |
| 6 |
|
| 7 |
use super::konst::*; |
| 8 |
use crate::builder::slice_indices::ByteSliceWithIndices; |
| 9 |
use crate::error::ZeroTrieBuildError; |
| 10 |
use crate::zerotrie::ZeroTrieSimpleAscii; |
| 11 |
use crate::ZeroTrie; |
| 12 |
use alloc::vec::Vec; |
| 13 |
use core::borrow::Borrow; |
| 14 |
use litemap::LiteMap; |
| 15 |
|
| 16 |
impl ZeroTrieSimpleAscii<Vec<u8>> { |
| 17 |
#[doc(hidden)] |
| 18 |
pub fn try_from_litemap_with_const_builder<'a, S>( |
| 19 |
items: &LiteMap<&'a [u8], usize, S>, |
| 20 |
) -> Result<Self, ZeroTrieBuildError> |
| 21 |
where |
| 22 |
S: litemap::store::StoreSlice<&'a [u8], usize, Slice = [(&'a [u8], usize)]>, |
| 23 |
{ |
| 24 |
let tuples = items.as_slice(); |
| 25 |
let byte_str_slice = ByteSliceWithIndices::from_byte_slice(tuples); |
| 26 |
|
| 27 |
Ok(Self { |
| 28 |
store: ZeroTrieBuilderConst::<10000>::from_slice_with_indices::<100>(byte_str_slice) |
| 29 |
.as_bytes() |
| 30 |
.to_vec(), |
| 31 |
}) |
| 32 |
} |
| 33 |
} |
| 34 |
|
| 35 |
impl<K, S> TryFrom<&LiteMap<K, usize, S>> for ZeroTrie<Vec<u8>> |
| 36 |
where |
| 37 |
// Borrow, not AsRef, because we rely on Ord being the same. Unfortunately |
| 38 |
// this means `LiteMap<&str, usize>` does not work. |
| 39 |
K: Borrow<[u8]>, |
| 40 |
S: litemap::store::StoreSlice<K, usize, Slice = [(K, usize)]>, |
| 41 |
{ |
| 42 |
type Error = ZeroTrieBuildError; |
| 43 |
fn try_from(items: &LiteMap<K, usize, S>) -> Result<Self, ZeroTrieBuildError> { |
| 44 |
let byte_litemap = items.to_borrowed_keys::<[u8], Vec<_>>(); |
| 45 |
let byte_slice = byte_litemap.as_slice(); |
| 46 |
let byte_str_slice = ByteSliceWithIndices::from_byte_slice(byte_slice); |
| 47 |
Self::try_from_tuple_slice(byte_str_slice) |
| 48 |
} |
| 49 |
} |
| 50 |
|
| 51 |
#[cfg(feature = "serde")] |
| 52 |
impl TryFrom<&LiteMap<crate::serde::SerdeByteStrOwned, usize>> for ZeroTrie<Vec<u8>> { |
| 53 |
type Error = ZeroTrieBuildError; |
| 54 |
fn try_from( |
| 55 |
items: &LiteMap<crate::serde::SerdeByteStrOwned, usize>, |
| 56 |
) -> Result<Self, ZeroTrieBuildError> { |
| 57 |
let tuples: Vec<(&[u8], usize)> = items.iter().map(|(k, v)| (k.as_bytes(), *v)).collect(); |
| 58 |
let byte_str_slice = ByteSliceWithIndices::from_byte_slice(&tuples); |
| 59 |
Self::try_from_tuple_slice(byte_str_slice) |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
// TODO(#7084): Make this more infallible by calculating the required length, |
| 64 |
// heap-allocating the required capacity, and pointing ConstAsciiTrieBuilderStore |
| 65 |
// to the heap buffer. |