Vendor dependencies for 0.3.0 release

This commit is contained in:
2025-09-27 10:29:08 -05:00
parent 0c8d39d483
commit 82ab7f317b
26803 changed files with 16134934 additions and 0 deletions

View File

@@ -0,0 +1 @@
{"files":{"Cargo.toml":"9a3d68d2142bd01d5b8e8f805d9052412f29b9a80a3eb64eee311b67e703f32e","LICENSE-APACHE":"7cbb56d1b5d83d735056b363ab20958524120afafc4ad8206e6be98cdec5d737","LICENSE-MIT":"7ad3ea8ca3caf894db98c3f31d5d4949173ffa93c883ef19a9e529ad48960f8c","README.md":"9d922b2906be36f007f89c6f4eae8976d90a01be8181928698a121b154bbb016","scripts/unicode.py":"a72c10b89ec8c7bf4d563231c3a761756b3f6b4fe7fd47ad56644e8c6fd1c719","src/lib.rs":"c7fe2550b1ed36de32f898d6102859481a31e4484d7264a3cc41f1399843537e","src/tables.rs":"41cdc49fee0da1ec70307915ac0ff2aec5f3c0ad51dce83d7adf5aa4d1aa7f61"},"package":"9fb421b350c9aff471779e262955939f565ec18b86c15364e6bdf0d662ca7c1f"}

67
vendor/unicode-script/Cargo.toml vendored Normal file
View File

@@ -0,0 +1,67 @@
# 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 = "2018"
name = "unicode-script"
version = "0.5.7"
authors = ["Manish Goregaokar <manishsmail@gmail.com>"]
build = false
exclude = [
"target/*",
"Cargo.lock",
"scripts/tmp",
"*.txt",
]
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = """
This crate exposes the Unicode `Script` and `Script_Extension` properties from [UAX #24](http://www.unicode.org/reports/tr24/)
"""
homepage = "https://github.com/unicode-rs/unicode-script"
documentation = "https://docs.rs/unicode-script"
readme = "README.md"
keywords = [
"text",
"unicode",
"script",
"language",
]
license = "MIT OR Apache-2.0"
repository = "https://github.com/unicode-rs/unicode-script"
[lib]
name = "unicode_script"
path = "src/lib.rs"
[dependencies.compiler_builtins]
version = "0.1"
optional = true
[dependencies.core]
version = "1.0"
optional = true
package = "rustc-std-workspace-core"
[dependencies.std]
version = "1.0"
optional = true
package = "rustc-std-workspace-std"
[features]
bench = []
rustc-dep-of-std = [
"std",
"core",
"compiler_builtins",
]

201
vendor/unicode-script/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 2021 The Unicode-rs Developers
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.

27
vendor/unicode-script/LICENSE-MIT vendored Normal file
View File

@@ -0,0 +1,27 @@
MIT License
Copyright (c) 2019 Manish Goregaokar
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.

7
vendor/unicode-script/README.md vendored Normal file
View File

