unicode_names2_generator-2.0.0/.cargo_vcs_info.json0000644000000001470000000000100157760ustar { "git": { "sha1": "765fbf6826b91b6a359981bab53dad28abcdcf87" }, "path_in_vcs": "generator" }unicode_names2_generator-2.0.0/Cargo.toml0000644000000021000000000000100137630ustar # 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" rust-version = "1.63.0" name = "unicode_names2_generator" version = "2.0.0" authors = ["Huon Wilson "] description = """ Generates the perfect-hash function used by `unicode_names2`. """ homepage = "https://github.com/progval/unicode_names2" documentation = "https://docs.rs/unicode_names2/" license = "MIT OR Apache-2.0" repository = "https://github.com/progval/unicode_names2" [dependencies.phf_codegen] version = "0.11.1" [dependencies.rand] version = "0.8.5" [dependencies.time] version = "0.3" optional = true [features] default = [] timing = ["time"] unstable = [] unicode_names2_generator-2.0.0/Cargo.toml.orig000064400000000000000000000011051046102023000174500ustar 00000000000000[package] name = "unicode_names2_generator" edition = "2018" rust-version = "1.63.0" version = "2.0.0" authors = ["Huon Wilson "] homepage = "https://github.com/progval/unicode_names2" repository = "https://github.com/progval/unicode_names2" documentation = "https://docs.rs/unicode_names2/" license = "MIT OR Apache-2.0" description = """ Generates the perfect-hash function used by `unicode_names2`. """ [features] unstable = [] default = [] timing = ["time"] [dependencies] time = { version = "0.3", optional = true } rand = "0.8.5" phf_codegen = "0.11.1" unicode_names2_generator-2.0.0/LICENSE-APACHE000064400000000000000000000251371046102023000165200ustar 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. unicode_names2_generator-2.0.0/LICENSE-MIT000064400000000000000000000020361046102023000162210ustar 00000000000000Copyright (c) 2014 Huon Wilson 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.unicode_names2_generator-2.0.0/src/formatting.rs000064400000000000000000000024541046102023000201000ustar 00000000000000use std::{fmt::Debug, io::prelude::*}; static LINE_LIMIT: usize = 95; pub struct Context { pub out: Box, } impl Context { pub fn write_array(&mut self, name: &str, ty: &str, elements: &[T], format: F) where F: Fn(&T) -> String, { w!(self, "pub static {}: &'static [{}] = &[", name, ty); let mut width = LINE_LIMIT; for e in elements.iter() { let mut text = format(e); text.push(','); if 1 + width + text.len() >= LINE_LIMIT { w!(self, "\n "); width = 4; } else { w!(self, " "); width += 1 } w!(self, "{}", text); width += text.len() } w!(self, "];\n"); } pub fn write_debugs(&mut self, name: &str, ty: &str, elements: &[T]) { self.write_array(name, ty, elements, |x| format!("{:?}", x)) } pub fn write_plain_string(&mut self, name: &str, data: &str) { assert!(!data.contains('\\')); w!(self, "pub static {}: &'static str = \"", name); for chunk in data.as_bytes().chunks(LINE_LIMIT - 6) { w!(self, "\\\n "); self.out.write_all(chunk).unwrap(); } w!(self, "\";\n"); } } unicode_names2_generator-2.0.0/src/lib.rs000064400000000000000000000400161046102023000164700ustar 00000000000000use formatting::Context; use std::{ char, cmp, collections::{hash_map, HashMap}, fs::{self, File}, io::{self, prelude::*, BufWriter}, iter::repeat, path::Path, }; macro_rules! w { ($ctxt: expr, $($tt: tt)*) => { (write!($ctxt.out, $($tt)*)).unwrap() } } mod formatting; mod phf; mod trie; mod util; const SPLITTERS: &[u8] = b"-"; struct TableData { codepoint_names: Vec<(char, &'static str)>, cjk_ideograph_ranges: Vec<(char, char)>, } fn get_table_data(unicode_data: &'static str) -> TableData { fn extract(line: &'static str) -> Option<(char, &'static str)> { let splits: Vec<_> = line.splitn(15, ';').collect(); assert_eq!(splits.len(), 15); let s = splits[0]; let cp = u32::from_str_radix(s, 16) .ok() .unwrap_or_else(|| panic!("invalid {}", line)); let c = char::from_u32(cp)?; let name = splits[1]; Some((c, name)) } let mut iter = unicode_data.lines(); let mut codepoint_names = vec![]; let mut cjk_ideograph_ranges = vec![]; while let Some(l) = iter.next() { if l.is_empty() { break; } let (cp, name) = if let Some(extracted) = extract(l.trim()) { extracted } else { continue; }; if name.starts_with('<') { assert!(name.ends_with('>'), "should >: {}", name); let name = &name[1..name.len() - 1]; if name.starts_with("CJK Ideograph") { assert!(name.ends_with("First")); // should be CJK Ideograph ..., Last let line2 = iter.next().expect("unclosed ideograph range"); let (cp2, name2) = if let Some(extracted) = extract(line2.trim()) { extracted } else { continue; }; assert_eq!(&*name.replace("First", "Last"), &name2[1..name2.len() - 1]); cjk_ideograph_ranges.push((cp, cp2)); } else if name.starts_with("Hangul Syllable") { // the main lib only knows this range, so lets make // sure we're not going out of date wrt the unicode // standard. if name.ends_with("First") { assert_eq!(cp, '\u{AC00}'); } else if name.ends_with("Last") { assert_eq!(cp, '\u{D7A3}'); } else { panic!("unknown hangul syllable {}", name) } } } else { codepoint_names.push((cp, name)) } } TableData { codepoint_names, cjk_ideograph_ranges, } } pub struct Alias { pub code: &'static str, pub alias: &'static str, pub category: &'static str, } pub fn get_aliases(name_aliases: &'static str) -> Vec { let mut aliases = Vec::new(); for line in name_aliases.lines() { if line.is_empty() | line.starts_with('#') { continue; } let mut parts = line.splitn(3, ';'); let code = parts.next().expect(line); let alias = parts.next().expect(code); let category = parts.next().expect(alias); aliases.push(Alias { code, alias, category, }); } aliases } fn write_cjk_ideograph_ranges(ctxt: &mut Context, ranges: &[(char, char)]) { ctxt.write_debugs("CJK_IDEOGRAPH_RANGES", "(char, char)", ranges) } /// Construct a huge string storing the text data, and return it, /// along with information about the position and frequency of the /// constituent words of the input. fn create_lexicon_and_offsets( mut codepoint_names: Vec<(char, &str)>, ) -> (String, Vec<(usize, Vec, usize)>) { codepoint_names.sort_by(|a, b| a.1.len().cmp(&b.1.len()).reverse()); // a trie of all the suffixes of the data, let mut t = trie::Trie::new(); let mut output = String::new(); let mut substring_overlaps = 0; let mut substring_o_bytes = 0; for &(_, name) in codepoint_names.iter() { for n in util::split(name, SPLITTERS) { if n.len() == 1 && SPLITTERS.contains(&n.as_bytes()[0]) { continue; } let (already, previous_was_exact) = t.insert(n.bytes(), None, false); if already { if !previous_was_exact { substring_overlaps += 1; substring_o_bytes += n.len(); } } else { // completely new element, i.e. not a substring of // anything, so record its position & add it. let offset = output.len(); t.set_offset(n.bytes(), offset); output.push_str(n); // insert the suffixes of this word which saves about // 10KB (we could theoretically insert all substrings, // upto a certain length, but this only saves ~300 // bytes or so and is noticeably slower). for i in 1..n.len() { if t.insert(n[i..].bytes(), Some(offset + i), true).0 { // once we've found a string that's already // been inserted, we know all suffixes will've // been inserted too. break; } } } } } let words: Vec<_> = t .iter() .map(|(a, b, c)| (a, b, c.expect("unset offset?"))) .collect(); println!( "Lexicon: # words {}, byte size {}, with {} ({} bytes) non-exact matches", words.len(), output.len(), substring_overlaps, substring_o_bytes ); (output, words) } // creates arrays t1, t2 and a shift such that `dat[i] == t2[t1[i >> // shift] << shift + i & mask]`; this allows us to share blocks of // length `1 << shift`, and so compress an array with a lot of repeats // (like the 0's of the phrasebook_offsets below). fn bin_data(dat: &[u32]) -> (Vec, Vec, usize) { let mut smallest = 0xFFFFFFFF; let mut data = (vec![], vec![], 0); let mut cache = HashMap::new(); // brute force search for the shift that words best. for shift in 0..14 { cache.clear(); let mut t1 = vec![]; let mut t2 = vec![]; for chunk in dat.chunks(1 << shift) { // have we stored this chunk already? let index = *match cache.entry(chunk) { hash_map::Entry::Occupied(o) => o.into_mut(), hash_map::Entry::Vacant(v) => { // no :(, better put it in. let index = t2.len(); t2.extend(chunk.iter().cloned()); v.insert(index) } }; t1.push((index >> shift) as u32) } let my_size = t1.len() * util::smallest_type(t1.iter().copied()) + t2.len() * util::smallest_type(t2.iter().copied()); println!("binning: shift {}, size {}", shift, my_size); if my_size < smallest { data = (t1, t2, shift); smallest = my_size } } // verify. { let (ref t1, ref t2, shift) = data; let mask = (1 << shift) - 1; for (i, &elem) in dat.iter().enumerate() { assert_eq!( elem, t2[((t1[i >> shift] << shift) + (i as u32 & mask)) as usize] ) } } data } fn write_codepoint_maps(ctxt: &mut Context, codepoint_names: Vec<(char, &str)>) { let (lexicon_string, mut lexicon_words) = create_lexicon_and_offsets(codepoint_names.clone()); let num_escapes = (lexicon_words.len() + 255) / 256; // we reserve the high bit (end of word) and 127,126... for // non-space splits. The high bit saves about 10KB, and doing the // extra splits reduces the space required even more (e.g. - is a // reduction of 14KB). let short = 128 - SPLITTERS.len() - num_escapes; // find the `short` most common elements lexicon_words.sort_by(|a, b| a.cmp(b).reverse()); // and then sort the rest into groups of equal length, to allow us // to avoid storing the full length table; just the indices. The // ordering is irrelevant here; just that they are in groups. lexicon_words[short..].sort_by(|(_, a, _), (_, b, _)| a.len().cmp(&b.len())); // the encoding for each word, to avoid having to recompute it // each time, we can just blit it out of here. let mut word_encodings = HashMap::new(); for (i, x) in SPLITTERS.iter().enumerate() { // precomputed word_encodings.insert(vec![*x], vec![128 - 1 - i as u32]); } // the indices into the main string let mut lexicon_offsets = vec![]; // and their lengths, for the most common strings, since these // have no information about their length (they were chosen by // frequency). let mut lexicon_short_lengths = vec![]; let mut iter = lexicon_words.into_iter().enumerate(); for (i, (_, word, offset)) in iter.by_ref().take(short) { lexicon_offsets.push(offset); lexicon_short_lengths.push(word.len()); // encoded as a single byte. assert!(word_encodings.insert(word, vec![i as u32]).is_none()) } // this stores (end point, length) for each block of words of a // given length, where `end point` is one-past-the-end. let mut lexicon_ordered_lengths = vec![]; let mut previous_len = 0xFFFF; for (i, (_, word, offset)) in iter { let (hi, lo) = (short + i / 256, i % 256); assert!(short <= hi && hi < 128 - SPLITTERS.len()); lexicon_offsets.push(offset); let len = word.len(); if len != previous_len { if previous_len != 0xFFFF { lexicon_ordered_lengths.push((i, previous_len)); } previous_len = len; } assert!(word_encodings .insert(word, vec![hi as u32, lo as u32]) .is_none()); } // don't forget the last one. lexicon_ordered_lengths.push((lexicon_offsets.len(), previous_len)); // phrasebook encodes the words out of the lexicon that make each // codepoint name. let mut phrasebook = vec![0u32]; // this is a map from `char` -> the index in phrasebook. it is // currently huge, but it has a lot of 0's, so we compress it // using the binning, below. let mut phrasebook_offsets = repeat(0).take(0x10FFFF + 1).collect::>(); let mut longest_name = String::new(); for &(cp, name) in codepoint_names.iter() { longest_name = cmp::max_by_key(normalise_name(name, cp), longest_name, |s| s.len()); let start = phrasebook.len() as u32; phrasebook_offsets[cp as usize] = start; let mut last_len = 0; for w in util::split(name, SPLITTERS) { let data = word_encodings .get(w.as_bytes()) .expect(concat!("option on ", line!())); last_len = data.len(); // info!("{}: '{}' {}", name, w, data); // blit the data. phrasebook.extend(data.iter().cloned()) } // add the high bit to the first byte of the last encoded // phrase, to indicate the end. let idx = phrasebook.len() - last_len; phrasebook[idx] |= 0b1000_0000; } // compress the offsets, hopefully collapsing all the 0's. let (t1, t2, shift) = bin_data(&phrasebook_offsets); w!( ctxt, "pub const LONGEST_NAME: &str = {longest_name:?};\n\ pub const LONGEST_NAME_LEN: usize = LONGEST_NAME.len();\n" ); ctxt.write_plain_string("LEXICON", &lexicon_string); ctxt.write_debugs("LEXICON_OFFSETS", "u32", &lexicon_offsets); ctxt.write_debugs("LEXICON_SHORT_LENGTHS", "u8", &lexicon_short_lengths); ctxt.write_debugs( "LEXICON_ORDERED_LENGTHS", "(usize, u8)", &lexicon_ordered_lengths, ); w!(ctxt, "pub static PHRASEBOOK_SHORT: u8 = {};\n", short); ctxt.write_debugs("PHRASEBOOK", "u8", &phrasebook); w!( ctxt, "pub static PHRASEBOOK_OFFSET_SHIFT: usize = {};\n", shift ); ctxt.write_debugs( "PHRASEBOOK_OFFSETS1", &util::smallest_u(t1.iter().copied()), &t1, ); ctxt.write_debugs( "PHRASEBOOK_OFFSETS2", &util::smallest_u(t2.iter().copied()), &t2, ); } fn make_context(path: Option<&Path>) -> Context { let mut ctxt = Context { out: match path { Some(p) => Box::new(BufWriter::new( File::create(p.with_extension("tmp")).unwrap(), )) as Box, None => Box::new(io::sink()) as Box, }, }; let _ = ctxt .out .write(b"// autogenerated by generator.rs\n") .unwrap(); ctxt } #[allow(clippy::type_complexity)] fn get_truncated_table_data( unicode_data: &'static str, truncate: Option, ) -> (Vec<(char, &'static str)>, Vec<(char, char)>) { let TableData { mut codepoint_names, cjk_ideograph_ranges: cjk, } = get_table_data(unicode_data); if let Some(n) = truncate { codepoint_names.truncate(n) } (codepoint_names, cjk) } pub fn generate_phf( unicode_data: &'static str, path: Option<&Path>, truncate: Option, lambda: usize, tries: usize, ) { let (codepoint_names, _) = get_truncated_table_data(unicode_data, truncate); let codepoint_names: Vec<_> = codepoint_names .into_iter() .map(|(c, s)| (c, normalise_name(s, c))) .collect(); let mut ctxt = make_context(path); let (n, disps, data) = phf::create_phf(&codepoint_names, lambda, tries); w!(ctxt, "pub static NAME2CODE_N: u64 = {};\n", n); ctxt.write_debugs("NAME2CODE_DISP", "(u16, u16)", &disps); ctxt.write_debugs("NAME2CODE_CODE", "char", &data); if let Some(path) = path { fs::rename(path.with_extension("tmp"), path).unwrap() } } /// Convert a Unicode name to a form that can be used for loose matching, as per /// [UAX#44](https://www.unicode.org/reports/tr44/tr44-34.html#Matching_Names) /// /// This function matches `unicode_names2::normalise_name` in implementation, thus the result of one /// can be used to query a PHF generated from the other. fn normalise_name(s: &str, codepoint: char) -> String { let mut normalised = String::new(); let bytes = s.as_bytes(); for (i, c) in bytes.iter().map(u8::to_ascii_uppercase).enumerate() { // "Ignore case, whitespace, underscore ('_'), [...]" if c.is_ascii_whitespace() || c == b'_' { continue; } // "[...] and all medial hyphens except the hyphen in U+1180 HANGUL JUNGSEONG O-E." if codepoint != '\u{1180}' // HANGUL JUNGSEONG O-E && c == b'-' && bytes.get(i - 1).map_or(false, u8::is_ascii_alphanumeric) && bytes.get(i + 1).map_or(false, u8::is_ascii_alphanumeric) { continue; } assert!( c.is_ascii_alphanumeric() || c == b'-', "U+{:04X} contains an invalid character for a Unicode name: {:?}", codepoint as u32, s ); normalised.push(c as char); } normalised } pub fn generate(unicode_data: &'static str, path: Option<&Path>, truncate: Option) { let (codepoint_names, cjk) = get_truncated_table_data(unicode_data, truncate); let mut ctxt = make_context(path); write_cjk_ideograph_ranges(&mut ctxt, &cjk); let _ = ctxt.out.write(b"\n").unwrap(); write_codepoint_maps(&mut ctxt, codepoint_names); if let Some(path) = path { fs::rename(path.with_extension("tmp"), path).unwrap() } } pub fn generate_aliases(name_aliases: &'static str, path: &Path) { let mut aliases = phf_codegen::Map::new(); for Alias { code, alias, .. } in get_aliases(name_aliases).into_iter() { let formatted = format!("'\\u{{{code}}}'"); aliases.entry(alias, &formatted); } let aliases = aliases.build().to_string().replace("(\"", "(b\""); writeln!(BufWriter::new(File::create(path).unwrap()), "{aliases}",).unwrap(); } unicode_names2_generator-2.0.0/src/phf.rs000064400000000000000000000135551046102023000165070ustar 00000000000000//! Computes a perfect hash table using [the CHD //! algorithm](http://cmph.sourceforge.net/papers/esa09.pdf). //! //! Strongly inspired by https://github.com/sfackler/rust-phf use rand::prelude::{Rng, SeedableRng, SliceRandom, StdRng}; use std::iter::repeat; static NOVAL: char = '\0'; /// FNV fn hash(s: &str, h: u64) -> u64 { let mut g = 0xcbf29ce484222325 ^ h; for b in s.bytes() { g ^= b as u64; g = g.wrapping_mul(0x100000001b3); } g } pub fn displace(f1: u32, f2: u32, d1: u32, d2: u32) -> u32 { d2.wrapping_add(f1.wrapping_mul(d1)).wrapping_add(f2) } fn split(hash: u64) -> Hash { let bits = 21; let mask = (1 << bits) - 1; Hash { g: (hash & mask) as u32, f1: ((hash >> bits) & mask) as u32, f2: ((hash >> (2 * bits)) & mask) as u32, } } #[derive(Copy, Clone)] struct Hash { g: u32, f1: u32, f2: u32, } #[allow(clippy::type_complexity)] fn try_phf_table( values: &[(char, String)], lambda: usize, seed: u64, rng: &mut StdRng, ) -> Option<(Vec<(u32, u32)>, Vec)> { let hashes: Vec<_> = values .iter() .map(|(n, s)| (split(hash(s, seed)), *n)) .collect(); let table_len = hashes.len(); let buckets_len = (table_len + lambda - 1) / lambda; // group the elements into buckets of lambda (on average, for a // good hash) based on the suffix of their hash. let mut buckets = (0..buckets_len).map(|i| (i, vec![])).collect::>(); for &(h, cp) in hashes.iter() { buckets[h.g as usize % buckets_len].1.push((h, cp)) } // place the large buckets first. buckets.sort_by(|(_, a), (_, b)| b.len().cmp(&a.len())); // this stores the final computed backing vector, i.e. getting the // value for `foo` is "just" `map[displace(hash(foo))]`, where // `displace` uses the pair of displacements that we computed // (stored in `disps`). let mut map = repeat(NOVAL).take(table_len).collect::>(); let mut disps = repeat((0, 0)).take(buckets_len).collect::>(); // the set of index -> value mappings for the next bucket to be // placed; we need it separate because it may not work, so we may // have to roll back. // // it works by storing a map from index -> generation, so we can // check if the index is taken by a previously-placed element of // the current bucket cheaply (just an array lookup) without // having to clear the whole the whole array each time (just // compare against the generation). A u64 won't overflow. let mut generation = 0; let mut try_map = repeat(0u64).take(table_len).collect::>(); // the placed (index, codepoint) pairs of the current bucket, to // be placed into the main map if the whole bucket fits. let mut values_to_add = vec![]; // heuristically avoiding doing everything in the same order seems // good? I dunno; but anyway, we get vectors of indices and // shuffle them. let mut d1s = (0..(table_len as u32)).collect::>(); let mut d2s = d1s.clone(); d1s.shuffle(rng); d2s.shuffle(rng); // run through each bucket and try to fit the elements into the // array by choosing appropriate adjusting factors // ("displacements") that allow the other two parts of the hash to // be combined into an empty index. 'next_bucket: for &(bkt_idx, ref bkt_keys) in buckets.iter() { // exhaustively search for a pair of displacements that work. for &d1 in d1s.iter() { 'next_disp: for &d2 in d2s.iter() { generation += 1; values_to_add.clear(); // run through the elements to see if they all fit for &(h, cp) in bkt_keys.iter() { // adjust the index slightly using the // displacements, hoping that this will allow us // to avoid collisions. let idx = (displace(h.f1, h.f2, d1, d2) % table_len as u32) as usize; if map[idx] != NOVAL || try_map[idx] == generation { // nope, this one is taken, so this pair of // displacements doesn't work. continue 'next_disp; } try_map[idx] = generation; values_to_add.push((idx, cp)); } // everything works! let's lock it in and go to the // next bucket. disps[bkt_idx] = (d1, d2); for &(idx, cp) in values_to_add.iter() { map[idx] = cp } continue 'next_bucket; } } // if we're here, we ran through all displacements for a // bucket and didn't find one that worked, so we can't make // the hash table. return None; } Some((disps, map)) } pub fn create_phf( data: &[(char, String)], lambda: usize, max_tries: usize, ) -> (u64, Vec<(u32, u32)>, Vec) { let mut rng = StdRng::seed_from_u64(0xf0f0f0f0); #[cfg(feature = "timing")] let start = time::Instant::now(); for i in 0..(max_tries) { #[cfg(feature = "timing")] let my_start = time::Instant::now(); #[cfg(feature = "timing")] println!("PHF #{}: starting {:.2}", i, my_start - start); #[cfg(not(feature = "timing"))] println!("PHF #{}", i); let seed = rng.gen(); if let Some((disp, map)) = try_phf_table(data, lambda, seed, &mut rng) { #[cfg(feature = "timing")] println!( "PHF took: total {:.2} s, successive {:.2} s", start.elapsed(), my_start.elapsed() ); return (seed, disp, map); } } panic!( "could not create a length {} PHF with {}, {}", data.len(), lambda, max_tries ); } unicode_names2_generator-2.0.0/src/trie.rs000064400000000000000000000055451046102023000166750ustar 00000000000000use std::collections::hash_map::{self, Entry, HashMap}; pub struct Trie { children: HashMap, count: usize, offset: Option, } impl Trie { pub fn new() -> Trie { Trie { children: HashMap::new(), count: 0, offset: None, } } pub fn get_child(&mut self, b: u8) -> &mut Trie { match self.children.entry(b) { Entry::Occupied(o) => o.into_mut(), Entry::Vacant(v) => v.insert(Trie::new()), } } pub fn set_offset>(&mut self, mut it: I, offset: usize) { if self.offset.is_none() { self.offset = Some(offset) } match it.next() { None => {} Some(b) => self.get_child(b).set_offset(it, offset), } } /// insert the value given by the sequence `it`, returning a tuple /// (is this a substring already in the tree, was this exact /// sequence previously inserted). pub fn insert>( &mut self, mut it: I, offset: Option, weak: bool, ) -> (bool, bool) { let ret = match it.next() { None => { let old_count = self.count; if !weak { self.count += 1 } (self.offset.is_some(), old_count > 0) } Some(b) => self.get_child(b).insert(it, offset, weak), }; if self.offset.is_none() { self.offset = offset } ret } pub fn iter(&self) -> Items { Items { parents: vec![], current: Some(self), stack: vec![], } } } pub struct Items<'a> { parents: Vec, current: Option<&'a Trie>, stack: Vec>, } impl<'a> Iterator for Items<'a> { type Item = (usize, Vec, Option); fn next(&mut self) -> Option<(usize, Vec, Option)> { 'outer: loop { if let Some(t) = self.current { self.current = None; self.stack.push(t.children.iter()); if t.count > 0 { return Some((t.count, self.parents.clone(), t.offset)); } } loop { match self.stack.pop() { None => return None, Some(mut it) => match it.next() { Some((&b, t)) => { self.parents.push(b); self.current = Some(t); self.stack.push(it); continue 'outer; } None => { self.parents.pop(); } }, } } } } } unicode_names2_generator-2.0.0/src/util.rs000064400000000000000000000037641046102023000167100ustar 00000000000000/// Figure out whether we need `u8` (1 byte), `u16` (2 bytes) or `u32` (4 bytes) to store all /// numbers. Returns the number of bytes pub fn smallest_type>(x: I) -> usize { let n = x.max().unwrap_or(0); for (max, bytes) in [(u8::MAX as u32, 1), (u16::MAX as u32, 2)] { if n <= max { return bytes; } } 4 } pub fn smallest_u>(x: I) -> String { format!("u{}", 8 * smallest_type(x)) } pub fn split<'a, 'b>(s: &'a str, splitters: &'b [u8]) -> Split<'a, 'b> { Split { s, splitters, pending: "", done: false, } } pub struct Split<'a, 'b> { s: &'a str, splitters: &'b [u8], pending: &'a str, done: bool, } impl<'a, 'b> Iterator for Split<'a, 'b> { type Item = &'a str; fn next(&mut self) -> Option<&'a str> { if self.done { return None; } if self.s.is_empty() { self.done = true; return Some(""); } if !self.pending.is_empty() { return Some(std::mem::take(&mut self.pending)); } for (i, b) in self.s.bytes().enumerate() { if b == b' ' || self.splitters.contains(&b) { let ret = &self.s[..i]; // dont include the space, but include everything else on the next step if b != b' ' { self.pending = &self.s[i..i + 1] } self.s = &self.s[i + 1..]; return Some(ret); } } // trailing data self.done = true; Some(self.s) } } #[test] fn test_split() { let tests: &[(&str, &[&str])] = &[ ("a", &["a"]), ("a b", &["a", "b"]), (" a b ", &["", "a", "b", ""]), ("a-b", &["a", "-", "b"]), ("a- b", &["a", "-", "", "b"]), ("a -b", &["a", "", "-", "b"]), ]; for &(s, v) in tests.iter() { assert_eq!(split(s, b"-").collect::>(), v) } }