ucd-parse-0.1.4/Cargo.toml.orig010064400017500000144000000007751351474547500145330ustar0000000000000000[package] name = "ucd-parse" version = "0.1.4" #: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/Apache-2.0" [dependencies] lazy_static = "1" regex = "1" ucd-parse-0.1.4/Cargo.toml0000644000000020310000000000000107520ustar00# 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 believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "ucd-parse" version = "0.1.4" authors = ["Andrew Gallant "] description = "A library for parsing data files in the Unicode character database.\n" homepage = "https://github.com/BurntSushi/ucd-generate" documentation = "https://docs.rs/ucd-parse" readme = "README.md" keywords = ["unicode", "database", "character", "property"] license = "MIT/Apache-2.0" repository = "https://github.com/BurntSushi/ucd-generate" [dependencies.lazy_static] version = "1" [dependencies.regex] version = "1" ucd-parse-0.1.4/Cargo.toml.orig0000644000000020320000000000000117120ustar00# 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 believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "ucd-parse" version = "0.1.4" authors = ["Andrew Gallant "] description = "A library for parsing data files in the Unicode character database.\n" homepage = "https://github.com/BurntSushi/ucd-generate" documentation = "https://docs.rs/ucd-parse" readme = "README.md" keywords = ["unicode", "database", "character", "property"] license = "MIT/Apache-2.0" repository = "https://github.com/BurntSushi/ucd-generate" [dependencies.lazy_static] version = "1" [dependencies.regex] version = "1" ucd-parse-0.1.4/LICENSE-APACHE010064400017500000144000000251371324750327300135560ustar0000000000000000 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.4/LICENSE-MIT010064400017500000144000000020711324737324300132600ustar0000000000000000The 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.4/README.md010066400017500000144000000011761324750314000131010ustar0000000000000000ucd-parse ========= A library for parsing Unicode Character Database (UCD) files into structured data. [![Linux build status](https://api.travis-ci.org/BurntSushi/ucd-generate.png)](https://travis-ci.org/BurntSushi/ucd-generate) [![](http://meritbadge.herokuapp.com/ucd-generate)](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 http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ucd-parse-0.1.4/src/age.rs010066400017500000144000000030161322551650000135060ustar0000000000000000 use std::path::Path; use std::str::FromStr; use common::{ UcdFile, UcdFileByCodepoint, Codepoints, CodepointIter, parse_codepoint_association, }; use 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: 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.4/src/case_folding.rs010066400017500000144000000112261320431740200153660ustar0000000000000000use std::path::Path; use std::str::FromStr; use regex::Regex; use common::{UcdFile, UcdFileByCodepoint, Codepoint, CodepointIter}; use 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 { lazy_static! { static ref PARTS: Regex = 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: 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.4/src/common.rs010064400017500000144000000347021351473746600142670ustar0000000000000000use 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 regex::Regex; use 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) } /// 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> { lazy_static! { static ref PARTS: Regex = 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> { lazy_static! { static ref PARTS: Regex = Regex::new( r"(?x) ^ (?:÷|×) (?P(?:\s[0-9A-Fa-f]{4,5}\s(?:÷|×))+) \s+ \#(?P.+) $ " ).unwrap(); static ref GROUP: Regex = 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: 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 { lazy_static! { static ref PARTS: Regex = 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: start, end: 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: 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.4/src/core_properties.rs010066400017500000144000000032551321010026700161540ustar0000000000000000use std::path::Path; use std::str::FromStr; use common::{ UcdFile, UcdFileByCodepoint, Codepoints, CodepointIter, parse_codepoint_association, }; use 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: 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.4/src/emoji_properties.rs010064400017500000144000000037641337513255600163540ustar0000000000000000use std::path::Path; use std::str::FromStr; use common::{ UcdFile, UcdFileByCodepoint, Codepoints, CodepointIter, parse_codepoint_association, }; use 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-data.txt") } } 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: 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.4/src/error.rs010064400017500000144000000046711351474407500141240ustar0000000000000000use std::error; use std::fmt; use std::io; use std::path::{Path, PathBuf}; /// Create a new parse error from the given message. pub fn error_parse(msg: String) -> Error { Error { kind: ErrorKind::Parse(msg), line: None, path: None } } /// 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 { /// 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 description(&self) -> &str { match self.kind { ErrorKind::Io(ref err) => err.description(), ErrorKind::Parse(ref msg) => msg, } } 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.4/src/grapheme_cluster_break.rs010064400017500000144000000065131340134111100174400ustar0000000000000000use std::path::Path; use std::str::FromStr; use common::{ UcdFile, UcdFileByCodepoint, Codepoints, CodepointIter, parse_break_test, parse_codepoint_association, }; use 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: 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: 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.4/src/jamo_short_name.rs010064400017500000144000000037401320432024700161170ustar0000000000000000use std::path::Path; use std::str::FromStr; use regex::Regex; use common::{UcdFile, UcdFileByCodepoint, Codepoint, CodepointIter}; use 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 { lazy_static! { static ref PARTS: Regex = 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.4/src/lib.rs010064400017500000144000000032061340134111100135050ustar0000000000000000/*! A library for parsing the Unicode character database. */ #![deny(missing_docs)] #[macro_use] extern crate lazy_static; extern crate regex; pub use common::{ UcdFile, UcdFileByCodepoint, UcdLineParser, Codepoint, CodepointRange, Codepoints, CodepointIter, parse, parse_by_codepoint, parse_many_by_codepoint, }; pub use error::{Error, ErrorKind}; pub use age::Age; pub use case_folding::{CaseFold, CaseStatus}; pub use core_properties::CoreProperty; pub use emoji_properties::EmojiProperty; pub use grapheme_cluster_break::{ GraphemeClusterBreak, GraphemeClusterBreakTest, }; pub use jamo_short_name::JamoShortName; pub use line_break::LineBreakTest; pub use name_aliases::{NameAlias, NameAliasLabel}; pub use prop_list::Property; pub use property_aliases::PropertyAlias; pub use property_value_aliases::PropertyValueAlias; pub use script_extensions::ScriptExtension; pub use scripts::Script; pub use sentence_break::{SentenceBreak, SentenceBreakTest}; pub use special_casing::SpecialCaseMapping; pub use unicode_data::{ UnicodeData, UnicodeDataNumeric, UnicodeDataDecomposition, UnicodeDataDecompositionTag, UnicodeDataExpander, }; pub use word_break::{WordBreak, WordBreakTest}; macro_rules! err { ($($tt:tt)*) => { Err(::error::error_parse(format!($($tt)*))) } } mod common; mod error; mod age; mod case_folding; mod core_properties; 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.4/src/line_break.rs010064400017500000144000000027661340134111100150440ustar0000000000000000use std::path::Path; use std::str::FromStr; use common::{UcdFile, parse_break_test}; use 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: 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.4/src/name_aliases.rs010064400017500000144000000101241320432032700153640ustar0000000000000000use std::path::Path; use std::str::FromStr; use regex::Regex; use common::{UcdFile, UcdFileByCodepoint, Codepoint, CodepointIter}; use 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 { lazy_static! { static ref PARTS: Regex = Regex::new( r"(?x) ^ (?P[A-Z0-9]+); \s* (?P[^;]+); \s* (?P