Skip to main content

harfrust/
tag.rs

1use smallvec::SmallVec;
2
3use super::{tag_reverse, tag_table, Language, Script, Tag};
4
5type ThreeTags = SmallVec<[Tag; 3]>;
6
7trait SmallVecExt {
8    fn left(&self) -> usize;
9    fn is_full(&self) -> bool;
10}
11
12impl<A: smallvec::Array> SmallVecExt for SmallVec<A> {
13    fn left(&self) -> usize {
14        self.inline_size() - self.len()
15    }
16
17    fn is_full(&self) -> bool {
18        self.len() == self.inline_size()
19    }
20}
21
22impl Script {
23    /// Converts an optional script and language to preferred OpenType tags.
24    pub fn tags_for_language(
25        script: Option<Self>,
26        language: Option<&Language>,
27    ) -> (ScriptTags, LanguageTags) {
28        let mut needs_script = true;
29        let mut scripts = SmallVec::new();
30        let mut languages = SmallVec::new();
31
32        let mut private_use_subtag = None;
33        let mut prefix = b"" as &[u8];
34        if let Some(language) = language {
35            let language = language.as_bytes();
36            if language.starts_with(b"x-") {
37                private_use_subtag = Some(language);
38            } else {
39                let mut i = 1;
40                while i < language.len() {
41                    if language.get(i - 1) == Some(&b'-') && language.get(i + 1) == Some(&b'-') {
42                        if language[i] == b'x' {
43                            private_use_subtag = Some(&language[i..]);
44                            if prefix.is_empty() {
45                                prefix = &language[..i - 1];
46                            }
47
48                            break;
49                        } else {
50                            prefix = &language[..i - 1];
51                        }
52                    }
53
54                    i += 1;
55                }
56
57                if prefix.is_empty() {
58                    prefix = &language[..i];
59                }
60            }
61
62            needs_script = !parse_private_use_subtag(
63                private_use_subtag,
64                b"-hbsc",
65                u8::to_ascii_lowercase,
66                &mut scripts,
67            );
68
69            let needs_language = !parse_private_use_subtag(
70                private_use_subtag,
71                b"-hbot",
72                u8::to_ascii_uppercase,
73                &mut languages,
74            );
75
76            if needs_language && !prefix.is_empty() {
77                tags_from_language(prefix, &mut languages);
78            }
79        }
80
81        if needs_script {
82            all_tags_from_script(script, &mut scripts);
83        }
84
85        (ScriptTags(scripts), LanguageTags(languages))
86    }
87}
88
89fn parse_private_use_subtag(
90    private_use_subtag: Option<&[u8]>,
91    prefix: &[u8],
92    normalize: fn(&u8) -> u8,
93    tags: &mut ThreeTags,
94) -> bool {
95    let Some(private_use_subtag) = private_use_subtag else {
96        return false;
97    };
98
99    let private_use_subtag = match private_use_subtag
100        .windows(prefix.len())
101        .position(|window| window == prefix)
102    {
103        Some(idx) => &private_use_subtag[idx + prefix.len()..],
104        None => return false,
105    };
106
107    let mut tag = if let Some(hex) = private_use_subtag.strip_prefix(b"-") {
108        // Hexadecimal tags encode four bytes without case normalization.
109        let Some(hex) = hex.get(..8) else {
110            return false;
111        };
112        let mut value = 0;
113        for &c in hex {
114            let Some(digit) = char::from(c).to_digit(16) else {
115                return false;
116            };
117            value = (value << 4) | digit;
118        }
119        Tag::from_u32(value)
120    } else {
121        let mut tag = SmallVec::<[u8; 4]>::new();
122        for c in private_use_subtag.iter().take(4) {
123            if c.is_ascii_alphanumeric() {
124                tag.push((normalize)(c));
125            } else {
126                break;
127            }
128        }
129
130        if tag.is_empty() {
131            return false;
132        }
133
134        Tag::from_bytes_lossy(tag.as_slice())
135    };
136
137    // Some bits magic from HarfBuzz...
138    if tag.as_u32() & 0xDFDF_DFDF == Tag::default_script().as_u32() {
139        tag = Tag::from_u32(tag.as_u32() ^ !0xDFDF_DFDF);
140    }
141
142    tags.push(tag);
143
144    true
145}
146
147fn lang_cmp(s1: &[u8], s2: &[u8]) -> core::cmp::Ordering {
148    let da = s1
149        .iter()
150        .position(|&c| c == b'-' || c == b'\0')
151        .unwrap_or(s1.len());
152    let db = s2
153        .iter()
154        .position(|&c| c == b'-' || c == b'\0')
155        .unwrap_or(s2.len());
156    let n = core::cmp::max(da, db);
157    let ea = core::cmp::min(n, s1.len());
158    let eb = core::cmp::min(n, s2.len());
159    s1[..ea].cmp(&s2[..eb])
160}
161
162pub(super) fn subtag_matches(language: impl AsRef<[u8]>, subtag: impl AsRef<[u8]>) -> bool {
163    let language = language.as_ref();
164    let subtag = subtag.as_ref();
165
166    for i in language
167        .windows(subtag.len())
168        .enumerate()
169        .filter_map(|(i, window)| (window == subtag).then_some(i))
170    {
171        if let Some(c) = language.get(i + subtag.len()) {
172            if !c.is_ascii_alphanumeric() {
173                return true;
174            }
175        } else {
176            return true;
177        }
178    }
179
180    false
181}
182
183pub(super) fn lang_matches(language: impl AsRef<[u8]>, spec: impl AsRef<[u8]>) -> bool {
184    let language = language.as_ref();
185    let spec = spec.as_ref();
186
187    if language.starts_with(spec) {
188        return language.len() == spec.len() || language.get(spec.len()) == Some(&b'-');
189    }
190
191    false
192}
193
194pub(super) fn strncmp(s1: impl AsRef<[u8]>, s2: impl AsRef<[u8]>, n: usize) -> bool {
195    let s1 = s1.as_ref();
196    let s2 = s2.as_ref();
197
198    let n1 = core::cmp::min(n, s1.len());
199    let n2 = core::cmp::min(n, s2.len());
200    s1[..n1] == s2[..n2]
201}
202
203fn tags_from_language(language: &[u8], tags: &mut ThreeTags) {
204    // Check for matches of multiple subtags.
205    if let Ok(language_str) = core::str::from_utf8(language) {
206        if tag_table::tags_from_complex_language(language_str, tags) {
207            return;
208        }
209    }
210
211    let mut sublang = language;
212
213    // Find a language matching in the first component.
214    if let Some(i) = language.iter().position(|&c| c == b'-') {
215        // If there is an extended language tag, use it.
216        if language.len() >= 6 {
217            let extlang = match language[i + 1..].iter().position(|&c| c == b'-') {
218                Some(idx) => idx == 3,
219                None => language.len() - i - 1 == 3,
220            };
221
222            if extlang && language[i + 1].is_ascii_alphabetic() {
223                sublang = &language[i + 1..];
224            }
225        }
226    }
227
228    use tag_table::OPEN_TYPE_LANGUAGES as LANGUAGES;
229
230    if let Ok(mut idx) = LANGUAGES.binary_search_by(|v| lang_cmp(&v.language, sublang)) {
231        while idx != 0 && LANGUAGES[idx].language == LANGUAGES[idx - 1].language {
232            idx -= 1;
233        }
234
235        let len = core::cmp::min(tags.left(), LANGUAGES.len() - idx - 1);
236        for i in 0..len {
237            if LANGUAGES[idx + i].language != LANGUAGES[idx].language {
238                break;
239            }
240
241            if LANGUAGES[idx + i].tag.is_null() {
242                break;
243            }
244
245            if tags.is_full() {
246                break;
247            }
248
249            tags.push(LANGUAGES[idx + i].tag);
250        }
251
252        return;
253    }
254
255    if language.len() == 3 {
256        tags.push(Tag::from_bytes_lossy(language).to_uppercase());
257    }
258}
259
260impl Language {
261    /// Converts an OpenType language-system tag to a BCP 47 language.
262    ///
263    /// Unknown tags use HarfBuzz's private-use `x-hbot-` spelling so that they
264    /// round-trip through [`Script::tags_for_language`]. The `dflt` tag
265    /// returns `None`.
266    pub fn from_tag(tag: Tag) -> Option<Self> {
267        if tag == Tag::new(b"dflt") {
268            return None;
269        }
270
271        let bytes = tag.to_be_bytes();
272        if let Ok(index) = tag_reverse::OT_LANGUAGES_REVERSE
273            .binary_search_by_key(&bytes, |(candidate, _)| *candidate)
274        {
275            return Language::new(tag_reverse::OT_LANGUAGES_REVERSE[index].1);
276        }
277
278        let mut language = [0u8; 20];
279        let mut length = 0;
280        if bytes[..3].iter().all(u8::is_ascii_alphabetic) && bytes[3] == b' ' {
281            for byte in &bytes[..3] {
282                language[length] = byte.to_ascii_lowercase();
283                length += 1;
284            }
285            language[length] = b'-';
286            length += 1;
287        }
288        language[length..length + 7].copy_from_slice(b"x-hbot-");
289        length += 7;
290        for byte in bytes {
291            for nibble in [byte >> 4, byte & 0x0f] {
292                language[length] = b"0123456789abcdef"[nibble as usize];
293                length += 1;
294            }
295        }
296        Language::new(&language[..length])
297    }
298}
299
300fn all_tags_from_script(script: Option<Script>, tags: &mut ThreeTags) {
301    if let Some(script) = script {
302        if let Some(tag) = new_tag_from_script(script) {
303            // Script::Myanmar maps to 'mym2', but there is no 'mym3'.
304            if tag != Tag::new(b"mym2") {
305                let mut tag3 = tag.to_be_bytes();
306                tag3[3] = b'3';
307                tags.push(Tag::new(&tag3));
308            }
309
310            if !tags.is_full() {
311                tags.push(tag);
312            }
313        }
314
315        if !tags.is_full() {
316            tags.push(old_tag_from_script(script));
317        }
318    }
319}
320
321/// OpenType script tags for a Unicode script, in preference order.
322///
323/// At most three tags are stored inline.
324#[derive(Clone, Debug)]
325pub struct ScriptTags(ThreeTags);
326
327impl ScriptTags {
328    /// Returns the tags, from most to least preferred.
329    pub fn as_slice(&self) -> &[Tag] {
330        &self.0
331    }
332}
333
334/// OpenType language-system tags for a BCP 47 language, in preference order.
335///
336/// At most three tags are stored inline.
337#[derive(Clone, Debug)]
338pub struct LanguageTags(ThreeTags);
339
340impl LanguageTags {
341    /// Returns the tags, from most to least preferred.
342    pub fn as_slice(&self) -> &[Tag] {
343        &self.0
344    }
345}
346
347impl Script {
348    /// Returns the OpenType script tags corresponding to this Unicode script.
349    pub fn tags(self) -> ScriptTags {
350        let mut tags = ThreeTags::new();
351        all_tags_from_script(Some(self), &mut tags);
352        ScriptTags(tags)
353    }
354}
355
356fn new_tag_from_script(script: Script) -> Option<Tag> {
357    match script {
358        Script::BENGALI => Some(Tag::new(b"bng2")),
359        Script::DEVANAGARI => Some(Tag::new(b"dev2")),
360        Script::GUJARATI => Some(Tag::new(b"gjr2")),
361        Script::GURMUKHI => Some(Tag::new(b"gur2")),
362        Script::KANNADA => Some(Tag::new(b"knd2")),
363        Script::MALAYALAM => Some(Tag::new(b"mlm2")),
364        Script::ORIYA => Some(Tag::new(b"ory2")),
365        Script::TAMIL => Some(Tag::new(b"tml2")),
366        Script::TELUGU => Some(Tag::new(b"tel2")),
367        Script::MYANMAR => Some(Tag::new(b"mym2")),
368        _ => None,
369    }
370}
371
372fn old_tag_from_script(script: Script) -> Tag {
373    // This seems to be accurate as of end of 2012.
374    match script {
375        Script::MATH => Tag::new(b"math"),
376
377        // Hiragana and Katakana both map to 'kana'.
378        Script::HIRAGANA => Tag::new(b"kana"),
379
380        // Spaces at the end are preserved, unlike ISO 15924.
381        Script::LAO => Tag::new(b"lao "),
382        Script::YI => Tag::new(b"yi  "),
383        // Unicode-5.0 additions.
384        Script::NKO => Tag::new(b"nko "),
385        // Unicode-5.1 additions.
386        Script::VAI => Tag::new(b"vai "),
387
388        // Else, just change first char to lowercase and return.
389        _ => Tag::from_u32(script.tag().as_u32() | 0x2000_0000),
390    }
391}
392
393pub trait TagExt {
394    fn from_bytes_lossy(bytes: &[u8]) -> Self;
395    fn as_u32(self) -> u32;
396    fn is_null(self) -> bool;
397    fn default_script() -> Self;
398    fn default_language() -> Self;
399    #[cfg(test)]
400    fn to_lowercase(&self) -> Self;
401    fn to_uppercase(&self) -> Self;
402}
403
404impl TagExt for Tag {
405    fn from_bytes_lossy(bytes: &[u8]) -> Self {
406        let mut array = [b' '; 4];
407        for (src, dest) in bytes.iter().zip(&mut array) {
408            *dest = *src;
409        }
410        Tag::new(&array)
411    }
412
413    fn as_u32(self) -> u32 {
414        u32::from_be_bytes(self.to_be_bytes())
415    }
416
417    fn is_null(self) -> bool {
418        self.to_be_bytes() == [0, 0, 0, 0]
419    }
420
421    #[inline]
422    fn default_script() -> Self {
423        Tag::new(b"DFLT")
424    }
425
426    #[inline]
427    fn default_language() -> Self {
428        Tag::new(b"dflt")
429    }
430
431    /// Converts tag to lowercase.
432    #[cfg(test)]
433    #[inline]
434    fn to_lowercase(&self) -> Self {
435        let b = self.to_be_bytes();
436        Tag::new(&[
437            b[0].to_ascii_lowercase(),
438            b[1].to_ascii_lowercase(),
439            b[2].to_ascii_lowercase(),
440            b[3].to_ascii_lowercase(),
441        ])
442    }
443
444    /// Converts tag to uppercase.
445    #[inline]
446    fn to_uppercase(&self) -> Self {
447        let b = self.to_be_bytes();
448        Tag::new(&[
449            b[0].to_ascii_uppercase(),
450            b[1].to_ascii_uppercase(),
451            b[2].to_ascii_uppercase(),
452            b[3].to_ascii_uppercase(),
453        ])
454    }
455}
456
457#[rustfmt::skip]
458#[cfg(test)]
459mod tests {
460    #![allow(non_snake_case)]
461
462    use super::*;
463
464    #[test]
465    fn language_matches() {
466        assert!(lang_matches(b"pl", b"pl"));
467        assert!(lang_matches(b"pl-pl", b"pl"));
468        assert!(!lang_matches(b"pl", b"pl-pl"));
469        assert!(!lang_matches(b"plx", b"pl"));
470        assert!(!lang_matches(b"en", b"pl"));
471    }
472    use alloc::vec::Vec;
473
474    fn new_tag_to_script(tag: Tag) -> Option<Script> {
475        match &tag.to_be_bytes() {
476            b"bng2" => Some(Script::BENGALI),
477            b"dev2" => Some(Script::DEVANAGARI),
478            b"gjr2" => Some(Script::GUJARATI),
479            b"gur2" => Some(Script::GURMUKHI),
480            b"knd2" => Some(Script::KANNADA),
481            b"mlm2" => Some(Script::MALAYALAM),
482            b"ory2" => Some(Script::ORIYA),
483            b"tml2" => Some(Script::TAMIL),
484            b"tel2" => Some(Script::TELUGU),
485            b"mym2" => Some(Script::MYANMAR),
486            _ => Some(Script::UNKNOWN),
487        }
488    }
489
490    fn old_tag_to_script(tag: Tag) -> Option<Script> {
491        if tag == Tag::default_script() {
492            return None;
493        }
494
495        let mut bytes = tag.to_be_bytes();
496
497        // This side of the conversion is fully algorithmic.
498
499        // Any spaces at the end of the tag are replaced by repeating the last
500        // letter.  Eg 'nko ' -> 'Nkoo'
501        if bytes[2] == b' ' {
502            bytes[2] = bytes[1];
503        }
504        if bytes[3] == b' ' {
505            bytes[3] = bytes[2];
506        }
507
508        // Change first char to uppercase.
509        bytes[0] = bytes[0].to_ascii_uppercase();
510
511        Some(Script(Tag::new(&bytes)))
512    }
513
514    fn tag_to_script(tag: Tag) -> Option<Script> {
515        let bytes = tag.to_be_bytes();
516        if bytes[3] == b'2' || bytes[3] == b'3' {
517            let mut tag2 = bytes;
518            tag2[3] = b'2';
519            return new_tag_to_script(Tag::new(&tag2));
520        }
521
522        old_tag_to_script(tag)
523    }
524
525    fn test_simple_tags(tag: &str, script: Script) {
526        let tag = Tag::from_bytes_lossy(tag.as_bytes());
527
528        let (scripts, _) = Script::tags_for_language(Some(script), None);
529        if !scripts.as_slice().is_empty() {
530            assert_eq!(tag, scripts.as_slice()[0]);
531        } else {
532            assert_eq!(tag, Tag::default_script());
533        }
534
535        assert_eq!(tag_to_script(tag), Some(script));
536    }
537
538    #[test]
539    fn tag_to_uppercase() {
540        assert_eq!(Tag::new(b"abcd").to_uppercase(), Tag::new(b"ABCD"));
541        assert_eq!(Tag::new(b"abc ").to_uppercase(), Tag::new(b"ABC "));
542        assert_eq!(Tag::new(b"ABCD").to_uppercase(), Tag::new(b"ABCD"));
543    }
544
545    #[test]
546    fn tag_to_lowercase() {
547        assert_eq!(Tag::new(b"abcd").to_lowercase(), Tag::new(b"abcd"));
548        assert_eq!(Tag::new(b"abc ").to_lowercase(), Tag::new(b"abc "));
549        assert_eq!(Tag::new(b"ABCD").to_lowercase(), Tag::new(b"abcd"));
550    }
551
552    #[test]
553    fn script_degenerate() {
554        assert_eq!(Tag::new(b"DFLT"), Tag::default_script());
555
556        // Hiragana and Katakana both map to 'kana'.
557        test_simple_tags("kana", Script::KATAKANA);
558
559        let (scripts, _) = Script::tags_for_language(Some(Script::HIRAGANA), None);
560        assert_eq!(scripts.as_slice(), &[Tag::new(b"kana")]);
561
562        let katakana_or_hiragana =
563            Script::from_iso15924_tag(Tag::new(b"Hrkt")).unwrap();
564        let (scripts, _) = Script::tags_for_language(Some(katakana_or_hiragana), None);
565        assert_eq!(scripts.as_slice(), &[Tag::new(b"hrkt")]);
566
567        // Spaces are replaced
568        assert_eq!(tag_to_script(Tag::new(b"be  ")), Script::from_iso15924_tag(Tag::new(b"Beee")));
569    }
570
571    #[test]
572    fn script_tags_for_language() {
573        let language = Language::new("zh-Hant").unwrap();
574        let (scripts, languages) = Script::tags_for_language(Some(Script::DEVANAGARI), Some(&language));
575        assert_eq!(
576            scripts.as_slice(),
577            &[Tag::new(b"dev3"), Tag::new(b"dev2"), Tag::new(b"deva")]
578        );
579        assert_eq!(languages.as_slice(), &[Tag::new(b"ZHT ")]);
580    }
581
582    #[test]
583    fn script_simple() {
584        // Arbitrary non-existent script.
585        test_simple_tags("wwyz", Script::from_iso15924_tag(Tag::new(b"wWyZ")).unwrap());
586
587        // These we don't really care about.
588        test_simple_tags("zyyy", Script::COMMON);
589        test_simple_tags("zinh", Script::INHERITED);
590        test_simple_tags("zzzz", Script::UNKNOWN);
591
592        test_simple_tags("arab", Script::ARABIC);
593        test_simple_tags("copt", Script::COPTIC);
594        test_simple_tags("kana", Script::KATAKANA);
595        test_simple_tags("latn", Script::LATIN);
596
597        // These are trickier since their OT script tags have space.
598        test_simple_tags("lao ", Script::LAO);
599        test_simple_tags("yi  ", Script::YI);
600        // Unicode-5.0 additions.
601        test_simple_tags("nko ", Script::NKO);
602        // Unicode-5.1 additions.
603        test_simple_tags("vai ", Script::VAI);
604
605        // https://docs.microsoft.com/en-us/typography/opentype/spec/scripttags
606
607        // Unicode-5.2 additions.
608        test_simple_tags("mtei", Script::MEETEI_MAYEK);
609        // Unicode-6.0 additions.
610        test_simple_tags("mand", Script::MANDAIC);
611    }
612
613    macro_rules! test_script_from_language {
614        ($name:ident, $tag:expr, $lang:expr, $script:expr) => {
615            #[test]
616            fn $name() {
617                let tag = Tag::from_bytes_lossy($tag.as_bytes());
618                let (scripts, _) =
619                    Script::tags_for_language($script, Language::new($lang).as_ref());
620                if !scripts.as_slice().is_empty() {
621                    assert_eq!(scripts.as_slice(), &[tag]);
622                }
623            }
624        };
625    }
626
627    test_script_from_language!(script_from_language_01, "", "", None);
628    test_script_from_language!(script_from_language_02, "", "en", None);
629    test_script_from_language!(script_from_language_03, "copt", "en", Some(Script::COPTIC));
630    test_script_from_language!(script_from_language_04, "", "x-hbsc", None);
631    test_script_from_language!(script_from_language_05, "copt", "x-hbsc", Some(Script::COPTIC));
632    test_script_from_language!(script_from_language_06, "abc ", "x-hbscabc", None);
633    test_script_from_language!(script_from_language_07, "deva", "x-hbscdeva", None);
634    test_script_from_language!(script_from_language_08, "dev2", "x-hbscdev2", None);
635    test_script_from_language!(script_from_language_09, "dev3", "x-hbscdev3", None);
636    test_script_from_language!(script_from_language_10, "copt", "x-hbotpap0-hbsccopt", None);
637    test_script_from_language!(script_from_language_11, "", "en-x-hbsc", None);
638    test_script_from_language!(script_from_language_12, "copt", "en-x-hbsc", Some(Script::COPTIC));
639    test_script_from_language!(script_from_language_13, "abc ", "en-x-hbscabc", None);
640    test_script_from_language!(script_from_language_14, "deva", "en-x-hbscdeva", None);
641    test_script_from_language!(script_from_language_15, "dev2", "en-x-hbscdev2", None);
642    test_script_from_language!(script_from_language_16, "dev3", "en-x-hbscdev3", None);
643    test_script_from_language!(script_from_language_17, "copt", "en-x-hbotpap0-hbsccopt", None);
644
645    #[test]
646    fn script_indic() {
647        fn check(tag1: &str, tag2: &str, tag3: &str, script: Script) {
648            let tag1 = Tag::from_bytes_lossy(tag1.as_bytes());
649            let tag2 = Tag::from_bytes_lossy(tag2.as_bytes());
650            let tag3 = Tag::from_bytes_lossy(tag3.as_bytes());
651
652            let (scripts, _) = Script::tags_for_language(Some(script), None);
653            assert_eq!(scripts.as_slice(), &[tag1, tag2, tag3]);
654            assert_eq!(tag_to_script(tag1), Some(script));
655            assert_eq!(tag_to_script(tag2), Some(script));
656            assert_eq!(tag_to_script(tag3), Some(script));
657        }
658
659        check("bng3", "bng2", "beng", Script::BENGALI);
660        check("dev3", "dev2", "deva", Script::DEVANAGARI);
661        check("gjr3", "gjr2", "gujr", Script::GUJARATI);
662        check("gur3", "gur2", "guru", Script::GURMUKHI);
663        check("knd3", "knd2", "knda", Script::KANNADA);
664        check("mlm3", "mlm2", "mlym", Script::MALAYALAM);
665        check("ory3", "ory2", "orya", Script::ORIYA);
666        check("tml3", "tml2", "taml", Script::TAMIL);
667        check("tel3", "tel2", "telu", Script::TELUGU);
668    }
669
670    // TODO: swap tag and lang
671    macro_rules! test_tag_from_language {
672        ($name:ident, $tag:expr, $lang:expr) => {
673            #[test]
674            fn $name() {
675                let tag = Tag::from_bytes_lossy($tag.as_bytes());
676                let (_, languages) = Script::tags_for_language(
677                    None,
678                    Language::new(&$lang.to_lowercase()).as_ref(),
679                );
680                if !languages.as_slice().is_empty() {
681                    assert_eq!(languages.as_slice()[0], tag);
682                }
683            }
684        };
685    }
686
687    test_tag_from_language!(tag_from_language_dflt, "dflt", "");
688    test_tag_from_language!(tag_from_language_ALT, "ALT", "alt");
689    test_tag_from_language!(tag_from_language_ARA, "ARA", "ar");
690    test_tag_from_language!(tag_from_language_AZE, "AZE", "az");
691    test_tag_from_language!(tag_from_language_az_ir, "AZE", "az-ir");
692    test_tag_from_language!(tag_from_language_az_az, "AZE", "az-az");
693    test_tag_from_language!(tag_from_language_ENG, "ENG", "en");
694    test_tag_from_language!(tag_from_language_en_US, "ENG", "en_US");
695    test_tag_from_language!(tag_from_language_CJA, "CJA", "cja"); /* Western Cham */
696    test_tag_from_language!(tag_from_language_CJM, "CJM", "cjm"); /* Eastern Cham */
697    test_tag_from_language!(tag_from_language_ENV, "EVN", "eve");
698    test_tag_from_language!(tag_from_language_HAL, "HAL", "cfm"); /* BCP47 and current ISO639-3 code for Halam/Falam Chin */
699    test_tag_from_language!(tag_from_language_flm, "HAL", "flm"); /* Retired ISO639-3 code for Halam/Falam Chin */
700    test_tag_from_language!(tag_from_language_hy, "HYE0", "hy");
701    test_tag_from_language!(tag_from_language_hyw, "HYE", "hyw");
702    test_tag_from_language!(tag_from_language_bgr, "QIN", "bgr"); /* Bawm Chin */
703    test_tag_from_language!(tag_from_language_cbl, "QIN", "cbl"); /* Bualkhaw Chin */
704    test_tag_from_language!(tag_from_language_cka, "QIN", "cka"); /* Khumi Awa Chin */
705    test_tag_from_language!(tag_from_language_cmr, "QIN", "cmr"); /* Mro-Khimi Chin */
706    test_tag_from_language!(tag_from_language_cnb, "QIN", "cnb"); /* Chinbon Chin */
707    test_tag_from_language!(tag_from_language_cnh, "QIN", "cnh"); /* Hakha Chin */
708    test_tag_from_language!(tag_from_language_cnk, "QIN", "cnk"); /* Khumi Chin */
709    test_tag_from_language!(tag_from_language_cnw, "QIN", "cnw"); /* Ngawn Chin */
710    test_tag_from_language!(tag_from_language_csh, "QIN", "csh"); /* Asho Chin */
711    test_tag_from_language!(tag_from_language_csy, "QIN", "csy"); /* Siyin Chin */
712    test_tag_from_language!(tag_from_language_ctd, "QIN", "ctd"); /* Tedim Chin */
713    test_tag_from_language!(tag_from_language_czt, "QIN", "czt"); /* Zotung Chin */
714    test_tag_from_language!(tag_from_language_dao, "QIN", "dao"); /* Daai Chin */
715    test_tag_from_language!(tag_from_language_htl, "QIN", "hlt"); /* Matu Chin */
716    test_tag_from_language!(tag_from_language_mrh, "QIN", "mrh"); /* Mara Chin */
717    test_tag_from_language!(tag_from_language_pck, "QIN", "pck"); /* Paite Chin */
718    test_tag_from_language!(tag_from_language_sez, "QIN", "sez"); /* Senthang Chin */
719    test_tag_from_language!(tag_from_language_tcp, "QIN", "tcp"); /* Tawr Chin */
720    test_tag_from_language!(tag_from_language_tcz, "QIN", "tcz"); /* Thado Chin */
721    test_tag_from_language!(tag_from_language_yos, "QIN", "yos"); /* Yos, deprecated by IANA in favor of Zou [zom] */
722    test_tag_from_language!(tag_from_language_zom, "QIN", "zom"); /* Zou */
723    test_tag_from_language!(tag_from_language_FAR, "FAR", "fa");
724    test_tag_from_language!(tag_from_language_fa_IR, "FAR", "fa_IR");
725    test_tag_from_language!(tag_from_language_man, "MNK", "man");
726    test_tag_from_language!(tag_from_language_SWA, "SWA", "aii"); /* Swadaya Aramaic */
727    test_tag_from_language!(tag_from_language_SYR, "SYR", "syr"); /* Syriac [macrolanguage] */
728    test_tag_from_language!(tag_from_language_amw, "SYR", "amw"); /* Western Neo-Aramaic */
729    test_tag_from_language!(tag_from_language_cld, "SYR", "cld"); /* Chaldean Neo-Aramaic */
730    test_tag_from_language!(tag_from_language_syc, "SYR", "syc"); /* Classical Syriac */
731    test_tag_from_language!(tag_from_language_TUA, "TUA", "tru"); /* Turoyo Aramaic */
732    test_tag_from_language!(tag_from_language_zh, "ZHS", "zh"); /* Chinese */
733    test_tag_from_language!(tag_from_language_zh_cn, "ZHS", "zh-cn"); /* Chinese (China) */
734    test_tag_from_language!(tag_from_language_zh_sg, "ZHS", "zh-sg"); /* Chinese (Singapore) */
735    test_tag_from_language!(tag_from_language_zh_mo, "ZHTM", "zh-mo"); /* Chinese (Macao) */
736    test_tag_from_language!(tag_from_language_zh_hant_mo, "ZHTM", "zh-hant-mo"); /* Chinese (Macao) */
737    test_tag_from_language!(tag_from_language_zh_hans_mo, "ZHS", "zh-hans-mo"); /* Chinese (Simplified, Macao) */
738    test_tag_from_language!(tag_from_language_ZHH, "ZHH", "zh-HK"); /* Chinese (Hong Kong) */
739    test_tag_from_language!(tag_from_language_zh_HanT_hK, "ZHH", "zH-HanT-hK"); /* Chinese (Hong Kong) */
740    test_tag_from_language!(tag_from_language_zh_HanS_hK, "ZHS", "zH-HanS-hK"); /* Chinese (Simplified, Hong Kong) */
741    test_tag_from_language!(tag_from_language_zh_tw, "ZHT", "zh-tw"); /* Chinese (Taiwan) */
742    test_tag_from_language!(tag_from_language_ZHS, "ZHS", "zh-Hans"); /* Chinese (Simplified) */
743    test_tag_from_language!(tag_from_language_ZHT, "ZHT", "zh-Hant"); /* Chinese (Traditional) */
744    test_tag_from_language!(tag_from_language_zh_xx, "ZHS", "zh-xx"); /* Chinese (Other) */
745    test_tag_from_language!(tag_from_language_zh_Hans_TW, "ZHS", "zh-Hans-TW");
746    test_tag_from_language!(tag_from_language_yue, "ZHH", "yue");
747    test_tag_from_language!(tag_from_language_yue_Hant, "ZHH", "yue-Hant");
748    test_tag_from_language!(tag_from_language_yue_Hans, "ZHS", "yue-Hans");
749    test_tag_from_language!(tag_from_language_ABC, "ABC", "abc");
750    test_tag_from_language!(tag_from_language_ABCD, "ABCD", "x-hbotabcd");
751    test_tag_from_language!(tag_from_language_asdf_asdf_wer_x_hbotabc_zxc, "ABC", "asdf-asdf-wer-x-hbotabc-zxc");
752    test_tag_from_language!(tag_from_language_asdf_asdf_wer_x_hbotabc, "ABC", "asdf-asdf-wer-x-hbotabc");
753    test_tag_from_language!(tag_from_language_asdf_asdf_wer_x_hbotabcd, "ABCD", "asdf-asdf-wer-x-hbotabcd");
754    test_tag_from_language!(tag_from_language_asdf_asdf_wer_x_hbot_zxc, "dflt", "asdf-asdf-wer-x-hbot-zxc");
755    test_tag_from_language!(tag_from_language_xy, "dflt", "xy");
756    test_tag_from_language!(tag_from_language_xyz, "XYZ", "xyz"); /* Unknown ISO 639-3 */
757    test_tag_from_language!(tag_from_language_xyz_qw, "XYZ", "xyz-qw"); /* Unknown ISO 639-3 */
758
759    /*
760     * Invalid input. The precise answer does not matter, as long as it
761     * does not crash or get into an infinite loop.
762     */
763    test_tag_from_language!(tag_from_language__fonipa, "IPPH", "-fonipa");
764
765    /*
766     * Tags that contain "-fonipa" as a substring but which do not contain
767     * the subtag "fonipa".
768     */
769    test_tag_from_language!(tag_from_language_en_fonipax, "ENG", "en-fonipax");
770    test_tag_from_language!(tag_from_language_en_x_fonipa, "ENG", "en-x-fonipa");
771    test_tag_from_language!(tag_from_language_en_a_fonipa, "ENG", "en-a-fonipa");
772    test_tag_from_language!(tag_from_language_en_a_qwe_b_fonipa, "ENG", "en-a-qwe-b-fonipa");
773
774    /* International Phonetic Alphabet */
775    test_tag_from_language!(tag_from_language_en_fonipa, "IPPH", "en-fonipa");
776    test_tag_from_language!(tag_from_language_en_fonipax_fonipa, "IPPH", "en-fonipax-fonipa");
777    test_tag_from_language!(tag_from_language_rm_ch_fonipa_sursilv_x_foobar, "IPPH", "rm-CH-fonipa-sursilv-x-foobar");
778    test_tag_from_language!(tag_from_language_IPPH, "IPPH", "und-fonipa");
779    test_tag_from_language!(tag_from_language_zh_fonipa, "IPPH", "zh-fonipa");
780
781    /* North American Phonetic Alphabet (Americanist Phonetic Notation) */
782    test_tag_from_language!(tag_from_language_en_fonnapa, "APPH", "en-fonnapa");
783    test_tag_from_language!(tag_from_language_chr_fonnapa, "APPH", "chr-fonnapa");
784    test_tag_from_language!(tag_from_language_APPH, "APPH", "und-fonnapa");
785
786    /* Uralic Phonetic Alphabet */
787    test_tag_from_language!(tag_from_language_fi_fonupa, "UPPH", "fi-fonupa");
788    test_tag_from_language!(tag_from_language_UPPH, "UPPH", "und-fonupa");
789
790    /* Khutsuri Georgian */
791    test_tag_from_language!(tag_from_language_ka_geok, "KGE", "ka-Geok");
792    test_tag_from_language!(tag_from_language_KGE, "KGE", "und-Geok");
793
794    /* Irish Traditional */
795    test_tag_from_language!(tag_from_language_IRT, "IRT", "ga-Latg");
796
797    /* Moldavian */
798    test_tag_from_language!(tag_from_language_MOL, "MOL", "ro-MD");
799
800    /* Polytonic Greek */
801    test_tag_from_language!(tag_from_language_PGR, "PGR", "el-polyton");
802    test_tag_from_language!(tag_from_language_el_CY_polyton, "PGR", "el-CY-polyton");
803
804    /* Estrangela Syriac */
805    test_tag_from_language!(tag_from_language_aii_Syre, "SYRE", "aii-Syre");
806    test_tag_from_language!(tag_from_language_de_Syre, "SYRE", "de-Syre");
807    test_tag_from_language!(tag_from_language_syr_Syre, "SYRE", "syr-Syre");
808    test_tag_from_language!(tag_from_language_und_Syre, "SYRE", "und-Syre");
809
810    /* Western Syriac */
811    test_tag_from_language!(tag_from_language_aii_Syrj, "SYRJ", "aii-Syrj");
812    test_tag_from_language!(tag_from_language_de_Syrj, "SYRJ", "de-Syrj");
813    test_tag_from_language!(tag_from_language_syr_Syrj, "SYRJ", "syr-Syrj");
814    test_tag_from_language!(tag_from_language_SYRJ, "SYRJ", "und-Syrj");
815
816    /* Eastern Syriac */
817    test_tag_from_language!(tag_from_language_aii_Syrn, "SYRN", "aii-Syrn");
818    test_tag_from_language!(tag_from_language_de_Syrn, "SYRN", "de-Syrn");
819    test_tag_from_language!(tag_from_language_syr_Syrn, "SYRN", "syr-Syrn");
820    test_tag_from_language!(tag_from_language_SYRN, "SYRN", "und-Syrn");
821
822    /* Test that x-hbot overrides the base language */
823    test_tag_from_language!(tag_from_language_fa_x_hbotabc_zxc, "ABC", "fa-x-hbotabc-zxc");
824    test_tag_from_language!(tag_from_language_fa_ir_x_hbotabc_zxc, "ABC", "fa-ir-x-hbotabc-zxc");
825    test_tag_from_language!(tag_from_language_zh_x_hbotabc_zxc, "ABC", "zh-x-hbotabc-zxc");
826    test_tag_from_language!(tag_from_language_zh_cn_x_hbotabc_zxc, "ABC", "zh-cn-x-hbotabc-zxc");
827    test_tag_from_language!(tag_from_language_zh_xy_x_hbotabc_zxc, "ABC", "zh-xy-x-hbotabc-zxc");
828    test_tag_from_language!(tag_from_language_xyz_xy_x_hbotabc_zxc, "ABC", "xyz-xy-x-hbotabc-zxc");
829
830    /* Unnormalized BCP 47 tags */
831    test_tag_from_language!(tag_from_language_ar_aao, "ARA", "ar-aao");
832    test_tag_from_language!(tag_from_language_art_lojban, "JBO", "art-lojban");
833    test_tag_from_language!(tag_from_language_kok_gom, "KOK", "kok-gom");
834    test_tag_from_language!(tag_from_language_i_lux, "LTZ", "i-lux");
835    test_tag_from_language!(tag_from_language_drh, "MNG", "drh");
836    test_tag_from_language!(tag_from_language_ar_ary1, "MOR", "ar-ary");
837    test_tag_from_language!(tag_from_language_ar_ary_DZ, "MOR", "ar-ary-DZ");
838    test_tag_from_language!(tag_from_language_no_bok, "NOR", "no-bok");
839    test_tag_from_language!(tag_from_language_no_nyn, "NYN", "no-nyn");
840    test_tag_from_language!(tag_from_language_i_hak, "ZHS", "i-hak");
841    test_tag_from_language!(tag_from_language_zh_guoyu, "ZHS", "zh-guoyu");
842    test_tag_from_language!(tag_from_language_zh_min, "ZHS", "zh-min");
843    test_tag_from_language!(tag_from_language_zh_min_nan, "ZHS", "zh-min-nan");
844    test_tag_from_language!(tag_from_language_zh_xiang, "ZHS", "zh-xiang");
845
846    /* BCP 47 tags that look similar to unrelated language system tags */
847    test_tag_from_language!(tag_from_language_als, "SQI", "als");
848    test_tag_from_language!(tag_from_language_far, "dflt", "far");
849
850    /* A UN M.49 region code, not an extended language subtag */
851    test_tag_from_language!(tag_from_language_ar_001, "ARA", "ar-001");
852
853    /* An invalid tag */
854    test_tag_from_language!(tag_from_language_invalid, "TRK", "tr@foo=bar");
855
856    macro_rules! test_tags {
857        ($name:ident, $script:expr, $lang:expr, $scripts:expr, $langs:expr) => {
858            #[test]
859            fn $name() {
860                let (scripts, languages) =
861                    Script::tags_for_language($script, Language::new($lang).as_ref());
862
863                let exp_scripts: Vec<Tag> = $scripts.iter().map(|v| Tag::from_bytes_lossy(*v)).collect();
864                let exp_langs: Vec<Tag> = $langs.iter().map(|v| Tag::from_bytes_lossy(*v)).collect();
865
866                assert_eq!(exp_scripts, scripts.as_slice());
867                assert_eq!(exp_langs, languages.as_slice());
868            }
869        };
870    }
871
872    test_tags!(tag_full_en, None, "en", &[], &[b"ENG"]);
873    test_tags!(tag_full_en_x_hbscdflt, None, "en-x-hbscdflt", &[b"DFLT"], &[b"ENG"]);
874    test_tags!(tag_full_en_latin, Some(Script::LATIN), "en", &[b"latn"], &[b"ENG"]);
875    test_tags!(tag_full_und_fonnapa, None, "und-fonnapa", &[], &[b"APPH"]);
876    test_tags!(tag_full_en_fonnapa, None, "en-fonnapa", &[], &[b"APPH"]);
877    test_tags!(tag_full_und_fonupa, None, "und-fonupa", &[], &[b"UPPH"]);
878    test_tags!(tag_full_fi_fonupa, None, "fi-fonupa", &[], &[b"UPPH"]);
879    test_tags!(tag_full_x_hbot1234_hbsc5678, None, "x-hbot1234-hbsc5678", &[b"5678"], &[b"1234"]);
880    test_tags!(tag_full_x_hbsc5678_hbot1234, None, "x-hbsc5678-hbot1234", &[b"5678"], &[b"1234"]);
881    test_tags!(tag_hex_mont, Some(Script::MYANMAR), "x-hbot-4d4f4e54", &[b"mym2", b"mymr"], &[b"MONT"]);
882    test_tags!(tag_hex_uppercase, None, "X-HBOT-4D4F4E54", &[], &[b"MONT"]);
883    test_tags!(tag_hex_language_override, None, "my-x-hbot-4d4f4e54-zxc", &[], &[b"MONT"]);
884    test_tags!(tag_hex_script_override, Some(Script::LATIN), "en-x-hbsc-64657633", &[b"dev3"], &[b"ENG"]);
885    test_tags!(tag_hex_language_and_script, None, "x-hbot-4d4f4e54-hbsc-6d796d32", &[b"mym2"], &[b"MONT"]);
886    test_tags!(tag_hex_script_and_language, None, "x-hbsc-6d796d32-hbot-4d4f4e54", &[b"mym2"], &[b"MONT"]);
887    test_tags!(tag_hex_preserves_case_and_punctuation, None, "x-hbot-41686121-hbsc-41686121", &[b"Aha!"], &[b"Aha!"]);
888    test_tags!(tag_hex_preserves_spaces, None, "x-hbot-41424320-hbsc-79692020", &[b"yi  "], &[b"ABC "]);
889    test_tags!(tag_hex_preserves_arbitrary_bytes, None, "x-hbot-00ff80ab-hbsc-00ff80ab", &[b"\x00\xff\x80\xab"], &[b"\x00\xff\x80\xab"]);
890    test_tags!(tag_hex_preserves_zero, None, "x-hbot-00000000-hbsc-00000000", &[b"\0\0\0\0"], &[b"\0\0\0\0"]);
891    test_tags!(tag_hex_default_uppercase, None, "x-hbot-44464c54-hbsc-44464c54", &[b"dflt"], &[b"dflt"]);
892    test_tags!(tag_hex_default_lowercase, None, "x-hbot-64666c74-hbsc-64666c74", &[b"DFLT"], &[b"DFLT"]);
893    test_tags!(tag_hex_ignores_trailing_digits, None, "x-hbot-326c6f6e67-hbsc-326c6f6e67", &[b"2lon"], &[b"2lon"]);
894    test_tags!(tag_hex_first_override, None, "fa-x-hbot-41686121-hbotabc-zxc", &[], &[b"Aha!"]);
895    test_tags!(tag_text_first_override, None, "fa-x-hbotabc-hbot-41686121-zxc", &[], &[b"ABC"]);
896    test_tags!(tag_text_mont, None, "x-hbotmont", &[], &[b"MONT"]);
897
898    #[test]
899    fn tag_hex_invalid() {
900        for hex in [
901            "", "1", "1a", "414243", "4142432", "1a2b3c4x", "4d4f-4e54",
902            "+d4f4e54", "-d4f4e54", "4d4f4e5\u{e9}",
903        ] {
904            let language = alloc::format!("en-x-hbot-{hex}-hbsc-{hex}");
905            let (scripts, languages) = Script::tags_for_language(
906                Some(Script::LATIN), Language::new(&language).as_ref(),
907            );
908            assert_eq!(scripts.as_slice(), &[Tag::new(b"latn")], "{language}");
909            assert_eq!(languages.as_slice(), &[Tag::new(b"ENG ")], "{language}");
910
911            let language = alloc::format!("x-hbot-{hex}-hbsc-{hex}");
912            let (scripts, languages) =
913                Script::tags_for_language(None, Language::new(&language).as_ref());
914            assert!(scripts.as_slice().is_empty(), "{language}");
915            assert!(languages.as_slice().is_empty(), "{language}");
916        }
917    }
918
919    test_tags!(tag_full_ml, Some(Script::MALAYALAM), "ml", &[b"mlm3", b"mlm2", b"mlym"], &[b"MAL", b"MLR"]);
920    test_tags!(tag_full_xyz, None, "xyz", &[], &[b"XYZ"]);
921    test_tags!(tag_full_xy, None, "xy", &[], &[]);
922}