@@ -0,0 +1,7 @@
# unicode-script
[![Build Status](https://github.com/unicode-rs/unicode-script/workflows/Tests/badge.svg)](https://github.com/unicode-rs/unicode-script/actions)
[![Current Version](https://img.shields.io/crates/v/unicode-script.svg)](https://crates.io/crates/unicode-script)
[![License: MIT/Apache-2.0](https://img.shields.io/crates/l/unicode-script.svg)](#license)
This crate exposes the Unicode `Script` and `Script_Extension` properties from [UAX #24](http://www.unicode.org/reports/tr24/)

402
vendor/unicode-script/scripts/unicode.py vendored Normal file
View File

@@ -0,0 +1,402 @@
#!/usr/bin/env python
#
# Copyright 2011-2015 The Rust Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution and at
# http://rust-lang.org/COPYRIGHT.
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
# option. This file may not be copied, modified, or distributed
# except according to those terms.
# This script uses the following Unicode tables:
# - PropertyValueAliases.txt
# - ScriptExtensions.txt
# - Scripts.txt
#
# Since this should not require frequent updates, we just store this
# out-of-line and check the unicode.rs file into git.
import fileinput, re, os, sys
preamble = '''// Copyright 2012-2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// NOTE: The following code was generated by "scripts/unicode.py", do not edit directly
#![allow(missing_docs, non_upper_case_globals, non_snake_case)]
pub use tables_impl::*;
#[rustfmt::skip]
mod tables_impl {
use crate::ScriptExtension;
'''
# Close `mod impl {`
ending='''
}
'''
UNICODE_VERSION = (16, 0, 0)
UNICODE_VERSION_NUMBER = "%s.%s.%s" %UNICODE_VERSION
def escape_char(c):
return "'\\u{%x}'" % c
def fetch(f):
if not os.path.exists(os.path.basename(f)):
if "emoji" in f:
os.system("curl -O https://www.unicode.org/Public/emoji/%s.%s/%s"
% (UNICODE_VERSION[0], UNICODE_VERSION[1], f))
else:
os.system("curl -O https://www.unicode.org/Public/%s/ucd/%s"
% (UNICODE_VERSION_NUMBER, f))
if not os.path.exists(os.path.basename(f)):
sys.stderr.write("cannot load %s" % f)
exit(1)
def group_cats(cats):
cats_out = {}
for cat in cats:
cats_out[cat] = group_cat(cats[cat])
return cats_out
def aliases():
"""
Fetch the shorthand aliases for each longhand Script name
"""
fetch("PropertyValueAliases.txt")
longforms = {}
shortforms = {}
re1 = re.compile(r"^ *sc *; *(\w+) *; *(\w+)")
for line in fileinput.input(os.path.basename("PropertyValueAliases.txt")):
m = re1.match(line)
if m:
l = m.group(2).strip()
s = m.group(1).strip()
assert(s not in longforms)
assert(l not in shortforms)
longforms[s] = l
shortforms[l] = s
else:
continue
return (longforms, shortforms)
def format_table_content(f, content, indent):
line = " "*indent
first = True
for chunk in content.split(","):
if len(line) + len(chunk) < 98:
if first:
line += chunk
else:
line += ", " + chunk
first = False
else:
f.write(line + ",\n")
line = " "*indent + chunk
f.write(line)
# Implementation from unicode-segmentation
def load_properties(f, interestingprops):
fetch(f)
props = {}
# Note: these regexes are different from those in unicode-segmentation,
# becase we need to handle spaces here
re1 = re.compile(r"^ *([0-9A-F]+) *; *([^#]+) *#")
re2 = re.compile(r"^ *([0-9A-F]+)\.\.([0-9A-F]+) *; *([^#]+) *#")
for line in fileinput.input(os.path.basename(f)):
prop = None
d_lo = 0
d_hi = 0
m = re1.match(line)
if m:
d_lo = m.group(1)
d_hi = m.group(1)
prop = m.group(2).strip()
else:
m = re2.match(line)
if m:
d_lo = m.group(1)
d_hi = m.group(2)
prop = m.group(3).strip()
else:
continue
if interestingprops and prop not in interestingprops:
continue
d_lo = int(d_lo, 16)
d_hi = int(d_hi, 16)
if prop not in props:
props[prop] = []
props[prop].append((d_lo, d_hi))
return props
# Implementation from unicode-segmentation
def emit_table(f, name, t_data, t_type = "&'static [(char, char)]", is_pub=True,
pfun=lambda x: "(%s,%s)" % (escape_char(x[0]), escape_char(x[1])), is_const=True):
pub_string = "const"
if not is_const:
pub_string = "let"
if is_pub:
pub_string = "pub " + pub_string
f.write(" %s %s: %s = &[\n" % (pub_string, name, t_type))
data = ""
first = True
for dat in t_data:
if not first:
data += ","
first = False
data += pfun(dat)
format_table_content(f, data, 8)
f.write("\n ];\n\n")
def emit_search(f):
f.write("""
pub fn bsearch_range_value_table<T: Copy>(c: char, r: &'static [(char, char, T)]) -> Option<T> {
use core::cmp::Ordering::{Equal, Less, Greater};
match r.binary_search_by(|&(lo, hi, _)| {
if lo <= c && c <= hi { Equal }
else if hi < c { Less }
else { Greater }
}) {
Ok(idx) => {
let (_, _, cat) = r[idx];
Some(cat)
}
Err(_) => None
}
}
#[inline]
pub fn get_script(c: char) -> Option<Script> {
bsearch_range_value_table(c, SCRIPTS)
}
#[inline]
pub fn get_script_extension(c: char) -> Option<ScriptExtension> {
bsearch_range_value_table(c, SCRIPT_EXTENSIONS)
}
""")
def emit_enums(f, script_list, extension_list, longforms):
"""
Emit the Script and ScriptExtension enums as well as any related utility functions
"""
f.write("""
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
#[non_exhaustive]
#[allow(non_camel_case_types)]
#[repr(u8)]
/// A value of the `Script` property
pub enum Script {
/// Unknown script
Unknown = 0xFF,
/// Zyyy
Common = 0xFE,
/// Zinh,
Inherited = 0xFD,
""")
for (i, script) in enumerate(script_list):
f.write(" /// %s\n %s = %s,\n" % (script, longforms[script], i))
f.write("}\n")
f.write("pub const NEXT_SCRIPT: u8 = %s;" % len(script_list))
f.write("""
pub mod script_extensions {
use crate::ScriptExtension;
pub const COMMON: ScriptExtension = ScriptExtension::new_common();
pub const INHERITED: ScriptExtension = ScriptExtension::new_inherited();
pub const UNKNOWN: ScriptExtension = ScriptExtension::new_unknown();
""")
for (i, script) in enumerate(script_list):
first = 0
second = 0
third = 0
# need to replace L because `hex()` will spit out an L suffix for larger numbers
if i < 64:
first = hex(1 << i).replace("L", "")
elif i < 128:
second = hex(1 << (i - 64)).replace("L", "")
else:
third = hex(1 << (i - 128)).replace("L", "")
f.write(" /// %s\n pub const %s: ScriptExtension = ScriptExtension::new(%s, %s, %s);\n" %
(longforms[script], longforms[script].upper(), first, second, third))
if script != longforms[script]:
f.write(" /// %s\n pub const %s: ScriptExtension = %s;\n" %
(longforms[script], script.upper(), longforms[script].upper()))
for ext in extension_list:
longform = ", ".join([longforms[s] for s in ext])
name = "_".join([s.upper() for s in ext])
expr = ext[0].upper()
for e in ext[1:]:
expr = "%s.union(%s)" % (expr, e.upper())
f.write(" /// %s\n pub const %s: ScriptExtension = %s;\n" % (longform, name, expr))
f.write("""}
""")
# Generate implementation for the `Script`
generate_script_impl(f)
def generate_script_impl(f):
"""Generates an `impl Script { ... }` section with all the required functions"""
# Open `impl Script` section.
f.write("""impl Script {
""")
# Generate impl of `inner_full_name`.
f.write("""
#[inline]
pub(crate) fn inner_full_name(self) -> &'static str {
match self {
Script::Unknown => "Unknown",
Script::Common => "Common",
Script::Inherited => "Inherited",
""")
for script in script_list:
f.write(" Script::%s => \"%s\",\n" % (longforms[script], longforms[script]))
f.write(""" }
}
""")
# Generate impl of `inner_from_full_name`.
f.write("""
#[inline]
pub(crate) fn inner_from_full_name(input: &str) -> Option<Self> {
match input {
"Unknown" => Some(Script::Unknown),
"Common" => Some(Script::Common),
"Inherited" => Some(Script::Inherited),
""")
for script in script_list:
f.write(" \"%s\" => Some(Script::%s),\n" % (longforms[script], longforms[script]))
f.write(" _ => None,\n" )
f.write(""" }
}
""")
# Generate impl of `inner_short_name`
f.write("""
#[inline]
pub(crate) fn inner_short_name(self) -> &'static str {
match self {
Script::Unknown => "",
Script::Common => "Zyyy",
Script::Inherited => "Zinh",
""")
for script in script_list:
f.write(" Script::%s => \"%s\",\n" % (longforms[script], script))
f.write(""" }
}
""")
# Generate impl of `inner_from_short_name`
f.write("""
#[inline]
pub(crate) fn inner_from_short_name(input: &str) -> Option<Self> {
match input {
"Zyyy" => Some(Script::Common),
"Zinh" => Some(Script::Inherited),
""")
for script in script_list:
f.write(" \"%s\" => Some(Script::%s),\n" % (script, longforms[script]))
f.write(""" _ => None,\n""")
f.write(""" }
}
""")
# Generate impl of `for_integer`
f.write("""
#[inline]
pub(crate) fn for_integer(value: u8) -> Self {
match value {
""")
for (i, script) in enumerate(script_list):
f.write(" %s => Script::%s,\n" % (i, longforms[script]))
f.write(""" _ => unreachable!(),
}
}
""")
# Close `impl Script` section
f.write("""
}
""")
def extension_name(ext):
"""Get the rust source for a given ScriptExtension"""
return "script_extensions::%s" % "_".join([e.upper() for e in ext])
if __name__ == "__main__":
r = "tables.rs"
if os.path.exists(r):
os.remove(r)
with open(r, "w") as rf:
# write the file's preamble
rf.write(preamble)
rf.write("""
/// The version of [Unicode](http://www.unicode.org/)
/// that this version of unicode-script is based on.
pub const UNICODE_VERSION: (u64, u64, u64) = (%s, %s, %s);
""" % UNICODE_VERSION)
(longforms, shortforms) = aliases()
scripts = load_properties("Scripts.txt", [])
script_table = []
script_list = []
for script in scripts:
if script not in ["Common", "Unknown", "Inherited"]:
script_list.append(shortforms[script])
script_table.extend([(x, y, shortforms[script]) for (x, y) in scripts[script]])
script_list.sort()
script_table.sort(key=lambda w: w[0])
extensions = load_properties("ScriptExtensions.txt", [])
extension_table = []
extension_list = []
for ext in extensions:
split = ext.split(" ")
split.sort()
output_ext = [ext]
if len(split) > 1:
extension_list.append(split)
output_ext = split
extension_table.extend([(x, y, output_ext) for (x, y) in extensions[ext]])
extension_table.sort(key=lambda w: w[0])
emit_enums(rf, script_list, extension_list, longforms)
emit_search(rf)
emit_table(rf, "SCRIPTS", script_table, t_type = "&'static [(char, char, Script)]",
is_pub=False , pfun=lambda x: "(%s,%s, Script::%s)" % (escape_char(x[0]), escape_char(x[1]), longforms[x[2]]))
emit_table(rf, "SCRIPT_EXTENSIONS", extension_table, t_type = "&'static [(char, char, ScriptExtension)]",
is_pub=False , pfun=lambda x: "(%s,%s,%s)" % (escape_char(x[0]), escape_char(x[1]), extension_name(x[2])))
# emit_table(rf, "FOObar", properties)
rf.write(ending)

560
vendor/unicode-script/src/lib.rs vendored Normal file
View File

@@ -0,0 +1,560 @@
//! This crate exposes the Unicode `Script` and `Script_Extension`
//! properties from [UAX #24](http://www.unicode.org/reports/tr24/)
#![cfg_attr(not(test), no_std)]
#![cfg_attr(feature = "bench", feature(test))]
mod tables;
use core::convert::TryFrom;
use core::fmt;
use core::u64;
pub use tables::script_extensions;
use tables::{get_script, get_script_extension, NEXT_SCRIPT};
pub use tables::{Script, UNICODE_VERSION};
impl Script {
/// Get the full name of a script.
pub fn full_name(self) -> &'static str {
self.inner_full_name()
}
/// Attempts to parse script name from the provided string.
/// Returns `None` if the provided string does not represent a valid
/// script full name.
pub fn from_full_name(input: &str) -> Option<Self> {
Self::inner_from_full_name(input)
}
/// Get the four-character short name of a script.
pub fn short_name(self) -> &'static str {
self.inner_short_name()
}
/// Attempts to parse script name from the provided string.
/// Returns `None` if the provided string does not represent a valid
/// script four-character short name.
pub fn from_short_name(input: &str) -> Option<Self> {
Self::inner_from_short_name(input)
}
/// Is this script "Recommended" according to
/// [UAX #31](www.unicode.org/reports/tr31/#Table_Recommended_Scripts)?
pub fn is_recommended(self) -> bool {
use Script::*;
match self {
Common | Inherited | Arabic | Armenian | Bengali | Bopomofo | Cyrillic | Devanagari
| Ethiopic | Georgian | Greek | Gujarati | Gurmukhi | Han | Hangul | Hebrew
| Hiragana | Kannada | Katakana | Khmer | Lao | Latin | Malayalam | Myanmar | Oriya
| Sinhala | Tamil | Telugu | Thaana | Thai | Tibetan => true,
_ => false,
}
}
}
impl From<Script> for ScriptExtension {
fn from(script: Script) -> Self {
if script == Script::Common {
ScriptExtension::new_common()
} else if script == Script::Inherited {
ScriptExtension::new_inherited()
} else if script == Script::Unknown {
ScriptExtension::new_unknown()
} else {
let mut first = 0;
let mut second = 0;
let mut third = 0;
let bit = script as u8;
// Find out which field it's in, and set the appropriate bit there
if bit < 64 {
first = 1 << bit as u64;
} else if bit < 128 {
// offset by 64 since `bit` is an absolute number,
// not relative to the chunk
second = 1 << (bit - 64) as u64;
} else {
third = 1 << (bit - 128) as u32;
}
ScriptExtension::new(first, second, third)
}
}
}
impl TryFrom<ScriptExtension> for Script {
type Error = ();
fn try_from(ext: ScriptExtension) -> Result<Self, ()> {
if ext.is_common_or_inherited() {
if ext.common {
Ok(Script::Common)
} else {
Ok(Script::Inherited)
}
} else if ext.is_empty() {
Ok(Script::Unknown)
} else {
// filled elements will have set ones
let fo = ext.first.count_ones();
let so = ext.second.count_ones();
let to = ext.third.count_ones();
// only one bit set, in the first chunk
if fo == 1 && so == 0 && to == 0 {
// use trailing_zeroes() to figure out which bit it is
Ok(Script::for_integer(ext.first.trailing_zeros() as u8))
// only one bit set, in the second chunk
} else if fo == 0 && so == 1 && to == 0 {
Ok(Script::for_integer(64 + ext.second.trailing_zeros() as u8))
// only one bit set, in the third chunk
} else if fo == 0 && so == 0 && to == 1 {
Ok(Script::for_integer(128 + ext.third.trailing_zeros() as u8))
} else {
Err(())
}
}
}
}
impl Default for Script {
fn default() -> Self {
Script::Common
}
}
impl From<char> for Script {
fn from(o: char) -> Self {
o.script()
}
}
impl fmt::Display for Script {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.full_name())
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
/// A value for the `Script_Extension` property
///
/// [`ScriptExtension`] is one or more [`Script`]
///
/// This is essentially an optimized version of `Vec<Script>` that uses bitfields
pub struct ScriptExtension {
// A bitset for the first 64 scripts
first: u64,
// A bitset for the scripts 65-128
second: u64,
// A bitset for scripts after 128
third: u64,
// Both Common and Inherited are represented by all used bits being set,
// this flag lets us distinguish the two.
common: bool,
}
impl ScriptExtension {
// We don't use the complete u64 of `third`, so the "all" value is not just u32::MAX
// Instead, we take the number of the next (unused) script bit, subtract 128 to bring
// it in the range of `third`, create a u64 with just that bit set, and subtract 1
// to create one with all the lower bits set.
const THIRD_MAX: u64 = ((1 << (NEXT_SCRIPT - 128)) - 1);
pub(crate) const fn new(first: u64, second: u64, third: u64) -> Self {
ScriptExtension {
first,
second,
third,
common: false,
}
}
pub(crate) const fn new_common() -> Self {
ScriptExtension {
first: u64::MAX,
second: u64::MAX,
third: Self::THIRD_MAX,
common: true,
}
}
pub(crate) const fn new_inherited() -> Self {
ScriptExtension {
first: u64::MAX,
second: u64::MAX,
third: Self::THIRD_MAX,
common: false,
}
}
pub(crate) const fn new_unknown() -> Self {
ScriptExtension {
first: 0,
second: 0,
third: 0,
common: false,
}
}
const fn is_common_or_inherited(self) -> bool {
(self.first == u64::MAX) & (self.second == u64::MAX) & (self.third == Self::THIRD_MAX)
}
/// Checks if the script extension is Common
pub const fn is_common(self) -> bool {
self.is_common_or_inherited() & self.common
}
/// Checks if the script extension is Inherited
pub const fn is_inherited(self) -> bool {
self.is_common_or_inherited() & !self.common
}
/// Checks if the script extension is empty (unknown)
pub const fn is_empty(self) -> bool {
(self.first == 0) & (self.second == 0) & (self.third == 0)
}
/// Returns the number of scripts in the script extension
pub fn len(self) -> usize {
if self.is_common_or_inherited() {
1
} else {
(self.first.count_ones() + self.second.count_ones() + self.third.count_ones()) as usize
}
}
/// Intersect this `ScriptExtension` with another `ScriptExtension`. Produces `Unknown` if things
/// do not intersect. This is equivalent to [`ScriptExtension::intersection`] but it stores the result
/// in `self`
///
/// "Common" (`Zyyy`) and "Inherited" (`Zinh`) are considered as intersecting
/// everything, the intersection of `Common` and `Inherited` is `Inherited`
pub fn intersect_with(&mut self, other: Self) {
*self = self.intersection(other)
}
/// Find the intersection between two ScriptExtensions. Returns Unknown if things
/// do not intersect.
///
/// "Common" (`Zyyy`) and "Inherited" (`Zinh`) are considered as intersecting
/// everything, the intersection of `Common` and `Inherited` is `Inherited`
pub const fn intersection(self, other: Self) -> Self {
let first = self.first & other.first;
let second = self.second & other.second;
let third = self.third & other.third;
let common = self.common & other.common;
ScriptExtension {
first,
second,
third,
common,
}
}
/// Find the union between two ScriptExtensions.
///
/// "Common" (`Zyyy`) and "Inherited" (`Zinh`) are considered as intersecting
/// everything, the union of `Common` and `Inherited` is `Common`
pub const fn union(self, other: Self) -> Self {
let first = self.first | other.first;
let second = self.second | other.second;
let third = self.third | other.third;
let common = self.common | other.common;
ScriptExtension {
first,
second,
third,
common,
}
}
/// Check if this ScriptExtension contains the given script
///
/// Should be used with specific scripts only, this will
/// return `true` if `self` is not `Unknown` and `script` is
/// `Common` or `Inherited`
pub fn contains_script(self, script: Script) -> bool {
!self.intersection(script.into()).is_empty()
}
/// Get the intersection of script extensions of all characters
/// in a string.
pub fn for_str(x: &str) -> Self {
let mut ext = ScriptExtension::default();
for ch in x.chars() {
ext.intersect_with(ch.into());
}
ext
}
/// Iterate over the scripts in this script extension
///
/// Will never yield Script::Unknown
pub fn iter(self) -> ScriptIterator {
ScriptIterator { ext: self }
}
}
impl Default for ScriptExtension {
fn default() -> Self {
ScriptExtension::new_common()
}
}
impl From<char> for ScriptExtension {
fn from(o: char) -> Self {
o.script_extension()
}
}
impl From<&'_ str> for ScriptExtension {
fn from(o: &'_ str) -> Self {
Self::for_str(o)
}
}
impl fmt::Debug for ScriptExtension {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ScriptExtension(")?;
fmt::Display::fmt(self, f)?;
write!(f, ")")
}
}
impl fmt::Display for ScriptExtension {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.is_common() {
write!(f, "Common")?;
} else if self.is_inherited() {
write!(f, "Inherited")?;
} else if self.is_empty() {
write!(f, "Unknown")?;
} else {
let mut first = true;
for script in self.iter() {
if !first {
write!(f, " + ")?;
first = false;
}
script.full_name().fmt(f)?;
}
}
Ok(())
}
}
/// Extension trait on `char` for calculating script properties
pub trait UnicodeScript {
/// Get the script for a given character
fn script(&self) -> Script;
/// Get the Script_Extension for a given character
fn script_extension(&self) -> ScriptExtension;
}
impl UnicodeScript for char {
fn script(&self) -> Script {
get_script(*self).unwrap_or(Script::Unknown)
}
fn script_extension(&self) -> ScriptExtension {
get_script_extension(*self).unwrap_or_else(|| self.script().into())
}
}
/// Iterator over scripts in a [ScriptExtension].
///
/// Can be obtained ia [ScriptExtension::iter()]
pub struct ScriptIterator {
ext: ScriptExtension,
}
impl Iterator for ScriptIterator {
type Item = Script;
fn next(&mut self) -> Option<Script> {
if self.ext.is_common_or_inherited() {
let common = self.ext.common;
self.ext = ScriptExtension::new_unknown();
if common {
Some(Script::Common)
} else {
Some(Script::Inherited)
}
// Are there bits left in the first chunk?
} else if self.ext.first != 0 {
// Find the next bit
let bit = self.ext.first.trailing_zeros();
// unset just that bit
self.ext.first &= !(1 << bit);
Some(Script::for_integer(bit as u8))
// Are there bits left in the second chunk?
} else if self.ext.second != 0 {
let bit = self.ext.second.trailing_zeros();
self.ext.second &= !(1 << bit);
Some(Script::for_integer(64 + bit as u8))
// Are there bits left in the third chunk?
} else if self.ext.third != 0 {
let bit = self.ext.third.trailing_zeros();
self.ext.third &= !(1 << bit);
Some(Script::for_integer(128 + bit as u8))
} else {
// Script::Unknown
None
}
}
}
#[cfg(test)]
mod tests {
use crate::*;
use std::collections::HashSet;
use std::convert::TryInto;
#[cfg(feature = "bench")]
use test::bench::Bencher;
#[cfg(feature = "bench")]
extern crate test;
#[test]
fn test_conversion() {
let mut seen_scripts = HashSet::new();
let mut seen_exts = HashSet::new();
for bit in 0..NEXT_SCRIPT {
let script = Script::for_integer(bit);
let ext = script.into();
if seen_scripts.contains(&script) {
panic!("Found script {:?} twice!", script)
}
if seen_exts.contains(&ext) {
panic!("Found extension {:?} twice!", ext)
}
seen_scripts.insert(script);
seen_exts.insert(ext);
assert_eq!(script as u8, bit);
assert!(!ScriptExtension::new_common().intersection(ext).is_empty());
assert!(!ScriptExtension::new_inherited()
.intersection(ext)
.is_empty());
assert!(ScriptExtension::new_unknown().intersection(ext).is_empty());
assert_eq!(ext.iter().collect::<Vec<_>>(), vec![script]);
assert_eq!(Ok(script), ext.try_into());
}
}
#[test]
fn test_specific() {
let s = "सवव मानवी व्यद्क् जन्मतःच स्वतींत्र आहेत व त्ाींना समान प्रवतष्ठा व समान अविकार आहेत. त्ाींना ववचारशद्क् व सवविे कबुद्द्धलाभलेली आहे. व त्ाींनी एकमेकाींशी बींिुत्वाचाभावनेने आचरण करावे.";
let ext = ScriptExtension::for_str(s);
assert_eq!(ext, script_extensions::DEVA);
println!(
"{:?}",
script_extensions::DEVA_DOGR_GUJR_GURU_KHOJ_KTHI_MAHJ_MODI_SIND_TAKR_TIRH
);
println!(
"{:?}",
ext.intersection(
script_extensions::DEVA_DOGR_GUJR_GURU_KHOJ_KTHI_MAHJ_MODI_SIND_TAKR_TIRH
)
);
assert!(!ext
.intersection(script_extensions::DEVA_DOGR_GUJR_GURU_KHOJ_KTHI_MAHJ_MODI_SIND_TAKR_TIRH)
.is_empty());
let u = ext.union(Script::Dogra.into());
assert_eq!(
u.intersection(
script_extensions::DEVA_DOGR_GUJR_GURU_KHOJ_KTHI_MAHJ_MODI_SIND_TAKR_TIRH
),
u
);
}
#[test]
fn test_specific_ext() {
let ext = script_extensions::DEVA_DOGR_GUJR_GURU_KHOJ_KTHI_MAHJ_MODI_SIND_TAKR_TIRH;
let all: HashSet<_> = ext.iter().collect();
for bit in 0..NEXT_SCRIPT {
let script = Script::for_integer(bit);
if all.contains(&script) {
assert!(ext.contains_script(script))
} else {
assert!(!ext.contains_script(script))
}
}
assert!(ext.contains_script(Script::Devanagari));
assert!(ext.contains_script(Script::Dogra));
assert!(ext.contains_script(Script::Gujarati));
assert!(ext.contains_script(Script::Gurmukhi));
assert!(ext.contains_script(Script::Khojki));
assert!(ext.contains_script(Script::Kaithi));
assert!(ext.contains_script(Script::Mahajani));
assert!(ext.contains_script(Script::Modi));
assert!(ext.contains_script(Script::Khudawadi));
assert!(ext.contains_script(Script::Takri));
assert!(ext.contains_script(Script::Tirhuta));
let scr: Result<Script, _> = ext.try_into();
assert!(scr.is_err());
}
#[cfg(feature = "bench")]
#[bench]
fn bench_script_intersection(b: &mut Bencher) {
b.iter(|| {
let script = test::black_box(Script::Devanagari);
let ext = test::black_box(script_extensions::BENG_DEVA_DOGR_GONG_GONM_GRAN_GUJR_GURU_KNDA_MAHJ_MLYM_NAND_ONAO_ORYA_SIND_SINH_SYLO_TAKR_TAML_TELU_TIRH);
test::black_box(ext.intersection(script.into()));
})
}
#[cfg(feature = "bench")]
#[bench]
fn bench_ext_to_script(b: &mut Bencher) {
let ext: ScriptExtension = Script::Devanagari.into();
b.iter(|| {
let ext = test::black_box(ext);
let script: Result<Script, _> = ext.try_into();
let _ = test::black_box(script);
})
}
#[cfg(feature = "bench")]
#[bench]
fn bench_script_to_ext(b: &mut Bencher) {
b.iter(|| {
let script = test::black_box(Script::Devanagari);
let ext: ScriptExtension = script.into();
test::black_box(ext);
})
}
#[cfg(feature = "bench")]
#[bench]
fn bench_ext_intersection(b: &mut Bencher) {
b.iter(|| {
let e1 = test::black_box(script_extensions::ARAB_GARA_NKOO_ROHG_SYRC_THAA_YEZI);
let e2 = test::black_box(script_extensions::BENG_DEVA_DOGR_GONG_GONM_GRAN_GUJR_GURU_KNDA_MAHJ_MLYM_NAND_ONAO_ORYA_SIND_SINH_SYLO_TAKR_TAML_TELU_TIRH);
test::black_box(e2.intersection(e1));
})
}
#[cfg(feature = "bench")]
#[bench]
fn bench_to_vec(b: &mut Bencher) {
b.iter(|| {
let ext = test::black_box(script_extensions::BENG_DEVA_DOGR_GONG_GONM_GRAN_GUJR_GURU_KNDA_MAHJ_MLYM_NAND_ONAO_ORYA_SIND_SINH_SYLO_TAKR_TAML_TELU_TIRH);
test::black_box(ext.iter().collect::<Vec<_>>());
})
}
#[cfg(feature = "bench")]
#[bench]
fn bench_string_ext(b: &mut Bencher) {
b.iter(|| {
let s = test::black_box("सवव मानवी व्यद्क् जन्मतःच स्वतींत्र आहेत व त्ाींना समान प्रवतष्ठा व समान अविकार आहेत. त्ाींना ववचारशद्क् व सवविे कबुद्द्धलाभलेली आहे. व त्ाींनी एकमेकाींशी बींिुत्वाचाभावनेने आचरण करावे.");
test::black_box(ScriptExtension::for_str(s));
})
}
}

3497
vendor/unicode-script/src/tables.rs vendored Normal file

File diff suppressed because it is too large Load Diff