ucd-parse-0.1.10/.cargo_vcs_info.json0000644000000001470000000000100130000ustar { "git": { "sha1": "a3f516ab9359130b56523c0836f9a8fa3b310eec" }, "path_in_vcs": "ucd-parse" }ucd-parse-0.1.10/Cargo.toml0000644000000021150000000000100107730ustar # 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 = "ucd-parse" version = "0.1.10" authors = ["Andrew Gallant "] description = """ A library for parsing data files in the Unicode character database. """ homepage = "https://github.com/BurntSushi/ucd-generate" documentation = "https://docs.rs/ucd-parse" readme = "README.md" keywords = [ "unicode", "database", "character", "property", ] license = "MIT OR Apache-2.0" repository = "https://github.com/BurntSushi/ucd-generate" [dependencies.once_cell] version = "1" [dependencies.regex] version = "1" features = [ "std", "unicode", ] default-features = false ucd-parse-0.1.10/Cargo.toml.orig000064400000000000000000000011371046102023000144570ustar 00000000000000[package] name = "ucd-parse" version = "0.1.10" #:version authors = ["Andrew Gallant "] description = """ A library for parsing data files in the Unicode character database. """ documentation = "https://docs.rs/ucd-parse" homepage = "https://github.com/BurntSushi/ucd-generate" repository = "https://github.com/BurntSushi/ucd-generate" readme = "README.md" keywords = ["unicode", "database", "character", "property"] license = "MIT OR Apache-2.0" edition = "2018" [dependencies] once_cell = "1" [dependencies.regex] version = "1" default-features = false features = ["std", "unicode"] ucd-parse-0.1.10/LICENSE-APACHE000064400000000000000000000251371046102023000135220ustar 00000000000000 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. ucd-parse-0.1.10/LICENSE-MIT000064400000000000000000000020711046102023000132220ustar 00000000000000The 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. ucd-parse-0.1.10/README.md000064400000000000000000000012251046102023000130450ustar 00000000000000ucd-parse ========= A library for parsing Unicode Character Database (UCD) files into structured data. [![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-parse.svg)](https://crates.io/crates/ucd-parse) ### Documentation https://docs.rs/ucd-parse ### 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. ucd-parse-0.1.10/src/age.rs000064400000000000000000000027561046102023000134710ustar 00000000000000use std::path::Path; use std::str::FromStr; use crate::common::{ parse_codepoint_association, CodepointIter, Codepoints, UcdFile, UcdFileByCodepoint, }; use crate::error::Error; /// A single row in the `DerivedAge.txt` file. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct Age { /// The codepoint or codepoint range for this entry. pub codepoints: Codepoints, /// The age assigned to the codepoints in this entry. pub age: String, } impl UcdFile for Age { fn relative_file_path() -> &'static Path { Path::new("DerivedAge.txt") } } impl UcdFileByCodepoint for Age { fn codepoints(&self) -> CodepointIter { self.codepoints.into_iter() } } impl FromStr for Age { type Err = Error; fn from_str(line: &str) -> Result { let (codepoints, script) = parse_codepoint_association(line)?; Ok(Age { codepoints, age: script.to_string() }) } } #[cfg(test)] mod tests { use super::Age; #[test] fn parse_single() { let line = "2BD2 ; 10.0 # GROUP MARK\n"; let row: Age = line.parse().unwrap(); assert_eq!(row.codepoints, 0x2BD2); assert_eq!(row.age, "10.0"); } #[test] fn parse_range() { let line = "11D0B..11D36 ; 10.0 # [44] MASARAM GONDI LETTER AU..MASARAM GONDI VOWEL SIGN VOCALIC R\n"; let row: Age = line.parse().unwrap(); assert_eq!(row.codepoints, (0x11D0B, 0x11D36)); assert_eq!(row.age, "10.0"); } } ucd-parse-0.1.10/src/arabic_shaping.rs000064400000000000000000000123261046102023000156610ustar 00000000000000use std::path::Path; use std::str::FromStr; use once_cell::sync::Lazy; use regex::Regex; use crate::common::{Codepoint, CodepointIter, UcdFile, UcdFileByCodepoint}; use crate::error::Error; /// Represents a single row in the `ArabicShaping.txt` file. /// /// The field names were taken from the header of ArabicShaping.txt. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct ArabicShaping { /// The codepoint corresponding to this row. pub codepoint: Codepoint, /// A short schematic name for the codepoint. /// /// The schematic name is descriptive of the shape, based as consistently as /// possible on a name for the skeleton and then the diacritic marks applied /// to the skeleton, if any. Note that this schematic name is considered a /// comment, and does not constitute a formal property value. pub schematic_name: String, /// The "joining type" of this codepoint. pub joining_type: JoiningType, /// The "joining group" of this codepoint. pub joining_group: String, } /// The Joining_Type field read from ArabicShaping.txt #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum JoiningType { RightJoining, LeftJoining, DualJoining, JoinCausing, NonJoining, Transparent, } impl JoiningType { pub fn as_str(&self) -> &str { match self { JoiningType::RightJoining => "R", JoiningType::LeftJoining => "L", JoiningType::DualJoining => "D", JoiningType::JoinCausing => "C", JoiningType::NonJoining => "U", JoiningType::Transparent => "T", } } } impl Default for JoiningType { fn default() -> JoiningType { JoiningType::NonJoining } } impl FromStr for JoiningType { type Err = Error; fn from_str(s: &str) -> Result { match s { "R" => Ok(JoiningType::RightJoining), "L" => Ok(JoiningType::LeftJoining), "D" => Ok(JoiningType::DualJoining), "C" => Ok(JoiningType::JoinCausing), "U" => Ok(JoiningType::NonJoining), "T" => Ok(JoiningType::Transparent), _ => err!( "unrecognized joining type: '{}' \ (must be one of R, L, D, C, U or T)", s ), } } } impl UcdFile for ArabicShaping { fn relative_file_path() -> &'static Path { Path::new("ArabicShaping.txt") } } impl UcdFileByCodepoint for ArabicShaping { fn codepoints(&self) -> CodepointIter { self.codepoint.into_iter() } } impl FromStr for ArabicShaping { type Err = Error; fn from_str(line: &str) -> Result { static PARTS: Lazy = Lazy::new(|| { Regex::new( r"(?x) ^ \s*(?P[A-F0-9]+)\s*; \s*(?P[^;]+)\s*; \s*(?P[^;]+)\s*; \s*(?P[^;]+) $ ", ) .unwrap() }); let caps = match PARTS.captures(line.trim()) { Some(caps) => caps, None => return err!("invalid ArabicShaping line"), }; Ok(ArabicShaping { codepoint: caps["codepoint"].parse()?, schematic_name: caps["name"].to_string(), joining_type: caps["joining_type"].parse()?, joining_group: caps["joining_group"].to_string(), }) } } #[cfg(test)] mod tests { use crate::common::Codepoint; use super::{ArabicShaping, JoiningType}; fn codepoint(n: u32) -> Codepoint { Codepoint::from_u32(n).unwrap() } fn s(string: &str) -> String { string.to_string() } #[test] fn parse1() { let line = "0600; ARABIC NUMBER SIGN; U; No_Joining_Group\n"; let data: ArabicShaping = line.parse().unwrap(); assert_eq!( data, ArabicShaping { codepoint: codepoint(0x0600), schematic_name: s("ARABIC NUMBER SIGN"), joining_type: JoiningType::NonJoining, joining_group: s("No_Joining_Group") } ); } #[test] fn parse2() { let line = "063D; FARSI YEH WITH INVERTED V ABOVE; D; FARSI YEH\n"; let data: ArabicShaping = line.parse().unwrap(); assert_eq!( data, ArabicShaping { codepoint: codepoint(0x063D), schematic_name: s("FARSI YEH WITH INVERTED V ABOVE"), joining_type: JoiningType::DualJoining, joining_group: s("FARSI YEH") } ); } #[test] fn parse3() { let line = "10D23; HANIFI ROHINGYA DOTLESS KINNA YA WITH DOT ABOVE; D; HANIFI ROHINGYA KINNA YA\n"; let data: ArabicShaping = line.parse().unwrap(); assert_eq!( data, ArabicShaping { codepoint: codepoint(0x10D23), schematic_name: s( "HANIFI ROHINGYA DOTLESS KINNA YA WITH DOT ABOVE" ), joining_type: JoiningType::DualJoining, joining_group: s("HANIFI ROHINGYA KINNA YA") } ); } } ucd-parse-0.1.10/src/bidi_mirroring_glyph.rs000064400000000000000000000053771046102023000171410ustar 00000000000000use std::fmt; use std::path::Path; use std::str::FromStr; use once_cell::sync::Lazy; use regex::Regex; use crate::common::{Codepoint, CodepointIter, UcdFile, UcdFileByCodepoint}; use crate::error::Error; /// Represents a single row in the `BidiMirroring.txt` file. /// /// The field names were taken from the header of BidiMirroring.txt. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct BidiMirroring { /// The codepoint corresponding to this row. pub codepoint: Codepoint, /// The codepoint that has typically has a glyph that is the mirror image /// of `codepoint`. pub bidi_mirroring_glyph: Codepoint, } impl UcdFile for BidiMirroring { fn relative_file_path() -> &'static Path { Path::new("BidiMirroring.txt") } } impl UcdFileByCodepoint for BidiMirroring { fn codepoints(&self) -> CodepointIter { self.codepoint.into_iter() } } impl FromStr for BidiMirroring { type Err = Error; fn from_str(line: &str) -> Result { static PARTS: Lazy = Lazy::new(|| { Regex::new( r"(?x) ^ \s*(?P[A-F0-9]+)\s*; \s*(?P[A-F0-9]+) \s+ \#(?:.+) $ ", ) .unwrap() }); let caps = match PARTS.captures(line.trim()) { Some(caps) => caps, None => return err!("invalid BidiMirroring line"), }; Ok(BidiMirroring { codepoint: caps["codepoint"].parse()?, bidi_mirroring_glyph: caps["substitute_codepoint"].parse()?, }) } } impl fmt::Display for BidiMirroring { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{};", self.codepoint)?; write!(f, "{};", self.bidi_mirroring_glyph)?; Ok(()) } } #[cfg(test)] mod tests { use crate::common::Codepoint; use super::BidiMirroring; fn codepoint(n: u32) -> Codepoint { Codepoint::from_u32(n).unwrap() } #[test] fn parse() { let line = "0028; 0029 # LEFT PARENTHESIS\n"; let data: BidiMirroring = line.parse().unwrap(); assert_eq!( data, BidiMirroring { codepoint: codepoint(0x0028), bidi_mirroring_glyph: codepoint(0x0029), } ); } #[test] fn parse_best_fit() { let line = "228A; 228B # [BEST FIT] SUBSET OF WITH NOT EQUAL TO\n"; let data: BidiMirroring = line.parse().unwrap(); assert_eq!( data, BidiMirroring { codepoint: codepoint(0x228A), bidi_mirroring_glyph: codepoint(0x228B), } ); } } ucd-parse-0.1.10/src/case_folding.rs000064400000000000000000000113721046102023000153440ustar 00000000000000use std::path::Path; use std::str::FromStr; use once_cell::sync::Lazy; use regex::Regex; use crate::common::{Codepoint, CodepointIter, UcdFile, UcdFileByCodepoint}; use crate::error::Error; /// A single row in the `CaseFolding.txt` file. /// /// The contents of `CaseFolding.txt` are a convenience derived from both /// `UnicodeData.txt` and `SpecialCasing.txt`. /// /// Note that a single codepoint may be mapped multiple times. In particular, /// a single codepoint might have distinct `CaseStatus::Simple` and /// `CaseStatus::Full` mappings. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct CaseFold { /// The codepoint that is being mapped. pub codepoint: Codepoint, /// The case status of this mapping. pub status: CaseStatus, /// The actual case mapping, which is more than one codepoint if this is /// a "full" mapping. pub mapping: Vec, } impl UcdFile for CaseFold { fn relative_file_path() -> &'static Path { Path::new("CaseFolding.txt") } } impl UcdFileByCodepoint for CaseFold { fn codepoints(&self) -> CodepointIter { self.codepoint.into_iter() } } impl FromStr for CaseFold { type Err = Error; fn from_str(line: &str) -> Result { static PARTS: Lazy = Lazy::new(|| { Regex::new( r"(?x) ^ \s*(?P[^\s;]+)\s*; \s*(?P[^\s;]+)\s*; \s*(?P[^;]+)\s*; ", ) .unwrap() }); let caps = match PARTS.captures(line.trim()) { Some(caps) => caps, None => return err!("invalid CaseFolding line: '{}'", line), }; let mut mapping = vec![]; for cp in caps["mapping"].split_whitespace() { mapping.push(cp.parse()?); } Ok(CaseFold { codepoint: caps["codepoint"].parse()?, status: caps["status"].parse()?, mapping, }) } } /// The status of a particular case mapping. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum CaseStatus { /// Case mappings shared by both "simple" and "full" mappings. Common, /// A case mapping that changes the number of codepoints. Full, /// A case mapping that doesn't change the number of codepoints, when it /// differs from `Full`. Simple, /// Special cases (currently only for Turkic mappings) that are typically /// excluded by default. Special cases don't change the number of /// codepoints, but may changed the encoding (e.g., UTF-8) length in bytes. Special, } impl Default for CaseStatus { fn default() -> CaseStatus { CaseStatus::Common } } impl CaseStatus { /// Returns true if and only if this status indicates a case mapping that /// won't change the number of codepoints. pub fn is_fixed(&self) -> bool { *self != CaseStatus::Full } } impl FromStr for CaseStatus { type Err = Error; fn from_str(s: &str) -> Result { match s { "C" => Ok(CaseStatus::Common), "F" => Ok(CaseStatus::Full), "S" => Ok(CaseStatus::Simple), "T" => Ok(CaseStatus::Special), _ => err!( "unrecognized case status: '{}' \ (must be one of C, F, S or T)", s ), } } } #[cfg(test)] mod tests { use super::{CaseFold, CaseStatus}; #[test] fn parse_common() { let line = "0150; C; 0151; # LATIN CAPITAL LETTER O WITH DOUBLE ACUTE\n"; let row: CaseFold = line.parse().unwrap(); assert_eq!(row.codepoint, 0x0150); assert_eq!(row.status, CaseStatus::Common); assert_eq!(row.mapping, vec![0x0151]); } #[test] fn parse_full() { let line = "03B0; F; 03C5 0308 0301; # GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS\n"; let row: CaseFold = line.parse().unwrap(); assert_eq!(row.codepoint, 0x03B0); assert_eq!(row.status, CaseStatus::Full); assert_eq!(row.mapping, vec![0x03C5, 0x0308, 0x0301]); } #[test] fn parse_simple() { let line = "1F8F; S; 1F87; # GREEK CAPITAL LETTER ALPHA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI\n"; let row: CaseFold = line.parse().unwrap(); assert_eq!(row.codepoint, 0x1F8F); assert_eq!(row.status, CaseStatus::Simple); assert_eq!(row.mapping, vec![0x1F87]); } #[test] fn parse_special() { let line = "0049; T; 0131; # LATIN CAPITAL LETTER I\n"; let row: CaseFold = line.parse().unwrap(); assert_eq!(row.codepoint, 0x0049); assert_eq!(row.status, CaseStatus::Special); assert_eq!(row.mapping, vec![0x0131]); } } ucd-parse-0.1.10/src/common.rs000064400000000000000000000414561046102023000142250ustar 00000000000000use std::char; use std::collections::BTreeMap; use std::fmt; use std::fs::File; use std::io::{self, BufRead}; use std::marker::PhantomData; use std::path::{Path, PathBuf}; use std::str::FromStr; use once_cell::sync::Lazy; use regex::Regex; use crate::error::{Error, ErrorKind}; /// Parse a particular file in the UCD into a sequence of rows. /// /// The given directory should be the directory to the UCD. pub fn parse(ucd_dir: P) -> Result, Error> where P: AsRef, D: UcdFile, { let mut xs = vec![]; for result in D::from_dir(ucd_dir)? { let x = result?; xs.push(x); } Ok(xs) } /// Parse a particular file in the UCD into a map from codepoint to the record. /// /// The given directory should be the directory to the UCD. pub fn parse_by_codepoint( ucd_dir: P, ) -> Result, Error> where P: AsRef, D: UcdFileByCodepoint, { let mut map = BTreeMap::new(); for result in D::from_dir(ucd_dir)? { let x = result?; for cp in x.codepoints() { map.insert(cp, x.clone()); } } Ok(map) } /// Parse a particular file in the UCD into a map from codepoint to all /// records associated with that codepoint. /// /// This is useful for files that have multiple records for each codepoint. /// For example, the `NameAliases.txt` file lists multiple aliases for some /// codepoints. /// /// The given directory should be the directory to the UCD. pub fn parse_many_by_codepoint( ucd_dir: P, ) -> Result>, Error> where P: AsRef, D: UcdFileByCodepoint, { let mut map = BTreeMap::new(); for result in D::from_dir(ucd_dir)? { let x = result?; for cp in x.codepoints() { map.entry(cp).or_insert(vec![]).push(x.clone()); } } Ok(map) } /// Given a path pointing at the root of the `ucd_dir`, attempts to determine /// it's unicode version. /// /// This just checks the readme and the very first line of PropList.txt -- in /// practice this works for all versions of UCD since 4.1.0. pub fn ucd_directory_version>( ucd_dir: &D, ) -> Result<(u64, u64, u64), Error> { // Avoid duplication from generic path parameter. fn ucd_directory_version_inner( ucd_dir: &Path, ) -> Result<(u64, u64, u64), Error> { static VERSION_RX: Lazy = Lazy::new(|| { Regex::new(r"-([0-9]+).([0-9]+).([0-9]+).txt").unwrap() }); let proplist = ucd_dir.join("PropList.txt"); let contents = first_line(&proplist)?; let caps = match VERSION_RX.captures(&contents) { Some(c) => c, None => { return err!("Failed to find version in line {:?}", contents) } }; let capture_to_num = |n| { caps.get(n).unwrap().as_str().parse::().map_err(|e| Error { kind: ErrorKind::Parse(format!( "Failed to parse version from {:?} in PropList.txt: {}", contents, e )), line: Some(0), path: Some(proplist.clone()), }) }; let major = capture_to_num(1)?; let minor = capture_to_num(2)?; let patch = capture_to_num(3)?; Ok((major, minor, patch)) } ucd_directory_version_inner(ucd_dir.as_ref()) } fn first_line(path: &Path) -> Result { let file = std::fs::File::open(path).map_err(|e| Error { kind: ErrorKind::Io(e), line: None, path: Some(path.into()), })?; let mut reader = std::io::BufReader::new(file); let mut line_contents = String::new(); reader.read_line(&mut line_contents).map_err(|e| Error { kind: ErrorKind::Io(e), line: None, path: Some(path.into()), })?; Ok(line_contents) } /// A helper function for parsing a common record format that associates one /// or more codepoints with a string value. pub fn parse_codepoint_association<'a>( line: &'a str, ) -> Result<(Codepoints, &'a str), Error> { static PARTS: Lazy = Lazy::new(|| { Regex::new( r"(?x) ^ \s*(?P[^\s;]+)\s*; \s*(?P[^;\x23]+)\s* ", ) .unwrap() }); let caps = match PARTS.captures(line.trim()) { Some(caps) => caps, None => return err!("invalid PropList line: '{}'", line), }; let property = match caps.name("property") { Some(property) => property.as_str().trim(), None => { return err!( "could not find property name in PropList line: '{}'", line ) } }; Ok((caps["codepoints"].parse()?, property)) } /// A helper function for parsing a sequence of space separated codepoints. /// The sequence is permitted to be empty. pub fn parse_codepoint_sequence(s: &str) -> Result, Error> { let mut cps = vec![]; for cp in s.trim().split_whitespace() { cps.push(cp.parse()?); } Ok(cps) } /// A helper function for parsing a single test for the various break /// algorithms. /// /// Upon success, this returns the UTF-8 encoded groups of codepoints along /// with the comment associated with the test. The comment is a human readable /// description of the test that may prove useful for debugging. pub fn parse_break_test(line: &str) -> Result<(Vec, String), Error> { static PARTS: Lazy = Lazy::new(|| { Regex::new( r"(?x) ^ (?:÷|×) (?P(?:\s[0-9A-Fa-f]{4,5}\s(?:÷|×))+) \s+ \#(?P.+) $ ", ) .unwrap() }); static GROUP: Lazy = Lazy::new(|| { Regex::new( r"(?x) (?P[0-9A-Fa-f]{4,5})\s(?P÷|×) ", ) .unwrap() }); let caps = match PARTS.captures(line.trim()) { Some(caps) => caps, None => return err!("invalid break test line: '{}'", line), }; let comment = caps["comment"].trim().to_string(); let mut groups = vec![]; let mut cur = String::new(); for cap in GROUP.captures_iter(&caps["groups"]) { let cp: Codepoint = cap["codepoint"].parse()?; let ch = match cp.scalar() { Some(ch) => ch, None => { return err!( "invalid codepoint '{:X}' in line: '{}'", cp.value(), line ) } }; cur.push(ch); if &cap["kind"] == "÷" { groups.push(cur); cur = String::new(); } } Ok((groups, comment)) } /// Describes a single UCD file. pub trait UcdFile: Clone + fmt::Debug + Default + Eq + FromStr + PartialEq { /// The file path corresponding to this file, relative to the UCD /// directory. fn relative_file_path() -> &'static Path; /// The full file path corresponding to this file given the UCD directory /// path. fn file_path>(ucd_dir: P) -> PathBuf { ucd_dir.as_ref().join(Self::relative_file_path()) } /// Create an iterator over each record in this UCD file. /// /// The parameter should correspond to the directory containing the UCD. fn from_dir>( ucd_dir: P, ) -> Result, Error> { UcdLineParser::from_path(Self::file_path(ucd_dir)) } } /// Describes a single UCD file where every record in the file is associated /// with one or more codepoints. pub trait UcdFileByCodepoint: UcdFile { /// Returns the codepoints associated with this record. fn codepoints(&self) -> CodepointIter; } /// A line oriented parser for a particular UCD file. /// /// Callers can build a line parser via the /// [`UcdFile::from_dir`](trait.UcdFile.html) method. /// /// The `R` type parameter refers to the underlying `io::Read` implementation /// from which the UCD data is read. /// /// The `D` type parameter refers to the type of the record parsed out of each /// line. #[derive(Debug)] pub struct UcdLineParser { path: Option, rdr: io::BufReader, line: String, line_number: u64, _data: PhantomData, } impl UcdLineParser { /// Create a new parser from the given file path. pub(crate) fn from_path>( path: P, ) -> Result, Error> { let path = path.as_ref(); let file = File::open(path).map_err(|e| Error { kind: ErrorKind::Io(e), line: None, path: Some(path.to_path_buf()), })?; Ok(UcdLineParser::new(Some(path.to_path_buf()), file)) } } impl UcdLineParser { /// Create a new parser that parses the reader given. /// /// The type of data parsed is determined when the `parse_next` function /// is called by virtue of the type requested. /// /// Note that the reader is buffered internally, so the caller does not /// need to provide their own buffering. pub(crate) fn new(path: Option, rdr: R) -> UcdLineParser { UcdLineParser { path, rdr: io::BufReader::new(rdr), line: String::new(), line_number: 0, _data: PhantomData, } } } impl> Iterator for UcdLineParser { type Item = Result; fn next(&mut self) -> Option> { loop { self.line_number += 1; self.line.clear(); let n = match self.rdr.read_line(&mut self.line) { Err(err) => { return Some(Err(Error { kind: ErrorKind::Io(err), line: None, path: self.path.clone(), })) } Ok(n) => n, }; if n == 0 { return None; } if !self.line.starts_with('#') && !self.line.trim().is_empty() { break; } } let line_number = self.line_number; Some(self.line.parse().map_err(|mut err: Error| { err.line = Some(line_number); err })) } } /// A representation of either a single codepoint or a range of codepoints. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)] pub enum Codepoints { /// A single codepoint. Single(Codepoint), /// A range of codepoints. Range(CodepointRange), } impl Default for Codepoints { fn default() -> Codepoints { Codepoints::Single(Codepoint::default()) } } impl IntoIterator for Codepoints { type IntoIter = CodepointIter; type Item = Codepoint; fn into_iter(self) -> CodepointIter { match self { Codepoints::Single(x) => x.into_iter(), Codepoints::Range(x) => x.into_iter(), } } } impl FromStr for Codepoints { type Err = Error; fn from_str(s: &str) -> Result { if s.contains("..") { CodepointRange::from_str(s).map(Codepoints::Range) } else { Codepoint::from_str(s).map(Codepoints::Single) } } } impl fmt::Display for Codepoints { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { Codepoints::Single(ref x) => x.fmt(f), Codepoints::Range(ref x) => x.fmt(f), } } } impl PartialEq for Codepoints { fn eq(&self, other: &u32) -> bool { match *self { Codepoints::Single(ref x) => x == other, Codepoints::Range(ref x) => x == &(*other, *other), } } } impl PartialEq for Codepoints { fn eq(&self, other: &Codepoint) -> bool { match *self { Codepoints::Single(ref x) => x == other, Codepoints::Range(ref x) => x == &(*other, *other), } } } impl PartialEq<(u32, u32)> for Codepoints { fn eq(&self, other: &(u32, u32)) -> bool { match *self { Codepoints::Single(ref x) => &(x.value(), x.value()) == other, Codepoints::Range(ref x) => x == other, } } } impl PartialEq<(Codepoint, Codepoint)> for Codepoints { fn eq(&self, other: &(Codepoint, Codepoint)) -> bool { match *self { Codepoints::Single(ref x) => &(*x, *x) == other, Codepoints::Range(ref x) => x == other, } } } /// A range of Unicode codepoints. The range is inclusive; both ends of the /// range are guaranteed to be valid codepoints. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, PartialOrd, Ord, )] pub struct CodepointRange { /// The start of the codepoint range. pub start: Codepoint, /// The end of the codepoint range. pub end: Codepoint, } impl IntoIterator for CodepointRange { type IntoIter = CodepointIter; type Item = Codepoint; fn into_iter(self) -> CodepointIter { CodepointIter { next: self.start.value(), range: self } } } impl FromStr for CodepointRange { type Err = Error; fn from_str(s: &str) -> Result { static PARTS: Lazy = Lazy::new(|| { Regex::new(r"^(?P[A-Z0-9]+)\.\.(?P[A-Z0-9]+)$") .unwrap() }); let caps = match PARTS.captures(s) { Some(caps) => caps, None => return err!("invalid codepoint range: '{}'", s), }; let start = caps["start"].parse().or_else(|err| { err!("failed to parse '{}' as a codepoint range: {}", s, err) })?; let end = caps["end"].parse().or_else(|err| { err!("failed to parse '{}' as a codepoint range: {}", s, err) })?; Ok(CodepointRange { start, end }) } } impl fmt::Display for CodepointRange { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}..{}", self.start, self.end) } } impl PartialEq<(u32, u32)> for CodepointRange { fn eq(&self, other: &(u32, u32)) -> bool { &(self.start.value(), self.end.value()) == other } } impl PartialEq<(Codepoint, Codepoint)> for CodepointRange { fn eq(&self, other: &(Codepoint, Codepoint)) -> bool { &(self.start, self.end) == other } } /// A single Unicode codepoint. /// /// This type's string representation is a hexadecimal number. It is guaranteed /// to be in the range `[0, 10FFFF]`. /// /// Note that unlike Rust's `char` type, this may be a surrogate codepoint. #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, PartialOrd, Ord, )] pub struct Codepoint(u32); impl Codepoint { /// Create a new codepoint from a `u32`. /// /// If the given number is not a valid codepoint, then this returns an /// error. pub fn from_u32(n: u32) -> Result { if n > 0x10FFFF { err!("{:x} is not a valid Unicode codepoint", n) } else { Ok(Codepoint(n)) } } /// Return the underlying `u32` codepoint value. pub fn value(self) -> u32 { self.0 } /// Attempt to convert this codepoint to a Unicode scalar value. /// /// If this is a surrogate codepoint, then this returns `None`. pub fn scalar(self) -> Option { char::from_u32(self.0) } } impl IntoIterator for Codepoint { type IntoIter = CodepointIter; type Item = Codepoint; fn into_iter(self) -> CodepointIter { let range = CodepointRange { start: self, end: self }; CodepointIter { next: self.value(), range } } } impl FromStr for Codepoint { type Err = Error; fn from_str(s: &str) -> Result { match u32::from_str_radix(s, 16) { Ok(n) => Codepoint::from_u32(n), Err(err) => { return err!( "failed to parse '{}' as a hexadecimal codepoint: {}", s, err ); } } } } impl fmt::Display for Codepoint { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:04X}", self.0) } } impl PartialEq for Codepoint { fn eq(&self, other: &u32) -> bool { self.0 == *other } } impl PartialEq for u32 { fn eq(&self, other: &Codepoint) -> bool { *self == other.0 } } /// An iterator over a range of Unicode codepoints. #[derive(Debug)] pub struct CodepointIter { next: u32, range: CodepointRange, } impl Iterator for CodepointIter { type Item = Codepoint; fn next(&mut self) -> Option { if self.next > self.range.end.value() { return None; } let current = self.next; self.next += 1; Some(Codepoint::from_u32(current).unwrap()) } } ucd-parse-0.1.10/src/core_properties.rs000064400000000000000000000032321046102023000161270ustar 00000000000000use std::path::Path; use std::str::FromStr; use crate::common::{ parse_codepoint_association, CodepointIter, Codepoints, UcdFile, UcdFileByCodepoint, }; use crate::error::Error; /// A single row in the `DerivedCoreProperties.txt` file. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct CoreProperty { /// The codepoint or codepoint range for this entry. pub codepoints: Codepoints, /// The property name assigned to the codepoints in this entry. pub property: String, } impl UcdFile for CoreProperty { fn relative_file_path() -> &'static Path { Path::new("DerivedCoreProperties.txt") } } impl UcdFileByCodepoint for CoreProperty { fn codepoints(&self) -> CodepointIter { self.codepoints.into_iter() } } impl FromStr for CoreProperty { type Err = Error; fn from_str(line: &str) -> Result { let (codepoints, property) = parse_codepoint_association(line)?; Ok(CoreProperty { codepoints, property: property.to_string() }) } } #[cfg(test)] mod tests { use super::CoreProperty; #[test] fn parse_single() { let line = "1163D ; Case_Ignorable # Mn MODI SIGN ANUSVARA\n"; let row: CoreProperty = line.parse().unwrap(); assert_eq!(row.codepoints, 0x1163D); assert_eq!(row.property, "Case_Ignorable"); } #[test] fn parse_range() { let line = "11133..11134 ; Grapheme_Link # Mn [2] CHAKMA VIRAMA..CHAKMA MAAYYAA\n"; let row: CoreProperty = line.parse().unwrap(); assert_eq!(row.codepoints, (0x11133, 0x11134)); assert_eq!(row.property, "Grapheme_Link"); } } ucd-parse-0.1.10/src/east_asian_width.rs000064400000000000000000000034451046102023000162370ustar 00000000000000use std::path::Path; use std::str::FromStr; use crate::common::{ parse_codepoint_association, CodepointIter, Codepoints, UcdFile, UcdFileByCodepoint, }; use crate::error::Error; /// A single row in the `EastAsianWidth.txt` file, describing the value of the /// `East_Asian_Width` property. /// /// Note: All code points, assigned or unassigned, that are not listed in /// EastAsianWidth.txt file are given the value "N". #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct EastAsianWidth { /// The codepoint or codepoint range for this entry. pub codepoints: Codepoints, /// One of "A", "F", "H", "N", "Na", "W". pub width: String, } impl UcdFile for EastAsianWidth { fn relative_file_path() -> &'static Path { Path::new("EastAsianWidth.txt") } } impl UcdFileByCodepoint for EastAsianWidth { fn codepoints(&self) -> CodepointIter { self.codepoints.into_iter() } } impl FromStr for EastAsianWidth { type Err = Error; fn from_str(line: &str) -> Result { let (codepoints, width) = parse_codepoint_association(line)?; Ok(EastAsianWidth { codepoints, width: width.to_string() }) } } #[cfg(test)] mod tests { use super::EastAsianWidth; #[test] fn parse_single() { let line = "27E7;Na # Pe MATHEMATICAL RIGHT WHITE SQUARE BRACKET\n"; let row: EastAsianWidth = line.parse().unwrap(); assert_eq!(row.codepoints, 0x27E7); assert_eq!(row.width, "Na"); } #[test] fn parse_range() { let line = "1F57B..1F594;N # So [26] LEFT HAND TELEPHONE RECEIVER..REVERSED VICTORY HAND\n"; let row: EastAsianWidth = line.parse().unwrap(); assert_eq!(row.codepoints, (0x1F57B, 0x1F594)); assert_eq!(row.width, "N"); } } ucd-parse-0.1.10/src/emoji_properties.rs000064400000000000000000000052541046102023000163100ustar 00000000000000use std::path::{Path, PathBuf}; use std::str::FromStr; use crate::common::{ parse_codepoint_association, CodepointIter, Codepoints, UcdFile, UcdFileByCodepoint, }; use crate::error::Error; /// A single row in the `emoji-data.txt` file. /// /// The `emoji-data.txt` file is the source of truth on several Emoji-related /// Unicode properties. /// /// Note that `emoji-data.txt` is not formally part of the Unicode Character /// Database. You can download the Emoji data files separately here: /// https://unicode.org/Public/emoji/ #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct EmojiProperty { /// The codepoint or codepoint range for this entry. pub codepoints: Codepoints, /// The property name assigned to the codepoints in this entry. pub property: String, } impl UcdFile for EmojiProperty { fn relative_file_path() -> &'static Path { Path::new("emoji/emoji-data.txt") } fn file_path>(ucd_dir: P) -> PathBuf { let ucd_dir = ucd_dir.as_ref(); // The standard location, but only on UCDs from 13.0.0 and up. let std = ucd_dir.join(Self::relative_file_path()); if std.exists() { std } else { // If the old location does exist, use it. let legacy = ucd_dir.join("emoji-data.txt"); if legacy.exists() { legacy } else { // This might end up in an error message, so use the standard // one if forced to choose. Arguably we could do something like // peek std } } } } impl UcdFileByCodepoint for EmojiProperty { fn codepoints(&self) -> CodepointIter { self.codepoints.into_iter() } } impl FromStr for EmojiProperty { type Err = Error; fn from_str(line: &str) -> Result { let (codepoints, property) = parse_codepoint_association(line)?; Ok(EmojiProperty { codepoints, property: property.to_string() }) } } #[cfg(test)] mod tests { use super::EmojiProperty; #[test] fn parse_single() { let line = "24C2 ; Emoji # 1.1 [1] (Ⓜ️) circled M\n"; let row: EmojiProperty = line.parse().unwrap(); assert_eq!(row.codepoints, 0x24C2); assert_eq!(row.property, "Emoji"); } #[test] fn parse_range() { let line = "1FA6E..1FFFD ; Extended_Pictographic# NA[1424] (🩮️..🿽️) ..\n"; let row: EmojiProperty = line.parse().unwrap(); assert_eq!(row.codepoints, (0x1FA6E, 0x1FFFD)); assert_eq!(row.property, "Extended_Pictographic"); } } ucd-parse-0.1.10/src/error.rs000064400000000000000000000044301046102023000140550ustar 00000000000000use std::error; use std::fmt; use std::io; use std::path::{Path, PathBuf}; /// Represents any kind of error that can occur while parsing the UCD. #[derive(Debug)] pub struct Error { pub(crate) kind: ErrorKind, pub(crate) line: Option, pub(crate) path: Option, } /// The kind of error that occurred while parsing the UCD. #[derive(Debug)] pub enum ErrorKind { /// An I/O error. Io(io::Error), /// A generic parse error. Parse(String), } impl Error { /// Create a new parse error from the given message. pub(crate) fn parse(msg: String) -> Error { Error { kind: ErrorKind::Parse(msg), line: None, path: None } } /// Return the specific kind of this error. pub fn kind(&self) -> &ErrorKind { &self.kind } /// Return the line number at which this error occurred, if available. pub fn line(&self) -> Option { self.line } /// Return the file path associated with this error, if one exists. pub fn path(&self) -> Option<&Path> { self.path.as_ref().map(|p| &**p) } /// Unwrap this error into its underlying kind. pub fn into_kind(self) -> ErrorKind { self.kind } /// Returns true if and only if this is an I/O error. /// /// If this returns true, the underlying `ErrorKind` is guaranteed to be /// `ErrorKind::Io`. pub fn is_io_error(&self) -> bool { match self.kind { ErrorKind::Io(_) => true, _ => false, } } } impl error::Error for Error { fn cause(&self) -> Option<&dyn error::Error> { match self.kind { ErrorKind::Io(ref err) => Some(err), _ => None, } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if let Some(ref path) = self.path { if let Some(line) = self.line { write!(f, "{}:{}: ", path.display(), line)?; } else { write!(f, "{}: ", path.display())?; } } else if let Some(line) = self.line { write!(f, "error on line {}: ", line)?; } match self.kind { ErrorKind::Io(ref err) => write!(f, "{}", err), ErrorKind::Parse(ref msg) => write!(f, "{}", msg), } } } ucd-parse-0.1.10/src/extracted/derived_bidi_class.rs000064400000000000000000000033111046102023000205020ustar 00000000000000use std::path::Path; use std::str::FromStr; use crate::common::{ parse_codepoint_association, CodepointIter, Codepoints, UcdFile, UcdFileByCodepoint, }; use crate::error::Error; /// A single row in the `extracted/DerivedBidiClass.txt` file. /// /// This file gives the derived values of the Bidi_Class property. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct DerivedBidiClass { /// The codepoint or codepoint range for this entry. pub codepoints: Codepoints, /// The derived Bidi_Class of the codepoints in this entry. pub bidi_class: String, } impl UcdFile for DerivedBidiClass { fn relative_file_path() -> &'static Path { Path::new("extracted/DerivedBidiClass.txt") } } impl UcdFileByCodepoint for DerivedBidiClass { fn codepoints(&self) -> CodepointIter { self.codepoints.into_iter() } } impl FromStr for DerivedBidiClass { type Err = Error; fn from_str(line: &str) -> Result { let (codepoints, bidi_class) = parse_codepoint_association(line)?; Ok(DerivedBidiClass { codepoints, bidi_class: bidi_class.to_string() }) } } #[cfg(test)] mod tests { use super::DerivedBidiClass; #[test] fn parse_single() { let line = "00B5 ; L # L& MICRO SIGN\n"; let row: DerivedBidiClass = line.parse().unwrap(); assert_eq!(row.codepoints, 0x00B5); assert_eq!(row.bidi_class, "L"); } #[test] fn parse_range() { let line = "0030..0039 ; EN # Nd [10] DIGIT ZERO..DIGIT NINE\n"; let row: DerivedBidiClass = line.parse().unwrap(); assert_eq!(row.codepoints, (0x0030, 0x0039)); assert_eq!(row.bidi_class, "EN"); } } ucd-parse-0.1.10/src/extracted/derived_binary_properties.rs000064400000000000000000000037311046102023000221540ustar 00000000000000use std::path::Path; use std::str::FromStr; use crate::common::{ parse_codepoint_association, CodepointIter, Codepoints, UcdFile, UcdFileByCodepoint, }; use crate::error::Error; /// A single row in the `extracted/DerivedBinaryProperties.txt` file. /// /// This file indicates whether a codepoint has the Bidi_Mirrored property. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct DerivedBinaryProperties { /// The codepoint or codepoint range for this entry. pub codepoints: Codepoints, /// The derived property of the codepoints in this entry. Currently, /// this is always the always the string "Bidi_Mirrored". pub property: String, } impl UcdFile for DerivedBinaryProperties { fn relative_file_path() -> &'static Path { Path::new("extracted/DerivedBinaryProperties.txt") } } impl UcdFileByCodepoint for DerivedBinaryProperties { fn codepoints(&self) -> CodepointIter { self.codepoints.into_iter() } } impl FromStr for DerivedBinaryProperties { type Err = Error; fn from_str(line: &str) -> Result { let (codepoints, property) = parse_codepoint_association(line)?; Ok(DerivedBinaryProperties { codepoints, property: property.to_string(), }) } } #[cfg(test)] mod tests { use super::DerivedBinaryProperties; #[test] fn parse_single() { let line = "0028 ; Bidi_Mirrored # Ps LEFT PARENTHESIS\n"; let row: DerivedBinaryProperties = line.parse().unwrap(); assert_eq!(row.codepoints, 0x0028); assert_eq!(row.property, "Bidi_Mirrored"); } #[test] fn parse_range() { let line = "2A3C..2A3E ; Bidi_Mirrored # Sm [3] INTERIOR PRODUCT..Z NOTATION RELATIONAL COMPOSITION\n"; let row: DerivedBinaryProperties = line.parse().unwrap(); assert_eq!(row.codepoints, (0x2A3C, 0x2A3E)); assert_eq!(row.property, "Bidi_Mirrored"); } } ucd-parse-0.1.10/src/extracted/derived_combining_class.rs000064400000000000000000000035641046102023000215520ustar 00000000000000use std::path::Path; use std::str::FromStr; use crate::common::{ parse_codepoint_association, CodepointIter, Codepoints, UcdFile, UcdFileByCodepoint, }; use crate::error::Error; /// A single row in the `extracted/DerivedCombiningClass.txt` file. /// /// This file gives the derived values of the Canonical_Combining_Class /// property. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct DerivedCombiningClass { /// The codepoint or codepoint range for this entry. pub codepoints: Codepoints, /// The derived Canonical_Combining_Class of the codepoints in this entry. pub combining_class: String, } impl UcdFile for DerivedCombiningClass { fn relative_file_path() -> &'static Path { Path::new("extracted/DerivedCombiningClass.txt") } } impl UcdFileByCodepoint for DerivedCombiningClass { fn codepoints(&self) -> CodepointIter { self.codepoints.into_iter() } } impl FromStr for DerivedCombiningClass { type Err = Error; fn from_str(line: &str) -> Result { let (codepoints, combining_class) = parse_codepoint_association(line)?; Ok(DerivedCombiningClass { codepoints, combining_class: combining_class.to_string(), }) } } #[cfg(test)] mod tests { use super::DerivedCombiningClass; #[test] fn parse_single() { let line = "0020 ; 0 # Zs SPACE\n"; let row: DerivedCombiningClass = line.parse().unwrap(); assert_eq!(row.codepoints, 0x0020); assert_eq!(row.combining_class, "0"); } #[test] fn parse_range() { let line = "1DD1..1DF5 ; 230 # Mn [37] COMBINING UR ABOVE..COMBINING UP TACK ABOVE\n"; let row: DerivedCombiningClass = line.parse().unwrap(); assert_eq!(row.codepoints, (0x1DD1, 0x1DF5)); assert_eq!(row.combining_class, "230"); } } ucd-parse-0.1.10/src/extracted/derived_decomposition_type.rs000064400000000000000000000036761046102023000223410ustar 00000000000000use std::path::Path; use std::str::FromStr; use crate::common::{ parse_codepoint_association, CodepointIter, Codepoints, UcdFile, UcdFileByCodepoint, }; use crate::error::Error; /// A single row in the `extracted/DerivedCombiningClass.txt` file. /// /// This file gives the derived values of the Decomposition_Type /// property. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct DerivedDecompositionType { /// The codepoint or codepoint range for this entry. pub codepoints: Codepoints, /// The derived Decomposition_Type of the codepoints in this entry. pub decomposition_type: String, } impl UcdFile for DerivedDecompositionType { fn relative_file_path() -> &'static Path { Path::new("extracted/DerivedDecompositionType.txt") } } impl UcdFileByCodepoint for DerivedDecompositionType { fn codepoints(&self) -> CodepointIter { self.codepoints.into_iter() } } impl FromStr for DerivedDecompositionType { type Err = Error; fn from_str(line: &str) -> Result { let (codepoints, decomposition_type) = parse_codepoint_association(line)?; Ok(DerivedDecompositionType { codepoints, decomposition_type: decomposition_type.to_string(), }) } } #[cfg(test)] mod tests { use super::DerivedDecompositionType; #[test] fn parse_single() { let line = "00A0 ; Nobreak # Zs NO-BREAK SPACE\n"; let row: DerivedDecompositionType = line.parse().unwrap(); assert_eq!(row.codepoints, 0x00A0); assert_eq!(row.decomposition_type, "Nobreak"); } #[test] fn parse_range() { let line = "3070..3071 ; Canonical # Lo [2] HIRAGANA LETTER BA..HIRAGANA LETTER PA\n"; let row: DerivedDecompositionType = line.parse().unwrap(); assert_eq!(row.codepoints, (0x3070, 0x3071)); assert_eq!(row.decomposition_type, "Canonical"); } } ucd-parse-0.1.10/src/extracted/derived_east_asian_width.rs000064400000000000000000000035701046102023000217230ustar 00000000000000use std::path::Path; use std::str::FromStr; use crate::common::{ parse_codepoint_association, CodepointIter, Codepoints, UcdFile, UcdFileByCodepoint, }; use crate::error::Error; /// A single row in the `extracted/DerivedEastAsianWidth.txt` file. /// /// This file gives the derived values of the East_Asian_Width /// property. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct DerivedEastAsianWidth { /// The codepoint or codepoint range for this entry. pub codepoints: Codepoints, /// The derived East_Asian_Width of the codepoints in this entry. pub east_asian_width: String, } impl UcdFile for DerivedEastAsianWidth { fn relative_file_path() -> &'static Path { Path::new("extracted/DerivedEastAsianWidth.txt") } } impl UcdFileByCodepoint for DerivedEastAsianWidth { fn codepoints(&self) -> CodepointIter { self.codepoints.into_iter() } } impl FromStr for DerivedEastAsianWidth { type Err = Error; fn from_str(line: &str) -> Result { let (codepoints, east_asian_width) = parse_codepoint_association(line)?; Ok(DerivedEastAsianWidth { codepoints, east_asian_width: east_asian_width.to_string(), }) } } #[cfg(test)] mod tests { use super::DerivedEastAsianWidth; #[test] fn parse_single() { let line = "00A0 ; N # Zs NO-BREAK SPACE\n"; let row: DerivedEastAsianWidth = line.parse().unwrap(); assert_eq!(row.codepoints, 0x00A0); assert_eq!(row.east_asian_width, "N"); } #[test] fn parse_range() { let line = "FF10..FF19 ; F # Nd [10] FULLWIDTH DIGIT ZERO..FULLWIDTH DIGIT NINE\n"; let row: DerivedEastAsianWidth = line.parse().unwrap(); assert_eq!(row.codepoints, (0xFF10, 0xFF19)); assert_eq!(row.east_asian_width, "F"); } } ucd-parse-0.1.10/src/extracted/derived_general_category.rs000064400000000000000000000036161046102023000217300ustar 00000000000000use std::path::Path; use std::str::FromStr; use crate::common::{ parse_codepoint_association, CodepointIter, Codepoints, UcdFile, UcdFileByCodepoint, }; use crate::error::Error; /// A single row in the `extracted/DerivedGeneralCategory.txt` file. /// /// This file gives the derived values of the General_Category property. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct DerivedGeneralCategory { /// The codepoint or codepoint range for this entry. pub codepoints: Codepoints, /// The derived General_Category of the codepoints in this entry. pub general_category: String, } impl UcdFile for DerivedGeneralCategory { fn relative_file_path() -> &'static Path { Path::new("extracted/DerivedGeneralCategory.txt") } } impl UcdFileByCodepoint for DerivedGeneralCategory { fn codepoints(&self) -> CodepointIter { self.codepoints.into_iter() } } impl FromStr for DerivedGeneralCategory { type Err = Error; fn from_str(line: &str) -> Result { let (codepoints, general_category) = parse_codepoint_association(line)?; Ok(DerivedGeneralCategory { codepoints, general_category: general_category.to_string(), }) } } #[cfg(test)] mod tests { use super::DerivedGeneralCategory; #[test] fn parse_single() { let line = "04D9 ; Ll # CYRILLIC SMALL LETTER SCHWA\n"; let row: DerivedGeneralCategory = line.parse().unwrap(); assert_eq!(row.codepoints, 0x04D9); assert_eq!(row.general_category, "Ll"); } #[test] fn parse_range() { let line = "0660..0669 ; Nd # [10] ARABIC-INDIC DIGIT ZERO..ARABIC-INDIC DIGIT NINE"; let row: DerivedGeneralCategory = line.parse().unwrap(); assert_eq!(row.codepoints, (0x0660, 0x0669)); assert_eq!(row.general_category, "Nd"); } } ucd-parse-0.1.10/src/extracted/derived_joining_group.rs000064400000000000000000000035121046102023000212620ustar 00000000000000use std::path::Path; use std::str::FromStr; use crate::common::{ parse_codepoint_association, CodepointIter, Codepoints, UcdFile, UcdFileByCodepoint, }; use crate::error::Error; /// A single row in the `extracted/DerivedJoiningGroup.txt` file. /// /// This file gives the derived values of the Joining_Group property. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct DerivedJoiningGroup { /// The codepoint or codepoint range for this entry. pub codepoints: Codepoints, /// The derived Joining_Group of the codepoints in this entry. pub joining_group: String, } impl UcdFile for DerivedJoiningGroup { fn relative_file_path() -> &'static Path { Path::new("extracted/DerivedJoiningGroup.txt") } } impl UcdFileByCodepoint for DerivedJoiningGroup { fn codepoints(&self) -> CodepointIter { self.codepoints.into_iter() } } impl FromStr for DerivedJoiningGroup { type Err = Error; fn from_str(line: &str) -> Result { let (codepoints, joining_group) = parse_codepoint_association(line)?; Ok(DerivedJoiningGroup { codepoints, joining_group: joining_group.to_string(), }) } } #[cfg(test)] mod tests { use super::DerivedJoiningGroup; #[test] fn parse_single() { let line = "0710 ; Alaph # Lo SYRIAC LETTER ALAPH\n"; let row: DerivedJoiningGroup = line.parse().unwrap(); assert_eq!(row.codepoints, 0x0710); assert_eq!(row.joining_group, "Alaph"); } #[test] fn parse_range() { let line = "0633..0634 ; Seen # Lo [2] ARABIC LETTER SEEN..ARABIC LETTER SHEEN\n"; let row: DerivedJoiningGroup = line.parse().unwrap(); assert_eq!(row.codepoints, (0x0633, 0x0634)); assert_eq!(row.joining_group, "Seen"); } } ucd-parse-0.1.10/src/extracted/derived_joining_type.rs000064400000000000000000000034531046102023000211130ustar 00000000000000use std::path::Path; use std::str::FromStr; use crate::common::{ parse_codepoint_association, CodepointIter, Codepoints, UcdFile, UcdFileByCodepoint, }; use crate::error::Error; /// A single row in the `extracted/DerivedJoiningType.txt` file. /// /// This file gives the derived values of the Joining_Type property. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct DerivedJoiningType { /// The codepoint or codepoint range for this entry. pub codepoints: Codepoints, /// The derived Joining_Type of the codepoints in this entry. pub joining_type: String, } impl UcdFile for DerivedJoiningType { fn relative_file_path() -> &'static Path { Path::new("extracted/DerivedJoiningType.txt") } } impl UcdFileByCodepoint for DerivedJoiningType { fn codepoints(&self) -> CodepointIter { self.codepoints.into_iter() } } impl FromStr for DerivedJoiningType { type Err = Error; fn from_str(line: &str) -> Result { let (codepoints, joining_type) = parse_codepoint_association(line)?; Ok(DerivedJoiningType { codepoints, joining_type: joining_type.to_string(), }) } } #[cfg(test)] mod tests { use super::DerivedJoiningType; #[test] fn parse_single() { let line = "0628 ; D # Lo ARABIC LETTER BEH\n"; let row: DerivedJoiningType = line.parse().unwrap(); assert_eq!(row.codepoints, 0x0628); assert_eq!(row.joining_type, "D"); } #[test] fn parse_range() { let line = "1133B..1133C ; T # Mn [2] COMBINING BINDU BELOW..GRANTHA SIGN NUKTA\n"; let row: DerivedJoiningType = line.parse().unwrap(); assert_eq!(row.codepoints, (0x1133B, 0x1133C)); assert_eq!(row.joining_type, "T"); } } ucd-parse-0.1.10/src/extracted/derived_line_break.rs000064400000000000000000000033211046102023000205020ustar 00000000000000use std::path::Path; use std::str::FromStr; use crate::common::{ parse_codepoint_association, CodepointIter, Codepoints, UcdFile, UcdFileByCodepoint, }; use crate::error::Error; /// A single row in the `extracted/DerivedLineBreak.txt` file. /// /// This file gives the derived values of the Line_Break property. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct DerivedLineBreak { /// The codepoint or codepoint range for this entry. pub codepoints: Codepoints, /// The derived Line_Break of the codepoints in this entry. pub line_break: String, } impl UcdFile for DerivedLineBreak { fn relative_file_path() -> &'static Path { Path::new("extracted/DerivedLineBreak.txt") } } impl UcdFileByCodepoint for DerivedLineBreak { fn codepoints(&self) -> CodepointIter { self.codepoints.into_iter() } } impl FromStr for DerivedLineBreak { type Err = Error; fn from_str(line: &str) -> Result { let (codepoints, line_break) = parse_codepoint_association(line)?; Ok(DerivedLineBreak { codepoints, line_break: line_break.to_string() }) } } #[cfg(test)] mod tests { use super::DerivedLineBreak; #[test] fn parse_single() { let line = "0028 ; OP # Ps LEFT PARENTHESIS\n"; let row: DerivedLineBreak = line.parse().unwrap(); assert_eq!(row.codepoints, 0x0028); assert_eq!(row.line_break, "OP"); } #[test] fn parse_range() { let line = "0030..0039 ; NU # Nd [10] DIGIT ZERO..DIGIT NINE\n"; let row: DerivedLineBreak = line.parse().unwrap(); assert_eq!(row.codepoints, (0x0030, 0x0039)); assert_eq!(row.line_break, "NU"); } } ucd-parse-0.1.10/src/extracted/derived_name.rs000064400000000000000000000031621046102023000173320ustar 00000000000000use std::path::Path; use std::str::FromStr; use crate::common::{ parse_codepoint_association, CodepointIter, Codepoints, UcdFile, UcdFileByCodepoint, }; use crate::error::Error; /// A single row in the `extracted/DerivedName.txt` file. /// /// This file gives the derived values of the Name property. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct DerivedName { /// The codepoint or codepoint range for this entry. pub codepoints: Codepoints, /// The derived Name of the codepoints in this entry. pub name: String, } impl UcdFile for DerivedName { fn relative_file_path() -> &'static Path { Path::new("extracted/DerivedName.txt") } } impl UcdFileByCodepoint for DerivedName { fn codepoints(&self) -> CodepointIter { self.codepoints.into_iter() } } impl FromStr for DerivedName { type Err = Error; fn from_str(line: &str) -> Result { let (codepoints, name) = parse_codepoint_association(line)?; Ok(DerivedName { codepoints, name: name.to_string() }) } } #[cfg(test)] mod tests { use super::DerivedName; #[test] fn parse_single() { let line = "0021 ; EXCLAMATION MARK\n"; let row: DerivedName = line.parse().unwrap(); assert_eq!(row.codepoints, 0x0021); assert_eq!(row.name, "EXCLAMATION MARK"); } #[test] fn parse_range() { let line = "3400..4DBF ; CJK UNIFIED IDEOGRAPH-*\n"; let row: DerivedName = line.parse().unwrap(); assert_eq!(row.codepoints, (0x3400, 0x4DBF)); assert_eq!(row.name, "CJK UNIFIED IDEOGRAPH-*"); } } ucd-parse-0.1.10/src/extracted/derived_numeric_type.rs000064400000000000000000000035141046102023000211160ustar 00000000000000use std::path::Path; use std::str::FromStr; use crate::common::{ parse_codepoint_association, CodepointIter, Codepoints, UcdFile, UcdFileByCodepoint, }; use crate::error::Error; /// A single row in the `extracted/DerivedNumericType.txt` file. /// /// This file gives the derived values of the Numeric_Type property. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct DerivedNumericType { /// The codepoint or codepoint range for this entry. pub codepoints: Codepoints, /// The derived Numeric_Type of the codepoints in this entry. pub numeric_type: String, } impl UcdFile for DerivedNumericType { fn relative_file_path() -> &'static Path { Path::new("extracted/DerivedNumericType.txt") } } impl UcdFileByCodepoint for DerivedNumericType { fn codepoints(&self) -> CodepointIter { self.codepoints.into_iter() } } impl FromStr for DerivedNumericType { type Err = Error; fn from_str(line: &str) -> Result { let (codepoints, numeric_type) = parse_codepoint_association(line)?; Ok(DerivedNumericType { codepoints, numeric_type: numeric_type.to_string(), }) } } #[cfg(test)] mod tests { use super::DerivedNumericType; #[test] fn parse_single() { let line = "2189 ; Numeric # No VULGAR FRACTION ZERO THIRDS\n"; let row: DerivedNumericType = line.parse().unwrap(); assert_eq!(row.codepoints, 0x2189); assert_eq!(row.numeric_type, "Numeric"); } #[test] fn parse_range() { let line = "00B2..00B3 ; Digit # No [2] SUPERSCRIPT TWO..SUPERSCRIPT THREE\n"; let row: DerivedNumericType = line.parse().unwrap(); assert_eq!(row.codepoints, (0x00B2, 0x00B3)); assert_eq!(row.numeric_type, "Digit"); } } ucd-parse-0.1.10/src/extracted/derived_numeric_values.rs000064400000000000000000000055271046102023000214420ustar 00000000000000use std::path::Path; use std::str::FromStr; use once_cell::sync::Lazy; use regex::Regex; use crate::common::{CodepointIter, Codepoints, UcdFile, UcdFileByCodepoint}; use crate::error::Error; /// A single row in the `extracted/DerivedNumericValues.txt` file. /// /// This file gives the derived values of the Numeric_Value property. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct DerivedNumericValues { /// The codepoint or codepoint range for this entry. pub codepoints: Codepoints, /// The approximate Numeric_Value of the codepoints in this entry, /// as a decimal. pub numeric_value_decimal: String, /// The exact Numeric_Value of the codepoints in this entry, as /// a fraction. pub numeric_value_fraction: String, } impl UcdFile for DerivedNumericValues { fn relative_file_path() -> &'static Path { Path::new("extracted/DerivedNumericValues.txt") } } impl UcdFileByCodepoint for DerivedNumericValues { fn codepoints(&self) -> CodepointIter { self.codepoints.into_iter() } } impl FromStr for DerivedNumericValues { type Err = Error; fn from_str(line: &str) -> Result { static PARTS: Lazy = Lazy::new(|| { Regex::new( r"(?x) ^ \s*(?P[^\s;]+)\s*; \s*(?P[^\s;]+)\s*; \s*; \s*(?P[^\s;]+)\s* ", ) .unwrap() }); let caps = match PARTS.captures(line.trim()) { Some(caps) => caps, None => return err!("invalid PropList line: '{}'", line), }; let codepoints = caps["codepoints"].parse()?; let numeric_value_decimal = caps["numeric_value_decimal"].to_string(); let numeric_value_fraction = caps["numeric_value_fraction"].to_string(); Ok(DerivedNumericValues { codepoints, numeric_value_decimal, numeric_value_fraction, }) } } #[cfg(test)] mod tests { use super::DerivedNumericValues; #[test] fn parse_single() { let line = "0030 ; 0.0 ; ; 0 # Nd DIGIT ZERO\n"; let row: DerivedNumericValues = line.parse().unwrap(); assert_eq!(row.codepoints, 0x0030); assert_eq!(row.numeric_value_decimal, "0.0"); assert_eq!(row.numeric_value_fraction, "0"); } #[test] fn parse_range() { let line = "11FC9..11FCA ; 0.0625 ; ; 1/16 # No [2] TAMIL FRACTION ONE SIXTEENTH-1..TAMIL FRACTION ONE SIXTEENTH-2\n"; let row: DerivedNumericValues = line.parse().unwrap(); assert_eq!(row.codepoints, (0x11FC9, 0x11FCA)); assert_eq!(row.numeric_value_decimal, "0.0625"); assert_eq!(row.numeric_value_fraction, "1/16"); } } ucd-parse-0.1.10/src/extracted/mod.rs000064400000000000000000000023031046102023000154630ustar 00000000000000//! Structs for parsing files in the `extracted` subdirectory. //! //! These are placed here, rather than at the top level, to help keep //! the number of structs in any given module managable. pub use self::derived_bidi_class::DerivedBidiClass; pub use self::derived_binary_properties::DerivedBinaryProperties; pub use self::derived_combining_class::DerivedCombiningClass; pub use self::derived_decomposition_type::DerivedDecompositionType; pub use self::derived_east_asian_width::DerivedEastAsianWidth; pub use self::derived_general_category::DerivedGeneralCategory; pub use self::derived_joining_group::DerivedJoiningGroup; pub use self::derived_joining_type::DerivedJoiningType; pub use self::derived_line_break::DerivedLineBreak; pub use self::derived_name::DerivedName; pub use self::derived_numeric_type::DerivedNumericType; pub use self::derived_numeric_values::DerivedNumericValues; mod derived_bidi_class; mod derived_binary_properties; mod derived_combining_class; mod derived_decomposition_type; mod derived_east_asian_width; mod derived_general_category; mod derived_joining_group; mod derived_joining_type; mod derived_line_break; mod derived_name; mod derived_numeric_type; mod derived_numeric_values; ucd-parse-0.1.10/src/grapheme_cluster_break.rs000064400000000000000000000064021046102023000174220ustar 00000000000000use std::path::Path; use std::str::FromStr; use crate::common::{ parse_break_test, parse_codepoint_association, CodepointIter, Codepoints, UcdFile, UcdFileByCodepoint, }; use crate::error::Error; /// A single row in the `auxiliary/GraphemeBreakProperty.txt` file. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct GraphemeClusterBreak { /// The codepoint or codepoint range for this entry. pub codepoints: Codepoints, /// The property value assigned to the codepoints in this entry. pub value: String, } impl UcdFile for GraphemeClusterBreak { fn relative_file_path() -> &'static Path { Path::new("auxiliary/GraphemeBreakProperty.txt") } } impl UcdFileByCodepoint for GraphemeClusterBreak { fn codepoints(&self) -> CodepointIter { self.codepoints.into_iter() } } impl FromStr for GraphemeClusterBreak { type Err = Error; fn from_str(line: &str) -> Result { let (codepoints, value) = parse_codepoint_association(line)?; Ok(GraphemeClusterBreak { codepoints, value: value.to_string() }) } } /// A single row in the `auxiliary/GraphemeBreakTest.txt` file. /// /// This file defines tests for the grapheme cluster break algorithm. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct GraphemeClusterBreakTest { /// Each string is a UTF-8 encoded group of codepoints that make up a /// single grapheme cluster. pub grapheme_clusters: Vec, /// A human readable description of this test. pub comment: String, } impl UcdFile for GraphemeClusterBreakTest { fn relative_file_path() -> &'static Path { Path::new("auxiliary/GraphemeBreakTest.txt") } } impl FromStr for GraphemeClusterBreakTest { type Err = Error; fn from_str(line: &str) -> Result { let (groups, comment) = parse_break_test(line)?; Ok(GraphemeClusterBreakTest { grapheme_clusters: groups, comment }) } } #[cfg(test)] mod tests { use super::{GraphemeClusterBreak, GraphemeClusterBreakTest}; #[test] fn parse_single() { let line = "093B ; SpacingMark # Mc DEVANAGARI VOWEL SIGN OOE\n"; let row: GraphemeClusterBreak = line.parse().unwrap(); assert_eq!(row.codepoints, 0x093B); assert_eq!(row.value, "SpacingMark"); } #[test] fn parse_range() { let line = "1F1E6..1F1FF ; Regional_Indicator # So [26] REGIONAL INDICATOR SYMBOL LETTER A..REGIONAL INDICATOR SYMBOL LETTER Z\n"; let row: GraphemeClusterBreak = line.parse().unwrap(); assert_eq!(row.codepoints, (0x1F1E6, 0x1F1FF)); assert_eq!(row.value, "Regional_Indicator"); } #[test] fn parse_test() { let line = "÷ 0061 × 1F3FF ÷ 1F476 × 200D × 1F6D1 ÷ # ÷ [0.2] LATIN SMALL LETTER A (Other) × [9.0] EMOJI MODIFIER FITZPATRICK TYPE-6 (Extend) ÷ [999.0] BABY (ExtPict) × [9.0] ZERO WIDTH JOINER (ZWJ_ExtCccZwj) × [11.0] OCTAGONAL SIGN (ExtPict) ÷ [0.3]\n"; let row: GraphemeClusterBreakTest = line.parse().unwrap(); assert_eq!( row.grapheme_clusters, vec!["\u{0061}\u{1F3FF}", "\u{1F476}\u{200D}\u{1F6D1}",] ); assert!(row.comment.starts_with("÷ [0.2] LATIN SMALL LETTER A")); } } ucd-parse-0.1.10/src/jamo_short_name.rs000064400000000000000000000040311046102023000160660ustar 00000000000000use std::path::Path; use std::str::FromStr; use once_cell::sync::Lazy; use regex::Regex; use crate::common::{Codepoint, CodepointIter, UcdFile, UcdFileByCodepoint}; use crate::error::Error; /// A single row in the `Jamo.txt` file. /// /// The `Jamo.txt` file defines the `Jamo_Short_Name` property. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct JamoShortName { /// The codepoint corresponding to this row. pub codepoint: Codepoint, /// The actual "Jamo Short Name." This string contains at most 3 bytes and /// may be empty. pub name: String, } impl UcdFile for JamoShortName { fn relative_file_path() -> &'static Path { Path::new("Jamo.txt") } } impl UcdFileByCodepoint for JamoShortName { fn codepoints(&self) -> CodepointIter { self.codepoint.into_iter() } } impl FromStr for JamoShortName { type Err = Error; fn from_str(line: &str) -> Result { static PARTS: Lazy = Lazy::new(|| { Regex::new( r"(?x) ^ (?P[A-Z0-9]+); \s* (?P[A-Z]*) ", ) .unwrap() }); let caps = match PARTS.captures(line.trim()) { Some(caps) => caps, None => return err!("invalid Jamo_Short_name line"), }; Ok(JamoShortName { codepoint: caps["codepoint"].parse()?, name: caps.name("name").unwrap().as_str().to_string(), }) } } #[cfg(test)] mod tests { use super::JamoShortName; #[test] fn parse1() { let line = "1164; YAE # HANGUL JUNGSEONG YAE\n"; let row: JamoShortName = line.parse().unwrap(); assert_eq!(row.codepoint, 0x1164); assert_eq!(row.name, "YAE"); } #[test] fn parse2() { let line = "110B; # HANGUL CHOSEONG IEUNG\n"; let row: JamoShortName = line.parse().unwrap(); assert_eq!(row.codepoint, 0x110B); assert_eq!(row.name, ""); } } ucd-parse-0.1.10/src/lib.rs000064400000000000000000000037231046102023000134760ustar 00000000000000/*! A library for parsing the Unicode character database. */ #![deny(missing_docs)] pub use crate::common::{ parse, parse_by_codepoint, parse_many_by_codepoint, ucd_directory_version, Codepoint, CodepointIter, CodepointRange, Codepoints, UcdFile, UcdFileByCodepoint, UcdLineParser, }; pub use crate::error::{Error, ErrorKind}; pub use crate::age::Age; pub use crate::arabic_shaping::ArabicShaping; pub use crate::bidi_mirroring_glyph::BidiMirroring; pub use crate::case_folding::{CaseFold, CaseStatus}; pub use crate::core_properties::CoreProperty; pub use crate::east_asian_width::EastAsianWidth; pub use crate::emoji_properties::EmojiProperty; pub use crate::grapheme_cluster_break::{ GraphemeClusterBreak, GraphemeClusterBreakTest, }; pub use crate::jamo_short_name::JamoShortName; pub use crate::line_break::LineBreakTest; pub use crate::name_aliases::{NameAlias, NameAliasLabel}; pub use crate::prop_list::Property; pub use crate::property_aliases::PropertyAlias; pub use crate::property_value_aliases::PropertyValueAlias; pub use crate::script_extensions::ScriptExtension; pub use crate::scripts::Script; pub use crate::sentence_break::{SentenceBreak, SentenceBreakTest}; pub use crate::special_casing::SpecialCaseMapping; pub use crate::unicode_data::{ UnicodeData, UnicodeDataDecomposition, UnicodeDataDecompositionTag, UnicodeDataExpander, UnicodeDataNumeric, }; pub use crate::word_break::{WordBreak, WordBreakTest}; macro_rules! err { ($($tt:tt)*) => { Err(crate::error::Error::parse(format!($($tt)*))) } } pub mod extracted; mod common; mod error; mod age; mod arabic_shaping; mod bidi_mirroring_glyph; mod case_folding; mod core_properties; mod east_asian_width; mod emoji_properties; mod grapheme_cluster_break; mod jamo_short_name; mod line_break; mod name_aliases; mod prop_list; mod property_aliases; mod property_value_aliases; mod script_extensions; mod scripts; mod sentence_break; mod special_casing; mod unicode_data; mod word_break; ucd-parse-0.1.10/src/line_break.rs000064400000000000000000000027321046102023000150220ustar 00000000000000use std::path::Path; use std::str::FromStr; use crate::common::{parse_break_test, UcdFile}; use crate::error::Error; /// A single row in the `auxiliary/LineBreakTest.txt` file. /// /// This file defines tests for the line break algorithm. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct LineBreakTest { /// Each string is a UTF-8 encoded group of codepoints that make up a /// single line. pub lines: Vec, /// A human readable description of this test. pub comment: String, } impl UcdFile for LineBreakTest { fn relative_file_path() -> &'static Path { Path::new("auxiliary/LineBreakTest.txt") } } impl FromStr for LineBreakTest { type Err = Error; fn from_str(line: &str) -> Result { let (groups, comment) = parse_break_test(line)?; Ok(LineBreakTest { lines: groups, comment }) } } #[cfg(test)] mod tests { use super::LineBreakTest; #[test] fn parse_test() { let line = "× 1F1F7 × 1F1FA ÷ 1F1F8 × 1F1EA ÷ # × [0.3] REGIONAL INDICATOR SYMBOL LETTER R (RI) × [30.11] REGIONAL INDICATOR SYMBOL LETTER U (RI) ÷ [30.13] REGIONAL INDICATOR SYMBOL LETTER S (RI) × [30.11] REGIONAL INDICATOR SYMBOL LETTER E (RI) ÷ [0.3]"; let row: LineBreakTest = line.parse().unwrap(); assert_eq!( row.lines, vec!["\u{1F1F7}\u{1F1FA}", "\u{1F1F8}\u{1F1EA}",] ); assert!(row.comment.ends_with("(RI) ÷ [0.3]")); } } ucd-parse-0.1.10/src/name_aliases.rs000064400000000000000000000102151046102023000153430ustar 00000000000000use std::path::Path; use std::str::FromStr; use once_cell::sync::Lazy; use regex::Regex; use crate::common::{Codepoint, CodepointIter, UcdFile, UcdFileByCodepoint}; use crate::error::Error; /// A single row in the `NameAliases.txt` file. /// /// Note that there are multiple rows for some codepoint. Each row provides a /// new alias. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct NameAlias { /// The codepoint corresponding to this row. pub codepoint: Codepoint, /// The alias. pub alias: String, /// The label of this alias. pub label: NameAliasLabel, } impl UcdFile for NameAlias { fn relative_file_path() -> &'static Path { Path::new("NameAliases.txt") } } impl UcdFileByCodepoint for NameAlias { fn codepoints(&self) -> CodepointIter { self.codepoint.into_iter() } } impl FromStr for NameAlias { type Err = Error; fn from_str(line: &str) -> Result { static PARTS: Lazy = Lazy::new(|| { Regex::new( r"(?x) ^ (?P[A-Z0-9]+); \s* (?P[^;]+); \s* (?P