Skip to main content

unicode_names2/
lib.rs

1//! Convert between characters and their standard names.
2//!
3//! This crate provides two functions for mapping from a `char` to the
4//! name given by the Unicode standard (17.0). There are no runtime
5//! requirements so this is usable with only `core` (this requires
6//! specifying the `no_std` cargo feature). The tables are heavily
7//! compressed, but still large (500KB), and still offer efficient
8//! `O(1)` look-ups in both directions (more precisely, `O(length of
9//! name)`).
10//!
11//! ```rust
12//!     println!("☃ is called {:?}", unicode_names2::name('☃')); // SNOWMAN
13//!     println!("{:?} is happy", unicode_names2::character("white smiling face")); // ☺
14//!     // (NB. case insensitivity)
15//! ```
16//!
17//! [**Source**](https://github.com/ProgVal/unicode_names2).
18//!
19//! # Macros
20//!
21//! The associated `unicode_names2_macros` crate provides two macros
22//! for converting at compile-time, giving named literals similar to
23//! Python's `"\N{...}"`.
24//!
25//! - `named_char!(name)` takes a single string `name` and creates a
26//!   `char` literal.
27//! - `named!(string)` takes a string and replaces any `\\N{name}`
28//!   sequences with the character with that name. NB. String escape
29//!   sequences cannot be customised, so the extra backslash (or a raw
30//!   string) is required, unless you use a raw string.
31//!
32//! ```rust
33//! #![feature(proc_macro_hygiene)]
34//!
35//! #[macro_use]
36//! extern crate unicode_names2_macros;
37//!
38//! fn main() {
39//!     let x: char = named_char!("snowman");
40//!     assert_eq!(x, '☃');
41//!
42//!     let y: &str = named!("foo bar \\N{BLACK STAR} baz qux");
43//!     assert_eq!(y, "foo bar ★ baz qux");
44//!
45//!     let y: &str = named!(r"foo bar \N{BLACK STAR} baz qux");
46//!     assert_eq!(y, "foo bar ★ baz qux");
47//! }
48//! ```
49//!
50//! # Loose Matching
51//! For name->char retrieval (the `character` function and macros) this crate uses loose matching,
52//! as defined in Unicode Standard Annex #44[^1].
53//! In general, this means case, whitespace and underscore characters are ignored, as well as
54//! _medial hyphens_, which are hyphens (`-`) that come between two alphanumeric characters[^1].
55//!
56//! Under this scheme, the query `Low_Line` will find `U+005F LOW LINE`, as well as `l o w L-I-N-E`,
57//! `lowline`, and `low\nL-I-N-E`, but not `low- line`.
58//! Similarly, `tibetan letter -a` will find `U+0F60 TIBETAN LETTER -A`, as well as
59//! `tibetanletter - a` and `TIBETAN L_ETTE_R-  __a__`, but not `tibetan letter-a` or
60//! `TIBETAN LETTER A`.
61//!
62//! In the implementation of this crate, 'whitespace' is determined by the [`is_ascii_whitespace`]
63//! method on `u8` and `char`. See its documentation for more info.
64//!
65//! [^1]: See [UAX44-LM2] for precise details.
66//!
67//! [UAX44-LM2]: https://www.unicode.org/reports/tr44/tr44-34.html#UAX44-LM2
68//! [`is_ascii_whitespace`]: char::is_ascii_whitespace
69
70#![cfg_attr(feature = "no_std", no_std)]
71#![cfg_attr(test, feature(test))]
72#![deny(missing_docs, unsafe_code)]
73
74#[cfg(all(test, feature = "no_std"))]
75#[macro_use]
76extern crate std;
77
78use core::{char, fmt};
79use generated::{
80    LONGEST_NAME_LEN, PHRASEBOOK_OFFSETS1, PHRASEBOOK_OFFSETS2, PHRASEBOOK_OFFSET_SHIFT,
81};
82
83#[allow(dead_code)]
84#[rustfmt::skip]
85#[allow(clippy::all)]
86mod generated {
87    include!(concat!(env!("OUT_DIR"), "/generated.rs"));
88}
89#[allow(dead_code)]
90#[rustfmt::skip]
91#[allow(clippy::all)]
92mod generated_phf {
93    include!(concat!(env!("OUT_DIR"), "/generated_phf.rs"));
94}
95#[allow(dead_code)]
96mod jamo;
97
98/// A map of unicode aliases to their corresponding values.
99/// Generated in generator
100#[allow(dead_code)]
101static ALIASES: phf::Map<&'static [u8], char> =
102    include!(concat!(env!("OUT_DIR"), "/generated_alias.rs"));
103
104mod iter_str;
105
106static HANGUL_SYLLABLE_PREFIX: &str = "HANGUL SYLLABLE ";
107static NORMALISED_HANGUL_SYLLABLE_PREFIX: &str = "HANGULSYLLABLE";
108static CJK_UNIFIED_IDEOGRAPH_PREFIX: &str = "CJK UNIFIED IDEOGRAPH-";
109static NORMALISED_CJK_UNIFIED_IDEOGRAPH_PREFIX: &str = "CJKUNIFIEDIDEOGRAPH";
110
111fn is_cjk_unified_ideograph(ch: char) -> bool {
112    generated::CJK_IDEOGRAPH_RANGES
113        .iter()
114        .any(|&(lo, hi)| lo <= ch && ch <= hi)
115}
116
117/// An iterator over the components of a code point's name. Notably implements `Display`.
118///
119/// To reconstruct the full Unicode name from this iterator, you can concatenate every string slice
120/// yielded from it. Each such slice is either a word matching `[A-Z0-9]*`, a space `" "`, or a
121/// hyphen `"-"`. (In particular, words can be the empty string `""`).
122///
123/// The [size hint] returns an exact size, by cloning the iterator and iterating it fully.
124/// Cloning and iteration are cheap, and all names are relatively short, so this should not have a
125/// high impact.
126///
127/// [size hint]: std::iter::Iterator::size_hint
128#[derive(Clone)]
129pub struct Name {
130    data: Name_,
131}
132#[allow(clippy::upper_case_acronyms)]
133#[derive(Clone)]
134enum Name_ {
135    Plain(iter_str::IterStr),
136    CJK(CJK),
137    Hangul(Hangul),
138}
139
140#[allow(clippy::upper_case_acronyms)]
141#[derive(Copy)]
142struct CJK {
143    emit_prefix: bool,
144    idx: u8,
145    // the longest character is 0x10FFFF
146    data: [u8; 6],
147}
148#[derive(Copy)]
149struct Hangul {
150    emit_prefix: bool,
151    idx: u8,
152    // stores the choseong, jungseong, jongseong syllable numbers (in
153    // that order)
154    data: [u8; 3],
155}
156impl Clone for CJK {
157    fn clone(&self) -> CJK {
158        *self
159    }
160}
161impl Clone for Hangul {
162    fn clone(&self) -> Hangul {
163        *self
164    }
165}
166
167#[allow(clippy::len_without_is_empty)]
168impl Name {
169    /// The number of bytes in the name.
170    ///
171    /// All names are plain ASCII, so this is also the number of
172    /// Unicode codepoints and the number of graphemes.
173    pub fn len(&self) -> usize {
174        let counted = self.clone();
175        counted.fold(0, |a, s| a + s.len())
176    }
177}
178
179impl Iterator for Name {
180    type Item = &'static str;
181
182    fn next(&mut self) -> Option<&'static str> {
183        match self.data {
184            Name_::Plain(ref mut s) => s.next(),
185            Name_::CJK(ref mut state) => {
186                // we're a CJK unified ideograph
187                if state.emit_prefix {
188                    state.emit_prefix = false;
189                    return Some(CJK_UNIFIED_IDEOGRAPH_PREFIX);
190                }
191                // run until we've run out of array: the construction
192                // of the data means this is exactly when we have
193                // finished emitting the number.
194                state
195                    .data
196                    .get(state.idx as usize)
197                    // (avoid conflicting mutable borrow problems)
198                    .map(|digit| *digit as usize)
199                    .map(|d| {
200                        state.idx += 1;
201                        static DIGITS: &str = "0123456789ABCDEF";
202                        &DIGITS[d..d + 1]
203                    })
204            }
205            Name_::Hangul(ref mut state) => {
206                if state.emit_prefix {
207                    state.emit_prefix = false;
208                    return Some(HANGUL_SYLLABLE_PREFIX);
209                }
210
211                let idx = state.idx as usize;
212                state.data.get(idx).map(|x| *x as usize).map(|x| {
213                    // progressively walk through the syllables
214                    state.idx += 1;
215                    [jamo::CHOSEONG, jamo::JUNGSEONG, jamo::JONGSEONG][idx][x]
216                })
217            }
218        }
219    }
220
221    fn size_hint(&self) -> (usize, Option<usize>) {
222        // we can estimate exactly by just iterating and summing up.
223        let counted = self.clone();
224        let n = counted.count();
225        (n, Some(n))
226    }
227}
228
229impl fmt::Debug for Name {
230    fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result {
231        fmt::Display::fmt(self, fmtr)
232    }
233}
234impl fmt::Display for Name {
235    fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result {
236        self.clone().try_for_each(|s| fmtr.write_str(s))
237    }
238}
239
240/// Find the name of `c`, or `None` if `c` has no name.
241///
242/// The return value is an iterator that yields `&'static str` components of the name successively
243/// (including spaces and hyphens). It implements `Display`, so can be used naturally to build
244/// `String`s or be printed. See also the [type-level docs][Name].
245///
246/// # Example
247///
248/// ```rust
249/// assert_eq!(unicode_names2::name('a').unwrap().to_string(), "LATIN SMALL LETTER A");
250/// assert_eq!(unicode_names2::name('\u{2605}').unwrap().to_string(), "BLACK STAR");
251/// assert_eq!(unicode_names2::name('☃').unwrap().to_string(), "SNOWMAN");
252///
253/// // control code
254/// assert!(unicode_names2::name('\x00').is_none());
255/// // unassigned
256/// assert!(unicode_names2::name('\u{10FFFF}').is_none());
257/// ```
258pub fn name(c: char) -> Option<Name> {
259    let cc = c as usize;
260    let offset =
261        (PHRASEBOOK_OFFSETS1[cc >> PHRASEBOOK_OFFSET_SHIFT] as usize) << PHRASEBOOK_OFFSET_SHIFT;
262
263    let mask = (1 << PHRASEBOOK_OFFSET_SHIFT) - 1;
264    let offset = PHRASEBOOK_OFFSETS2[offset + (cc & mask)];
265    if offset == 0 {
266        if is_cjk_unified_ideograph(c) {
267            // write the hex number out right aligned in this array.
268            let mut data = [b'0'; 6];
269            let mut number = c as u32;
270            let mut data_start = 6;
271            for place in data.iter_mut().rev() {
272                // this would be incorrect if U+0000 was CJK unified
273                // ideograph, but it's not, so it's fine.
274                if number == 0 {
275                    break;
276                }
277                *place = (number % 16) as u8;
278                number /= 16;
279                data_start -= 1;
280            }
281            Some(Name {
282                data: Name_::CJK(CJK {
283                    emit_prefix: true,
284                    idx: data_start,
285                    data,
286                }),
287            })
288        } else {
289            // maybe it is a hangul syllable?
290            jamo::syllable_decomposition(c).map(|(ch, ju, jo)| Name {
291                data: Name_::Hangul(Hangul {
292                    emit_prefix: true,
293                    idx: 0,
294                    data: [ch, ju, jo],
295                }),
296            })
297        }
298    } else {
299        Some(Name {
300            data: Name_::Plain(iter_str::IterStr::new(offset)),
301        })
302    }
303}
304
305fn fnv_hash<I: Iterator<Item = u8>>(x: I) -> u64 {
306    let mut g = 0xcbf29ce484222325 ^ generated_phf::NAME2CODE_N;
307    for b in x {
308        g ^= b as u64;
309        g = g.wrapping_mul(0x100000001b3);
310    }
311    g
312}
313fn displace(f1: u32, f2: u32, d1: u32, d2: u32) -> u32 {
314    d2.wrapping_add(f1.wrapping_mul(d1)).wrapping_add(f2)
315}
316fn split(hash: u64) -> (u32, u32, u32) {
317    let bits = 21;
318    let mask = (1 << bits) - 1;
319    (
320        (hash & mask) as u32,
321        ((hash >> bits) & mask) as u32,
322        ((hash >> (2 * bits)) & mask) as u32,
323    )
324}
325
326/// Get alias value from alias name, returns `None` if the alias is not found.
327fn character_by_alias(name: &[u8]) -> Option<char> {
328    ALIASES.get(name).copied()
329}
330
331/// Find the character called `name`, or `None` if no such character
332/// exists.
333///
334/// This function uses the [UAX44-LM2] loose matching scheme for lookup. For more information, see
335/// the [crate-level docs][self].
336///
337/// [UAX44-LM2]: https://www.unicode.org/reports/tr44/tr44-34.html#UAX44-LM2
338///
339/// # Example
340///
341/// ```rust
342/// assert_eq!(unicode_names2::character("LATIN SMALL LETTER A"), Some('a'));
343/// assert_eq!(unicode_names2::character("latinsmalllettera"), Some('a'));
344/// assert_eq!(unicode_names2::character("Black_Star"), Some('★'));
345/// assert_eq!(unicode_names2::character("SNOWMAN"), Some('☃'));
346/// assert_eq!(unicode_names2::character("BACKSPACE"), Some('\x08'));
347///
348/// assert_eq!(unicode_names2::character("nonsense"), None);
349/// ```
350pub fn character(search_name: &str) -> Option<char> {
351    let original_name = search_name;
352    let mut buf = [0; LONGEST_NAME_LEN];
353    let len = normalise_name(search_name, &mut buf);
354    let search_name = &buf[..len];
355
356    // try `HANGUL SYLLABLE <choseong><jungseong><jongseong>`
357    if search_name.starts_with(NORMALISED_HANGUL_SYLLABLE_PREFIX.as_bytes()) {
358        let remaining = &search_name[NORMALISED_HANGUL_SYLLABLE_PREFIX.len()..];
359        let (choseong, remaining) = jamo::slice_shift_choseong(remaining);
360        let (jungseong, remaining) = jamo::slice_shift_jungseong(remaining);
361        let (jongseong, remaining) = jamo::slice_shift_jongseong(remaining);
362        match (choseong, jungseong, jongseong, remaining) {
363            (Some(choseong), Some(jungseong), Some(jongseong), b"") => {
364                let c = 0xac00 + (choseong * 21 + jungseong) * 28 + jongseong;
365                return char::from_u32(c);
366            }
367            (_, _, _, _) => {
368                // there are no other names starting with `HANGUL SYLLABLE `
369                // (verified by `generator/...`).
370                return None;
371            }
372        }
373    }
374
375    // try `CJK UNIFIED IDEOGRAPH-<digits>`
376    if search_name.starts_with(NORMALISED_CJK_UNIFIED_IDEOGRAPH_PREFIX.as_bytes()) {
377        let remaining = &search_name[NORMALISED_CJK_UNIFIED_IDEOGRAPH_PREFIX.len()..];
378        if remaining.len() > 5 {
379            return None;
380        } // avoid overflow
381
382        let mut v = 0u32;
383        for &c in remaining {
384            v = match c {
385                b'0'..=b'9' => (v << 4) | (c - b'0') as u32,
386                b'A'..=b'F' => (v << 4) | (c - b'A' + 10) as u32,
387                _ => return None,
388            }
389        }
390        let ch = char::from_u32(v)?;
391
392        // check if the resulting code is indeed in the known ranges
393        if is_cjk_unified_ideograph(ch) {
394            return Some(ch);
395        } else {
396            // there are no other names starting with `CJK UNIFIED IDEOGRAPH-`
397            // (verified by `src/generate.py`).
398            return None;
399        }
400    }
401
402    // get the parts of the hash...
403    let (g, f1, f2) = split(fnv_hash(search_name.iter().copied()));
404    // ...and the appropriate displacements...
405    let (d1, d2) = generated_phf::NAME2CODE_DISP[g as usize % generated_phf::NAME2CODE_DISP.len()];
406
407    // ...to find the right index...
408    let idx = displace(f1, f2, d1 as u32, d2 as u32) as usize;
409    // ...for looking up the codepoint.
410    let codepoint = generated_phf::NAME2CODE_CODE[idx % generated_phf::NAME2CODE_CODE.len()];
411
412    // Now check that this is actually correct. Since this is a
413    // perfect hash table, valid names map precisely to their code
414    // point (and invalid names map to anything), so we only need to
415    // check the name for this codepoint matches the input and we know
416    // everything. (i.e. no need for probing)
417    let maybe_name = match name(codepoint) {
418        None => {
419            if true {
420                debug_assert!(false) // what?
421            }
422            return character_by_alias(search_name);
423        }
424        Some(name) => name,
425    };
426
427    // `name(codepoint)` returns an iterator yielding words separated by spaces or hyphens.
428    // That means whenever a name contains a non-medial hyphen, it must be emulated by inserting an
429    // artificial empty word (`""`) between the space and the hyphen.
430    let mut cmp_name = search_name;
431    for part in maybe_name {
432        let part = match part {
433            "" => "-",       // Non-medial hyphens are preserved by `normalise_name`, check them.
434            " " => continue, // Spaces and medial hyphens are removed, ignore them.
435            "-" if codepoint != '\u{1180}' => continue, // But the hyphen in U+1180 is preserved.
436            word => word,
437        };
438
439        if let Some(rest) = cmp_name.strip_prefix(part.as_bytes()) {
440            cmp_name = rest;
441        } else {
442            return character_by_alias(search_name);
443        }
444    }
445
446    // "HANGUL JUNGSEONG O-E" is ambiguous, returning U+116C HANGUL JUNGSEONG OE instead.
447    // All other ways of spelling U+1180 will get properly detected, so it's enough to just check
448    // if the hyphen is in the right place.
449    if codepoint == '\u{116C}'
450        && original_name
451            .trim_end_matches(|c: char| c.is_ascii_whitespace() || c == '_')
452            .bytes()
453            .nth_back(1)
454            == Some(b'-')
455    {
456        return Some('\u{1180}');
457    }
458
459    Some(codepoint)
460}
461
462/// Convert a Unicode name to a form that can be used for loose matching, as per
463/// [UAX#44](https://www.unicode.org/reports/tr44/tr44-34.html#Matching_Names).
464///
465/// This function matches `unicode_names2_generator::normalise_name` in implementation, except that
466/// the special case of U+1180 HANGUL JUNGSEONG O-E isn't handled here, because we don't yet know
467/// which character is being queried and a string comparison would be expensive to inspect each
468/// query with given it only matches for one character. Thus the case of U+1180 is handled at the
469/// end of [`character`].
470fn normalise_name(search_name: &str, buf: &mut [u8; LONGEST_NAME_LEN]) -> usize {
471    let mut cursor = 0;
472    let bytes = search_name.as_bytes();
473
474    for (i, c) in bytes.iter().map(u8::to_ascii_uppercase).enumerate() {
475        // "Ignore case, whitespace, underscore ('_'), [...]"
476        if c.is_ascii_whitespace() || c == b'_' {
477            continue;
478        }
479
480        // "[...] and all medial hyphens except the hyphen in U+1180 HANGUL JUNGSEONG O-E."
481        // See doc comment for why U+1180 isn't handled
482        if c == b'-'
483            && bytes.get(i - 1).map_or(false, u8::is_ascii_alphanumeric)
484            && bytes.get(i + 1).map_or(false, u8::is_ascii_alphanumeric)
485        {
486            continue;
487        }
488
489        if !c.is_ascii_alphanumeric() && c != b'-' {
490            // All unicode names comprise only of alphanumeric characters and hyphens after
491            // stripping spaces and underscores. Returning 0 effectively serves as returning `None`.
492            return 0;
493        }
494
495        if cursor >= buf.len() {
496            // No Unicode character has this long a name.
497            return 0;
498        }
499        buf[cursor] = c;
500        cursor += 1;
501    }
502
503    cursor
504}
505
506#[cfg(test)]
507mod tests {
508    use super::*;
509    use rand::{
510        distributions::{Distribution, Standard},
511        prelude::{SeedableRng, StdRng},
512    };
513    use std::char;
514    use std::prelude::v1::*;
515
516    extern crate test;
517
518    use test::bench::Bencher;
519
520    static DATA: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/data/UnicodeData.txt"));
521
522    #[test]
523    fn exhaustive() {
524        // check that gaps have no names (these are unassigned/control
525        // codes).
526        fn negative_range(from: u32, to: u32) {
527            for c in (from..to).filter_map(char::from_u32) {
528                if !is_cjk_unified_ideograph(c) && !jamo::is_hangul_syllable(c) {
529                    let n = name(c);
530                    assert!(
531                        n.is_none(),
532                        "{} ({}) shouldn't have a name but is called {}",
533                        c,
534                        c as u32,
535                        n.unwrap()
536                    );
537                }
538            }
539        }
540
541        let mut last = 0;
542        for line in DATA.lines() {
543            let mut it = line.split(';');
544
545            let raw_c = it.next();
546            let c = match char::from_u32(
547                raw_c.and_then(|s| u32::from_str_radix(s, 16).ok()).unwrap(),
548            ) {
549                Some(c) => c,
550                None => continue,
551            };
552
553            let n = it.next().unwrap();
554            if n.starts_with("<") {
555                continue;
556            }
557
558            let computed_n = name(c).unwrap();
559            let n_str = computed_n.to_string();
560            assert_eq!(n_str, n.to_string());
561            assert_eq!(computed_n.len(), n_str.len());
562
563            let (hint_low, hint_high) = computed_n.size_hint();
564            let number_of_parts = computed_n.count();
565            assert_eq!(hint_low, number_of_parts);
566            assert_eq!(hint_high, Some(number_of_parts));
567
568            assert_eq!(character(n), Some(c));
569            assert_eq!(character(&n.to_ascii_lowercase()), Some(c));
570
571            negative_range(last, c as u32);
572            last = c as u32 + 1;
573        }
574        negative_range(last, 0x10FFFF + 1)
575    }
576
577    #[test]
578    fn name_to_string() {
579        let n = name('a').unwrap();
580        assert_eq!(n.to_string(), "LATIN SMALL LETTER A".to_string());
581        let n = name('🁣').unwrap();
582        assert_eq!(n.to_string(), "DOMINO TILE VERTICAL-00-00".to_string());
583    }
584
585    #[test]
586    fn character_negative() {
587        let long_name = "x".repeat(generated::LONGEST_NAME_LEN + 1);
588        let prefix = format!("{}x", generated::LONGEST_NAME); // This name would appear valid if truncated
589        let names = ["", "x", "öäå", "SPAACE", &long_name, &prefix];
590        for &n in names.iter() {
591            assert_eq!(character(n), None);
592        }
593    }
594
595    #[test]
596    fn name_hangul_syllable() {
597        assert_eq!(
598            name('\u{ac00}').map(|s| s.to_string()),
599            Some("HANGUL SYLLABLE GA".to_string())
600        ); // first
601        assert_eq!(
602            name('\u{bdc1}').map(|s| s.to_string()),
603            Some("HANGUL SYLLABLE BWELG".to_string())
604        );
605        assert_eq!(
606            name('\u{d7a3}').map(|s| s.to_string()),
607            Some("HANGUL SYLLABLE HIH".to_string())
608        ); // last
609    }
610
611    #[test]
612    fn character_hangul_syllable() {
613        assert_eq!(character("HANGUL SYLLABLE GA"), Some('\u{ac00}'));
614        assert_eq!(character("HANGUL SYLLABLE BWELG"), Some('\u{bdc1}'));
615        assert_eq!(character("HANGUL SYLLABLE HIH"), Some('\u{d7a3}'));
616        assert_eq!(character("HANGUL SYLLABLE BLAH"), None);
617    }
618
619    #[test]
620    fn cjk_unified_ideograph_exhaustive() {
621        for &(lo, hi) in generated::CJK_IDEOGRAPH_RANGES.iter() {
622            for x in lo as u32..=hi as u32 {
623                let c = char::from_u32(x).unwrap();
624
625                let real_name = format!("CJK UNIFIED IDEOGRAPH-{:X}", x);
626                let lower_real_name = format!("CJK UNIFIED IDEOGRAPH-{:x}", x);
627                assert_eq!(character(&real_name), Some(c));
628                assert_eq!(character(&lower_real_name), Some(c));
629
630                assert_eq!(name(c).map(|s| s.to_string()), Some(real_name));
631            }
632        }
633    }
634    #[test]
635    fn name_cjk_unified_ideograph() {
636        assert_eq!(
637            name('\u{4e00}').map(|s| s.to_string()),
638            Some("CJK UNIFIED IDEOGRAPH-4E00".to_string())
639        ); // first in BMP
640        assert_eq!(
641            name('\u{9fcc}').map(|s| s.to_string()),
642            Some("CJK UNIFIED IDEOGRAPH-9FCC".to_string())
643        ); // last in BMP (as of 6.1)
644        assert_eq!(
645            name('\u{20000}').map(|s| s.to_string()),
646            Some("CJK UNIFIED IDEOGRAPH-20000".to_string())
647        ); // first in SIP
648        assert_eq!(
649            name('\u{2a6d6}').map(|s| s.to_string()),
650            Some("CJK UNIFIED IDEOGRAPH-2A6D6".to_string())
651        );
652        assert_eq!(
653            name('\u{2a700}').map(|s| s.to_string()),
654            Some("CJK UNIFIED IDEOGRAPH-2A700".to_string())
655        );
656        assert_eq!(
657            name('\u{2b81d}').map(|s| s.to_string()),
658            Some("CJK UNIFIED IDEOGRAPH-2B81D".to_string())
659        ); // last in SIP (as of 6.0)
660    }
661
662    #[test]
663    fn character_cjk_unified_ideograph() {
664        assert_eq!(character("CJK UNIFIED IDEOGRAPH-4E00"), Some('\u{4e00}'));
665        assert_eq!(character("CJK UNIFIED IDEOGRAPH-9FCC"), Some('\u{9fcc}'));
666        assert_eq!(character("CJK UNIFIED IDEOGRAPH-20000"), Some('\u{20000}'));
667        assert_eq!(character("CJK UNIFIED IDEOGRAPH-2A6D6"), Some('\u{2a6d6}'));
668        assert_eq!(character("CJK UNIFIED IDEOGRAPH-2A700"), Some('\u{2a700}'));
669        assert_eq!(character("CJK UNIFIED IDEOGRAPH-2B81D"), Some('\u{2b81d}'));
670        assert_eq!(character("CJK UNIFIED IDEOGRAPH-"), None);
671        assert_eq!(character("CJK UNIFIED IDEOGRAPH-!@#$"), None);
672        assert_eq!(character("CJK UNIFIED IDEOGRAPH-1234"), None);
673        assert_eq!(character("CJK UNIFIED IDEOGRAPH-EFGH"), None);
674        assert_eq!(character("CJK UNIFIED IDEOGRAPH-12345"), None);
675        assert_eq!(character("CJK UNIFIED IDEOGRAPH-2A6FF"), None); // between Ext B and Ext C
676        assert_eq!(character("CJK UNIFIED IDEOGRAPH-2A6FF"), None);
677    }
678
679    #[test]
680    fn character_by_alias() {
681        assert_eq!(super::character_by_alias(b"NEW LINE"), Some('\n'));
682        assert_eq!(super::character_by_alias(b"BACKSPACE"), Some('\u{8}'));
683        assert_eq!(super::character_by_alias(b"NOT AN ALIAS"), None);
684    }
685
686    #[test]
687    fn test_uax44() {
688        assert_eq!(character(" L_O_W l_i_n_e"), Some('_'));
689        assert_eq!(character("space \x09\x0a\x0c\x0d"), Some(' '));
690        assert_eq!(character("FULL S-T-O-P"), Some('.'));
691        assert_eq!(character("tibetan letter -a"), Some('\u{F60}'));
692        assert_eq!(character("tibetan letter- a"), Some('\u{F60}'));
693        assert_eq!(character("tibetan letter  -   a"), Some('\u{F60}'));
694        assert_eq!(character("tibetan letter_-_a"), Some('\u{F60}'));
695        assert_eq!(character("latinSMALLletterA"), Some('a'));
696
697        // Test exceptions related to U+1180
698        let jungseong_oe = Some('\u{116C}');
699        let jungseong_o_e = Some('\u{1180}');
700        assert_eq!(character("HANGUL JUNGSEONG OE"), jungseong_oe);
701        assert_eq!(character("HANGUL JUNGSEONG O_E"), jungseong_oe);
702        assert_eq!(character("HANGUL JUNGSEONG O E"), jungseong_oe);
703        assert_eq!(character("HANGUL JUNGSEONG O-E"), jungseong_o_e);
704        assert_eq!(character("HANGUL JUNGSEONG O-E\n"), jungseong_o_e);
705        assert_eq!(character("HANGUL JUNGSEONG O-E__"), jungseong_o_e);
706        assert_eq!(character("HANGUL JUNGSEONG O- E"), jungseong_o_e);
707        assert_eq!(character("HANGUL JUNGSEONG O -E"), jungseong_o_e);
708        assert_eq!(character("HANGUL JUNGSEONG O_-_E"), jungseong_o_e);
709    }
710
711    #[bench]
712    fn name_basic(b: &mut Bencher) {
713        b.iter(|| {
714            for s in name('ö').unwrap() {
715                test::black_box(s);
716            }
717        })
718    }
719
720    #[bench]
721    fn character_basic(b: &mut Bencher) {
722        b.iter(|| character("LATIN SMALL LETTER O WITH DIAERESIS"));
723    }
724
725    #[bench]
726    fn name_10000_invalid(b: &mut Bencher) {
727        // be consistent across runs, but avoid sequential/caching.
728        let mut rng = StdRng::seed_from_u64(0x12345678);
729        let chars: Vec<char> = Standard
730            .sample_iter(&mut rng)
731            .take(10000)
732            .filter_map(|c| match c {
733                c if name(c).is_none() => Some(c),
734                _ => None,
735            })
736            .collect();
737
738        b.iter(|| {
739            for &c in chars.iter() {
740                assert!(name(c).is_none());
741            }
742        })
743    }
744
745    #[bench]
746    fn name_all_valid(b: &mut Bencher) {
747        let chars = (0u32..0x10FFFF)
748            .filter_map(|x| match char::from_u32(x) {
749                Some(c) if name(c).is_some() => Some(c),
750                _ => None,
751            })
752            .collect::<Vec<char>>();
753
754        b.iter(|| {
755            for c in chars.iter() {
756                for s in name(*c).unwrap() {
757                    test::black_box(s);
758                }
759            }
760        });
761    }
762
763    #[bench]
764    fn character_10000(b: &mut Bencher) {
765        // be consistent across runs, but avoid sequential/caching.
766        let mut rng = StdRng::seed_from_u64(0x12345678);
767
768        let names: Vec<_> = Standard
769            .sample_iter(&mut rng)
770            .take(10000)
771            .filter_map(name)
772            .map(|name| name.to_string())
773            .collect();
774
775        b.iter(|| {
776            for n in names.iter() {
777                test::black_box(character(n));
778            }
779        })
780    }
781}
782
783#[cfg(all(feature = "no_std", not(test)))]
784mod std {
785    pub use core::{clone, fmt, marker};
786}