chore: checkpoint before Python removal

This commit is contained in:
2026-03-26 22:33:59 +00:00
parent 683cec9307
commit e568ddf82a
29972 changed files with 11269302 additions and 2 deletions

1
vendor/ucd-trie/.cargo-checksum.json vendored Normal file
View File

@@ -0,0 +1 @@
{"files":{".cargo_vcs_info.json":"0189d95723a93bf5233936eac19590f3735078ea05369b196266d19730e2f8f1","Cargo.toml":"0d8c74a0a809e12a6ee3e3f89bb0016b978a5951e3605f8a6eb81d60ce3b1bca","Cargo.toml.orig":"2a1e058a5a78bbf3fa423776660c74589f2a9ea5cf907ccbeb3f98859d1de02a","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"0f96a83840e146e43c0ec96a22ec1f392e0680e6c1226e6f3ba87e0740af850f","README.md":"6687ddcfa8075f52ea4326b3caa756165236ff6f75e3379e55ea9f6841821324","benches/bench.rs":"9b74139d17cfcccb502f2abe80b8a4c15a17037a681f27ec914d51e83ea7e55f","src/general_category.rs":"42cbf05dc036e46256621f008f557821f8d3597607c3b8ab62532cdf51b97f6d","src/lib.rs":"99bedb2b655b39ac3a2cc7b4b79a381f7d1e086a20558eec52968f556a638ec4","src/owned.rs":"b897f815685f597f3a98613d5f8196153a207a741e61bbb19f48f90c2bf594ae"},"package":"2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971"}

6
vendor/ucd-trie/.cargo_vcs_info.json vendored Normal file
View File

@@ -0,0 +1,6 @@
{
"git": {
"sha1": "6035dbb69169e68c9fcf309f9d16676aae4a16ae"
},
"path_in_vcs": "ucd-trie"
}

51
vendor/ucd-trie/Cargo.toml vendored Normal file
View File

@@ -0,0 +1,51 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2021"
name = "ucd-trie"
version = "0.1.7"
authors = ["Andrew Gallant <jamslam@gmail.com>"]
build = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = """
A trie for storing Unicode codepoint sets and maps.
"""
homepage = "https://github.com/BurntSushi/ucd-generate"
documentation = "https://docs.rs/ucd-trie"
readme = "README.md"
keywords = [
"unicode",
"database",
"character",
"codepoint",
"trie",
]
license = "MIT OR Apache-2.0"
repository = "https://github.com/BurntSushi/ucd-generate"
[lib]
name = "ucd_trie"
path = "src/lib.rs"
[[bench]]
name = "bench"
path = "benches/bench.rs"
[dev-dependencies.once_cell]
version = "1"
[features]
default = ["std"]
std = []

201
vendor/ucd-trie/LICENSE-APACHE vendored Normal file
View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

21
vendor/ucd-trie/LICENSE-MIT vendored Normal file
View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2015 Andrew Gallant
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

22
vendor/ucd-trie/README.md vendored Normal file
View File

@@ -0,0 +1,22 @@
ucd-trie
========
A library that provides compressed trie sets specifically tailored toward
representing boolean Unicode character properties.
[![Build status](https://github.com/BurntSushi/ucd-generate/workflows/ci/badge.svg)](https://github.com/BurntSushi/ucd-generate/actions)
[![crates.io](https://img.shields.io/crates/v/ucd-trie.svg)](https://crates.io/crates/ucd-trie)
### Documentation
https://docs.rs/ucd-trie
### License
This project is licensed under either of
* Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or
https://www.apache.org/licenses/LICENSE-2.0)
* MIT license ([LICENSE-MIT](LICENSE-MIT) or
https://opensource.org/licenses/MIT)
at your option.

25
vendor/ucd-trie/benches/bench.rs vendored Normal file
View File

@@ -0,0 +1,25 @@
#![feature(test)]
extern crate test;
use once_cell::sync::Lazy;
use ucd_trie::TrieSetOwned;
#[bench]
fn bench_trie_set(b: &mut test::Bencher) {
const CHARS: &'static [char] = &['a', 'β', '☃', '😼'];
// const CHARS: &'static [char] = &['a'];
static SET: Lazy<TrieSetOwned> =
Lazy::new(|| TrieSetOwned::from_scalars(CHARS).unwrap());
let set = Lazy::force(&SET);
let mut i = 0;
b.iter(|| {
let c = CHARS[i];
i = (i + 1) % CHARS.len();
for _ in 0..10000 {
assert!(set.contains_char(c));
}
});
}

6709
vendor/ucd-trie/src/general_category.rs vendored Normal file

File diff suppressed because it is too large Load Diff

117
vendor/ucd-trie/src/lib.rs vendored Normal file
View File

@@ -0,0 +1,117 @@
/*!
The ucd-trie crate provides a compressed trie set specifically tailored for
Unicode codepoints. The principle use case for such a trie is to represent
properties defined by Unicode that correspond to sets of Unicode codepoints.
(These properties are formally called boolean properties or "single valued"
properties. See
[UTR#23 S3.3](https://www.unicode.org/reports/tr23/#PropertyTypeDefinitions)
for more details.)
This crate has two principle types: `TrieSetOwned` and `TrieSetSlice`,
corresponding to a similar split as there is between `Vec<T>` and `&[T]`.
`TrieSetOwned` is the only way to construct a trie from a set of Unicode
codepoints.
The intended use of this library is to embed a static instance of
`TrieSetSlice` into your source code, and then use its methods as defined in
this crate to test membership. (The `ucd-generate` tool can likely generate
this code for you.)
Finally, while this crate uses the standard library by default, it provides
`no_std` functionality by disabling the `std` feature. When `no_std` is
enabled, then `TrieSetOwned` is not provided. Instead, only `TrieSetSlice` is
provided, which means `no_std` crates can still embed tries into their code.
*/
#![deny(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)]
use core::fmt;
#[cfg(feature = "std")]
pub use crate::owned::{Error, Result, TrieSetOwned};
#[cfg(test)]
#[allow(dead_code)]
mod general_category;
#[cfg(feature = "std")]
mod owned;
const CHUNK_SIZE: usize = 64;
/// A type alias for `TrieSetSlice<'static>`.
pub type TrieSet = TrieSetSlice<'static>;
/// A borrowed trie set.
#[derive(Clone, Copy)]
pub struct TrieSetSlice<'a> {
/// first tree, one level
#[doc(hidden)]
pub tree1_level1: &'a [u64],
/// second tree, first level
#[doc(hidden)]
pub tree2_level1: &'a [u8],
/// second tree, second level
#[doc(hidden)]
pub tree2_level2: &'a [u64],
/// third tree, first level
#[doc(hidden)]
pub tree3_level1: &'a [u8],
/// third tree, second level
#[doc(hidden)]
pub tree3_level2: &'a [u8],
/// third tree, third level
#[doc(hidden)]
pub tree3_level3: &'a [u64],
}
impl<'a> fmt::Debug for TrieSetSlice<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "TrieSetSlice(...)")
}
}
impl<'a> TrieSetSlice<'a> {
/// Returns true if and only if the given Unicode scalar value is in this
/// set.
pub fn contains_char(&self, c: char) -> bool {
self.contains(c as usize)
}
/// Returns true if and only if the given codepoint is in this set.
///
/// If the given value exceeds the codepoint range (i.e., it's greater
/// than `0x10FFFF`), then this returns false.
pub fn contains_u32(&self, cp: u32) -> bool {
if cp > 0x10FFFF {
return false;
}
self.contains(cp as usize)
}
#[inline(always)]
fn contains(&self, cp: usize) -> bool {
if cp < 0x800 {
self.chunk_contains(cp, self.tree1_level1[cp >> 6])
} else if cp < 0x10000 {
let leaf = match self.tree2_level1.get((cp >> 6) - 0x20) {
None => return false,
Some(&leaf) => leaf,
};
self.chunk_contains(cp, self.tree2_level2[leaf as usize])
} else {
let child = match self.tree3_level1.get((cp >> 12) - 0x10) {
None => return false,
Some(&child) => child,
};
let i = ((child as usize) * CHUNK_SIZE) + ((cp >> 6) & 0b111111);
let leaf = self.tree3_level2[i];
self.chunk_contains(cp, self.tree3_level3[leaf as usize])
}
}
#[inline(always)]
fn chunk_contains(&self, cp: usize, chunk: u64) -> bool {
((chunk >> (cp & 0b111111)) & 1) == 1
}
}

371
vendor/ucd-trie/src/owned.rs vendored Normal file
View File

@@ -0,0 +1,371 @@
use std::borrow::Borrow;
use std::collections::HashMap;
use std::error;
use std::fmt;
use std::io;
use std::result;
use super::{TrieSetSlice, CHUNK_SIZE};
// This implementation was pretty much cribbed from raphlinus' contribution
// to the standard library: https://github.com/rust-lang/rust/pull/33098/files
//
// The fundamental principle guiding this implementation is to take advantage
// of the fact that similar Unicode codepoints are often grouped together, and
// that most boolean Unicode properties are quite sparse over the entire space
// of Unicode codepoints.
//
// To do this, we represent sets using something like a trie (which gives us
// prefix compression). The "final" states of the trie are embedded in leaves
// or "chunks," where each chunk is a 64 bit integer. Each bit position of the
// integer corresponds to whether a particular codepoint is in the set or not.
// These chunks are not just a compact representation of the final states of
// the trie, but are also a form of suffix compression. In particular, if
// multiple ranges of 64 contiguous codepoints map have the same set membership
// ordering, then they all map to the exact same chunk in the trie.
//
// We organize this structure by partitioning the space of Unicode codepoints
// into three disjoint sets. The first set corresponds to codepoints
// [0, 0x800), the second [0x800, 0x1000) and the third [0x10000, 0x110000).
// These partitions conveniently correspond to the space of 1 or 2 byte UTF-8
// encoded codepoints, 3 byte UTF-8 encoded codepoints and 4 byte UTF-8 encoded
// codepoints, respectively.
//
// Each partition has its own tree with its own root. The first partition is
// the simplest, since the tree is completely flat. In particular, to determine
// the set membership of a Unicode codepoint (that is less than `0x800`), we
// do the following (where `cp` is the codepoint we're testing):
//
// let chunk_address = cp >> 6;
// let chunk_bit = cp & 0b111111;
// let chunk = tree1[cp >> 6];
// let is_member = 1 == ((chunk >> chunk_bit) & 1);
//
// We do something similar for the second partition:
//
// // we subtract 0x20 since (0x800 >> 6) == 0x20.
// let child_address = (cp >> 6) - 0x20;
// let chunk_address = tree2_level1[child_address];
// let chunk_bit = cp & 0b111111;
// let chunk = tree2_level2[chunk_address];
// let is_member = 1 == ((chunk >> chunk_bit) & 1);
//
// And so on for the third partition.
//
// Note that as a special case, if the second or third partitions are empty,
// then the trie will store empty slices for those levels. The `contains`
// check knows to return `false` in those cases.
const CHUNKS: usize = 0x110000 / CHUNK_SIZE;
/// A type alias that maps to `std::result::Result<T, ucd_trie::Error>`.
pub type Result<T> = result::Result<T, Error>;
/// An error that can occur during construction of a trie.
#[derive(Clone, Debug)]
pub enum Error {
/// This error is returned when an invalid codepoint is given to
/// `TrieSetOwned::from_codepoints`. An invalid codepoint is a `u32` that
/// is greater than `0x10FFFF`.
InvalidCodepoint(u32),
/// This error is returned when a set of Unicode codepoints could not be
/// sufficiently compressed into the trie provided by this crate. There is
/// no work-around for this error at this time.
GaveUp,
}
impl error::Error for Error {}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Error::InvalidCodepoint(cp) => write!(
f,
"could not construct trie set containing an \
invalid Unicode codepoint: 0x{:X}",
cp
),
Error::GaveUp => {
write!(f, "could not compress codepoint set into a trie")
}
}
}
}
impl From<Error> for io::Error {
fn from(err: Error) -> io::Error {
io::Error::new(io::ErrorKind::Other, err)
}
}
/// An owned trie set.
#[derive(Clone)]
pub struct TrieSetOwned {
tree1_level1: Vec<u64>,
tree2_level1: Vec<u8>,
tree2_level2: Vec<u64>,
tree3_level1: Vec<u8>,
tree3_level2: Vec<u8>,
tree3_level3: Vec<u64>,
}
impl fmt::Debug for TrieSetOwned {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "TrieSetOwned(...)")
}
}
impl TrieSetOwned {
fn new(all: &[bool]) -> Result<TrieSetOwned> {
let mut bitvectors = Vec::with_capacity(CHUNKS);
for i in 0..CHUNKS {
let mut bitvector = 0u64;
for j in 0..CHUNK_SIZE {
if all[i * CHUNK_SIZE + j] {
bitvector |= 1 << j;
}
}
bitvectors.push(bitvector);
}
let tree1_level1 =
bitvectors.iter().cloned().take(0x800 / CHUNK_SIZE).collect();
let (mut tree2_level1, mut tree2_level2) = compress_postfix_leaves(
&bitvectors[0x800 / CHUNK_SIZE..0x10000 / CHUNK_SIZE],
)?;
if tree2_level2.len() == 1 && tree2_level2[0] == 0 {
tree2_level1.clear();
tree2_level2.clear();
}
let (mid, mut tree3_level3) = compress_postfix_leaves(
&bitvectors[0x10000 / CHUNK_SIZE..0x110000 / CHUNK_SIZE],
)?;
let (mut tree3_level1, mut tree3_level2) =
compress_postfix_mid(&mid, 64)?;
if tree3_level3.len() == 1 && tree3_level3[0] == 0 {
tree3_level1.clear();
tree3_level2.clear();
tree3_level3.clear();
}
Ok(TrieSetOwned {
tree1_level1,
tree2_level1,
tree2_level2,
tree3_level1,
tree3_level2,
tree3_level3,
})
}
/// Create a new trie set from a set of Unicode scalar values.
///
/// This returns an error if a set could not be sufficiently compressed to
/// fit into a trie.
pub fn from_scalars<I, C>(scalars: I) -> Result<TrieSetOwned>
where
I: IntoIterator<Item = C>,
C: Borrow<char>,
{
let mut all = vec![false; 0x110000];
for s in scalars {
all[*s.borrow() as usize] = true;
}
TrieSetOwned::new(&all)
}
/// Create a new trie set from a set of Unicode scalar values.
///
/// This returns an error if a set could not be sufficiently compressed to
/// fit into a trie. This also returns an error if any of the given
/// codepoints are greater than `0x10FFFF`.
pub fn from_codepoints<I, C>(codepoints: I) -> Result<TrieSetOwned>
where
I: IntoIterator<Item = C>,
C: Borrow<u32>,
{
let mut all = vec![false; 0x110000];
for cp in codepoints {
let cp = *cp.borrow();
if cp > 0x10FFFF {
return Err(Error::InvalidCodepoint(cp));
}
all[cp as usize] = true;
}
TrieSetOwned::new(&all)
}
/// Return this set as a slice.
#[inline(always)]
pub fn as_slice(&self) -> TrieSetSlice<'_> {
TrieSetSlice {
tree1_level1: &self.tree1_level1,
tree2_level1: &self.tree2_level1,
tree2_level2: &self.tree2_level2,
tree3_level1: &self.tree3_level1,
tree3_level2: &self.tree3_level2,
tree3_level3: &self.tree3_level3,
}
}
/// Returns true if and only if the given Unicode scalar value is in this
/// set.
pub fn contains_char(&self, c: char) -> bool {
self.as_slice().contains_char(c)
}
/// Returns true if and only if the given codepoint is in this set.
///
/// If the given value exceeds the codepoint range (i.e., it's greater
/// than `0x10FFFF`), then this returns false.
pub fn contains_u32(&self, cp: u32) -> bool {
self.as_slice().contains_u32(cp)
}
}
fn compress_postfix_leaves(chunks: &[u64]) -> Result<(Vec<u8>, Vec<u64>)> {
let mut root = vec![];
let mut children = vec![];
let mut bychild = HashMap::new();
for &chunk in chunks {
if !bychild.contains_key(&chunk) {
let start = bychild.len();
if start > ::std::u8::MAX as usize {
return Err(Error::GaveUp);
}
bychild.insert(chunk, start as u8);
children.push(chunk);
}
root.push(bychild[&chunk]);
}
Ok((root, children))
}
fn compress_postfix_mid(
chunks: &[u8],
chunk_size: usize,
) -> Result<(Vec<u8>, Vec<u8>)> {
let mut root = vec![];
let mut children = vec![];
let mut bychild = HashMap::new();
for i in 0..(chunks.len() / chunk_size) {
let chunk = &chunks[i * chunk_size..(i + 1) * chunk_size];
if !bychild.contains_key(chunk) {
let start = bychild.len();
if start > ::std::u8::MAX as usize {
return Err(Error::GaveUp);
}
bychild.insert(chunk, start as u8);
children.extend(chunk);
}
root.push(bychild[chunk]);
}
Ok((root, children))
}
#[cfg(test)]
mod tests {
use super::TrieSetOwned;
use crate::general_category;
use std::collections::HashSet;
fn mk(scalars: &[char]) -> TrieSetOwned {
TrieSetOwned::from_scalars(scalars).unwrap()
}
fn ranges_to_set(ranges: &[(u32, u32)]) -> Vec<u32> {
let mut set = vec![];
for &(start, end) in ranges {
for cp in start..end + 1 {
set.push(cp);
}
}
set
}
#[test]
fn set1() {
let set = mk(&['a']);
assert!(set.contains_char('a'));
assert!(!set.contains_char('b'));
assert!(!set.contains_char('β'));
assert!(!set.contains_char('☃'));
assert!(!set.contains_char('😼'));
}
#[test]
fn set_combined() {
let set = mk(&['a', 'b', 'β', '☃', '😼']);
assert!(set.contains_char('a'));
assert!(set.contains_char('b'));
assert!(set.contains_char('β'));
assert!(set.contains_char('☃'));
assert!(set.contains_char('😼'));
assert!(!set.contains_char('c'));
assert!(!set.contains_char('θ'));
assert!(!set.contains_char('⛇'));
assert!(!set.contains_char('🐲'));
}
// Basic tests on all of the general category sets. We check that
// membership is correct on every Unicode codepoint... because we can.
macro_rules! category_test {
($name:ident, $ranges:ident) => {
#[test]
fn $name() {
let set = ranges_to_set(general_category::$ranges);
let hashset: HashSet<u32> = set.iter().cloned().collect();
let trie = TrieSetOwned::from_codepoints(&set).unwrap();
for cp in 0..0x110000 {
assert!(trie.contains_u32(cp) == hashset.contains(&cp));
}
// Test that an invalid codepoint is treated correctly.
assert!(!trie.contains_u32(0x110000));
assert!(!hashset.contains(&0x110000));
}
};
}
category_test!(gencat_cased_letter, CASED_LETTER);
category_test!(gencat_close_punctuation, CLOSE_PUNCTUATION);
category_test!(gencat_connector_punctuation, CONNECTOR_PUNCTUATION);
category_test!(gencat_control, CONTROL);
category_test!(gencat_currency_symbol, CURRENCY_SYMBOL);
category_test!(gencat_dash_punctuation, DASH_PUNCTUATION);
category_test!(gencat_decimal_number, DECIMAL_NUMBER);
category_test!(gencat_enclosing_mark, ENCLOSING_MARK);
category_test!(gencat_final_punctuation, FINAL_PUNCTUATION);
category_test!(gencat_format, FORMAT);
category_test!(gencat_initial_punctuation, INITIAL_PUNCTUATION);
category_test!(gencat_letter, LETTER);
category_test!(gencat_letter_number, LETTER_NUMBER);
category_test!(gencat_line_separator, LINE_SEPARATOR);
category_test!(gencat_lowercase_letter, LOWERCASE_LETTER);
category_test!(gencat_math_symbol, MATH_SYMBOL);
category_test!(gencat_mark, MARK);
category_test!(gencat_modifier_letter, MODIFIER_LETTER);
category_test!(gencat_modifier_symbol, MODIFIER_SYMBOL);
category_test!(gencat_nonspacing_mark, NONSPACING_MARK);
category_test!(gencat_number, NUMBER);
category_test!(gencat_open_punctuation, OPEN_PUNCTUATION);
category_test!(gencat_other, OTHER);
category_test!(gencat_other_letter, OTHER_LETTER);
category_test!(gencat_other_number, OTHER_NUMBER);
category_test!(gencat_other_punctuation, OTHER_PUNCTUATION);
category_test!(gencat_other_symbol, OTHER_SYMBOL);
category_test!(gencat_paragraph_separator, PARAGRAPH_SEPARATOR);
category_test!(gencat_private_use, PRIVATE_USE);
category_test!(gencat_punctuation, PUNCTUATION);
category_test!(gencat_separator, SEPARATOR);
category_test!(gencat_space_separator, SPACE_SEPARATOR);
category_test!(gencat_spacing_mark, SPACING_MARK);
category_test!(gencat_surrogate, SURROGATE);
category_test!(gencat_symbol, SYMBOL);
category_test!(gencat_titlecase_letter, TITLECASE_LETTER);
category_test!(gencat_unassigned, UNASSIGNED);
category_test!(gencat_uppercase_letter, UPPERCASE_LETTER);
}

View File

@@ -0,0 +1 @@
{"name":"ucd-trie","vers":"0.1.7","deps":[{"name":"once_cell","req":"^1","features":[],"optional":false,"default_features":true,"target":null,"kind":"dev","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false}],"features":{"default":["std"],"std":[]},"features2":null,"cksum":"07a0f68e0319a89473110c31bed8c39f7cb597a55d6fa9d1d0ea2f6361bc9b74","yanked":null,"links":null,"rust_version":null,"v":2}

Binary file not shown.

Binary file not shown.