Debian Codegraph @

third_party/rust/oxilangtag/src/lib.rs

raw
1 #![doc = include_str!("../README.md")]
2 #![deny(unsafe_code)]
3
4 #[cfg(feature = "serde")]
5 use serde::{Deserialize, Deserializer, Serialize, Serializer};
6 use std::borrow::{Borrow, Cow};
7 use std::cmp::Ordering;
8 use std::error::Error;
9 use std::fmt;
10 use std::hash::{Hash, Hasher};
11 use std::iter::once;
12 use std::ops::Deref;
13 use std::str::{FromStr, Split};
14
15 /// A [RFC 5646](https://tools.ietf.org/html/rfc5646) language tag.
16 ///
17 /// ```
18 /// use oxilangtag::LanguageTag;
19 ///
20 /// let language_tag = LanguageTag::parse("en-us").unwrap();
21 /// assert_eq!(language_tag.into_inner(), "en-us")
22 /// ```
23 #[derive(Copy, Clone)]
24 pub struct LanguageTag<T> {
25 tag: T,
26 positions: TagElementsPositions,
27 }
28
29 impl<T: Deref<Target = str>> LanguageTag<T> {
30 /// Parses a language tag acccording to [RFC 5646](https://tools.ietf.org/html/rfc5646).
31 /// and checks if the tag is ["well-formed"](https://tools.ietf.org/html/rfc5646#section-2.2.9).
32 ///
33 /// This operation keeps internally the `tag` parameter and does not allocate on the heap.
34 ///
35 /// ```
36 /// use oxilangtag::LanguageTag;
37 ///
38 /// let language_tag = LanguageTag::parse("en-us").unwrap();
39 /// assert_eq!(language_tag.into_inner(), "en-us")
40 /// ```
41 pub fn parse(tag: T) -> Result<Self, LanguageTagParseError> {
42 let positions = parse_language_tag(&tag, &mut VoidOutputBuffer::default())?;
43 Ok(Self { tag, positions })
44 }
45
46 /// Returns the underlying language tag representation.
47 #[inline]
48 pub fn as_str(&self) -> &str {
49 &self.tag
50 }
51
52 /// Returns the underlying language tag representation.
53 #[inline]
54 pub fn into_inner(self) -> T {
55 self.tag
56 }
57
58 /// Returns the [primary language subtag](https://tools.ietf.org/html/rfc5646#section-2.2.1).
59 ///
60 /// ```
61 /// use oxilangtag::LanguageTag;
62 ///
63 /// let language_tag = LanguageTag::parse("zh-cmn-Hans-CN").unwrap();
64 /// assert_eq!(language_tag.primary_language(), "zh");
65 /// ```
66 #[inline]
67 pub fn primary_language(&self) -> &str {
68 &self.tag[..self.positions.language_end]
69 }
70
71 /// Returns the [extended language subtags](https://tools.ietf.org/html/rfc5646#section-2.2.2).
72 ///
73 /// Valid language tags have at most one extended language.
74 ///
75 /// ```
76 /// use oxilangtag::LanguageTag;
77 ///
78 /// let language_tag = LanguageTag::parse("zh-cmn-Hans-CN").unwrap();
79 /// assert_eq!(language_tag.extended_language(), Some("cmn"));
80 /// ```
81 #[inline]
82 pub fn extended_language(&self) -> Option<&str> {
83 if self.positions.language_end == self.positions.extlang_end {
84 None
85 } else {
86 Some(&self.tag[self.positions.language_end + 1..self.positions.extlang_end])
87 }
88 }
89
90 /// Iterates on the [extended language subtags](https://tools.ietf.org/html/rfc5646#section-2.2.2).
91 ///
92 /// Valid language tags have at most one extended language.
93 ///
94 /// ```
95 /// use oxilangtag::LanguageTag;
96 ///
97 /// let language_tag = LanguageTag::parse("zh-cmn-Hans-CN").unwrap();
98 /// assert_eq!(language_tag.extended_language_subtags().collect::<Vec<_>>(), vec!["cmn"]);
99 /// ```
100 #[inline]
101 pub fn extended_language_subtags(&self) -> impl Iterator<Item = &str> {
102 self.extended_language().unwrap_or("").split_terminator('-')
103 }
104
105 /// Returns the [primary language subtag](https://tools.ietf.org/html/rfc5646#section-2.2.1)
106 /// and its [extended language subtags](https://tools.ietf.org/html/rfc5646#section-2.2.2).
107 ///
108 /// ```
109 /// use oxilangtag::LanguageTag;
110 ///
111 /// let language_tag = LanguageTag::parse("zh-cmn-Hans-CN").unwrap();
112 /// assert_eq!(language_tag.full_language(), "zh-cmn");
113 /// ```
114 #[inline]
115 pub fn full_language(&self) -> &str {
116 &self.tag[..self.positions.extlang_end]
117 }
118
119 /// Returns the [script subtag](https://tools.ietf.org/html/rfc5646#section-2.2.3).
120 ///
121 /// ```
122 /// use oxilangtag::LanguageTag;
123 ///
124 /// let language_tag = LanguageTag::parse("zh-cmn-Hans-CN").unwrap();
125 /// assert_eq!(language_tag.script(), Some("Hans"));
126 /// ```
127 #[inline]
128 pub fn script(&self) -> Option<&str> {
129 if self.positions.extlang_end == self.positions.script_end {
130 None
131 } else {
132 Some(&self.tag[self.positions.extlang_end + 1..self.positions.script_end])
133 }
134 }
135
136 /// Returns the [region subtag](https://tools.ietf.org/html/rfc5646#section-2.2.4).
137 ///
138 /// ```
139 /// use oxilangtag::LanguageTag;
140 ///
141 /// let language_tag = LanguageTag::parse("zh-cmn-Hans-CN").unwrap();
142 /// assert_eq!(language_tag.region(), Some("CN"));
143 /// ```
144 #[inline]
145 pub fn region(&self) -> Option<&str> {
146 if self.positions.script_end == self.positions.region_end {
147 None
148 } else {
149 Some(&self.tag[self.positions.script_end + 1..self.positions.region_end])
150 }
151 }
152
153 /// Returns the [variant subtags](https://tools.ietf.org/html/rfc5646#section-2.2.5).
154 ///
155 /// ```
156 /// use oxilangtag::LanguageTag;
157 ///
158 /// let language_tag = LanguageTag::parse("zh-Latn-TW-pinyin").unwrap();
159 /// assert_eq!(language_tag.variant(), Some("pinyin"));
160 /// ```
161 #[inline]
162 pub fn variant(&self) -> Option<&str> {
163 if self.positions.region_end == self.positions.variant_end {
164 None
165 } else {
166 Some(&self.tag[self.positions.region_end + 1..self.positions.variant_end])
167 }
168 }
169
170 /// Iterates on the [variant subtags](https://tools.ietf.org/html/rfc5646#section-2.2.5).
171 ///
172 /// ```
173 /// use oxilangtag::LanguageTag;
174 ///
175 /// let language_tag = LanguageTag::parse("zh-Latn-TW-pinyin").unwrap();
176 /// assert_eq!(language_tag.variant_subtags().collect::<Vec<_>>(), vec!["pinyin"]);
177 /// ```
178 #[inline]
179 pub fn variant_subtags(&self) -> impl Iterator<Item = &str> {
180 self.variant().unwrap_or("").split_terminator('-')
181 }
182
183 /// Returns the [extension subtags](https://tools.ietf.org/html/rfc5646#section-2.2.6).
184 ///
185 /// ```
186 /// use oxilangtag::LanguageTag;
187 ///
188 /// let language_tag = LanguageTag::parse("de-DE-u-co-phonebk").unwrap();
189 /// assert_eq!(language_tag.extension(), Some("u-co-phonebk"));
190 /// ```
191 #[inline]
192 pub fn extension(&self) -> Option<&str> {
193 if self.positions.variant_end == self.positions.extension_end {
194 None
195 } else {
196 Some(&self.tag[self.positions.variant_end + 1..self.positions.extension_end])
197 }
198 }
199
200 /// Iterates on the [extension subtags](https://tools.ietf.org/html/rfc5646#section-2.2.6).
201 ///
202 /// ```
203 /// use oxilangtag::LanguageTag;
204 ///
205 /// let language_tag = LanguageTag::parse("de-DE-u-co-phonebk").unwrap();
206 /// assert_eq!(language_tag.extension_subtags().collect::<Vec<_>>(), vec![('u', "co-phonebk")]);
207 /// ```
208 #[inline]
209 pub fn extension_subtags(&self) -> impl Iterator<Item = (char, &str)> {
210 match self.extension() {
211 Some(parts) => ExtensionsIterator::new(parts),
212 None => ExtensionsIterator::new(""),
213 }
214 }
215
216 /// Returns the [private use subtags](https://tools.ietf.org/html/rfc5646#section-2.2.7).
217 ///
218 /// ```
219 /// use oxilangtag::LanguageTag;
220 ///
221 /// let language_tag = LanguageTag::parse("de-x-foo-bar").unwrap();
222 /// assert_eq!(language_tag.private_use(), Some("x-foo-bar"));
223 /// ```
224 #[inline]
225 pub fn private_use(&self) -> Option<&str> {
226 if self.tag.starts_with("x-") {
227 Some(&self.tag)
228 } else if self.positions.extension_end == self.tag.len() {
229 None
230 } else {
231 Some(&self.tag[self.positions.extension_end + 1..])
232 }
233 }
234
235 /// Iterates on the [private use subtags](https://tools.ietf.org/html/rfc5646#section-2.2.7).
236 ///
237 /// ```
238 /// use oxilangtag::LanguageTag;
239 ///
240 /// let language_tag = LanguageTag::parse("de-x-foo-bar").unwrap();
241 /// assert_eq!(language_tag.private_use_subtags().collect::<Vec<_>>(), vec!["foo", "bar"]);
242 /// ```
243 #[inline]
244 pub fn private_use_subtags(&self) -> impl Iterator<Item = &str> {
245 self.private_use()
246 .map(|part| &part[2..])
247 .unwrap_or("")
248 .split_terminator('-')
249 }
250 }
251
252 impl LanguageTag<String> {
253 /// Parses a language tag acccording to [RFC 5646](https://tools.ietf.org/html/rfc5646)
254 /// and normalizes its case.
255 ///
256 /// This parser accepts the language tags that are "well-formed" according to
257 /// [RFC 5646](https://tools.ietf.org/html/rfc5646#section-2.2.9).
258 ///
259 /// This operation does heap allocation.
260 ///
261 /// ```
262 /// use oxilangtag::LanguageTag;
263 ///
264 /// let language_tag = LanguageTag::parse_and_normalize("en-us").unwrap();
265 /// assert_eq!(language_tag.into_inner(), "en-US")
266 /// ```
267 pub fn parse_and_normalize(tag: &str) -> Result<Self, LanguageTagParseError> {
268 let mut output_buffer = String::with_capacity(tag.len());
269 let positions = parse_language_tag(tag, &mut output_buffer)?;
270 Ok(Self {
271 tag: output_buffer,
272 positions,
273 })
274 }
275 }
276
277 impl<Lft: PartialEq<Rhs>, Rhs> PartialEq<LanguageTag<Rhs>> for LanguageTag<Lft> {
278 #[inline]
279 fn eq(&self, other: &LanguageTag<Rhs>) -> bool {
280 self.tag.eq(&other.tag)
281 }
282 }
283
284 impl<T: PartialEq<str>> PartialEq<str> for LanguageTag<T> {
285 #[inline]
286 fn eq(&self, other: &str) -> bool {
287 self.tag.eq(other)
288 }
289 }
290
291 impl<'a, T: PartialEq<&'a str>> PartialEq<&'a str> for LanguageTag<T> {
292 #[inline]
293 fn eq(&self, other: &&'a str) -> bool {
294 self.tag.eq(other)
295 }
296 }
297
298 impl<T: PartialEq<String>> PartialEq<String> for LanguageTag<T> {
299 #[inline]
300 fn eq(&self, other: &String) -> bool {
301 self.tag.eq(other)
302 }
303 }
304
305 impl<'a, T: PartialEq<Cow<'a, str>>> PartialEq<Cow<'a, str>> for LanguageTag<T> {
306 #[inline]
307 fn eq(&self, other: &Cow<'a, str>) -> bool {
308 self.tag.eq(other)
309 }
310 }
311
312 impl<T: PartialEq<str>> PartialEq<LanguageTag<T>> for str {
313 #[inline]
314 fn eq(&self, other: &LanguageTag<T>) -> bool {
315 other.tag.eq(self)
316 }
317 }
318
319 impl<'a, T: PartialEq<&'a str>> PartialEq<LanguageTag<T>> for &'a str {
320 #[inline]
321 fn eq(&self, other: &LanguageTag<T>) -> bool {
322 other.tag.eq(self)
323 }
324 }
325
326 impl<T: PartialEq<String>> PartialEq<LanguageTag<T>> for String {
327 #[inline]
328 fn eq(&self, other: &LanguageTag<T>) -> bool {
329 other.tag.eq(self)
330 }
331 }
332
333 impl<'a, T: PartialEq<Cow<'a, str>>> PartialEq<LanguageTag<T>> for Cow<'a, str> {
334 #[inline]
335 fn eq(&self, other: &LanguageTag<T>) -> bool {
336 other.tag.eq(self)
337 }
338 }
339
340 impl<T: Eq> Eq for LanguageTag<T> {}
341
342 impl<T: Hash> Hash for LanguageTag<T> {
343 #[inline]
344 fn hash<H: Hasher>(&self, state: &mut H) {
345 self.tag.hash(state)
346 }
347 }
348
349 impl<T: PartialOrd> PartialOrd for LanguageTag<T> {
350 #[inline]
351 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
352 self.tag.partial_cmp(&other.tag)
353 }
354 }
355
356 impl<T: Ord> Ord for LanguageTag<T> {
357 #[inline]
358 fn cmp(&self, other: &Self) -> Ordering {
359 self.tag.cmp(&other.tag)
360 }
361 }
362
363 impl<T: Deref<Target = str>> Deref for LanguageTag<T> {
364 type Target = str;
365
366 #[inline]
367 fn deref(&self) -> &str {
368 self.tag.deref()
369 }
370 }
371
372 impl<T: AsRef<str>> AsRef<str> for LanguageTag<T> {
373 #[inline]
374 fn as_ref(&self) -> &str {
375 self.tag.as_ref()
376 }
377 }
378
379 impl<T: Borrow<str>> Borrow<str> for LanguageTag<T> {
380 #[inline]
381 fn borrow(&self) -> &str {
382 self.tag.borrow()
383 }
384 }
385
386 impl<T: fmt::Debug> fmt::Debug for LanguageTag<T> {
387 #[inline]
388 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
389 self.tag.fmt(f)
390 }
391 }
392
393 impl<T: fmt::Display> fmt::Display for LanguageTag<T> {
394 #[inline]
395 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
396 self.tag.fmt(f)
397 }
398 }
399
400 impl FromStr for LanguageTag<String> {
401 type Err = LanguageTagParseError;
402
403 #[inline]
404 fn from_str(tag: &str) -> Result<Self, LanguageTagParseError> {
405 Self::parse_and_normalize(tag)
406 }
407 }
408
409 impl<'a> From<LanguageTag<&'a str>> for LanguageTag<String> {
410 #[inline]
411 fn from(tag: LanguageTag<&'a str>) -> Self {
412 Self {
413 tag: tag.tag.into(),
414 positions: tag.positions,
415 }
416 }
417 }
418
419 impl<'a> From<LanguageTag<Cow<'a, str>>> for LanguageTag<String> {
420 #[inline]
421 fn from(tag: LanguageTag<Cow<'a, str>>) -> Self {
422 Self {
423 tag: tag.tag.into(),
424 positions: tag.positions,
425 }
426 }
427 }
428
429 impl From<LanguageTag<Box<str>>> for LanguageTag<String> {
430 #[inline]
431 fn from(tag: LanguageTag<Box<str>>) -> Self {
432 Self {
433 tag: tag.tag.into(),
434 positions: tag.positions,
435 }
436 }
437 }
438
439 impl<'a> From<LanguageTag<&'a str>> for LanguageTag<Cow<'a, str>> {
440 #[inline]
441 fn from(tag: LanguageTag<&'a str>) -> Self {
442 Self {
443 tag: tag.tag.into(),
444 positions: tag.positions,
445 }
446 }
447 }
448
449 impl<'a> From<LanguageTag<String>> for LanguageTag<Cow<'a, str>> {
450 #[inline]
451 fn from(tag: LanguageTag<String>) -> Self {
452 Self {
453 tag: tag.tag.into(),
454 positions: tag.positions,
455 }
456 }
457 }
458
459 #[cfg(feature = "serde")]
460 impl<T: Serialize> Serialize for LanguageTag<T> {
461 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
462 self.tag.serialize(serializer)
463 }
464 }
465
466 #[cfg(feature = "serde")]
467 impl<'de, T: Deref<Target = str> + Deserialize<'de>> Deserialize<'de> for LanguageTag<T> {
468 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<LanguageTag<T>, D::Error> {
469 use serde::de::Error;
470
471 Self::parse(T::deserialize(deserializer)?).map_err(D::Error::custom)
472 }
473 }
474
475 /// An error raised during [`LanguageTag`](struct.LanguageTag.html) validation.
476 #[derive(Debug)]
477 pub struct LanguageTagParseError {
478 kind: TagParseErrorKind,
479 }
480
481 impl fmt::Display for LanguageTagParseError {
482 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
483 match self.kind {
484 TagParseErrorKind::EmptyExtension => {
485 write!(f, "If an extension subtag is present, it must not be empty")
486 }
487 TagParseErrorKind::EmptyPrivateUse => {
488 write!(f, "If the `x` subtag is present, it must not be empty")
489 }
490 TagParseErrorKind::ForbiddenChar => {
491 write!(f, "The langtag contains a char not allowed")
492 }
493 TagParseErrorKind::InvalidSubtag => write!(
494 f,
495 "A subtag fails to parse, it does not match any other subtags"
496 ),
497 TagParseErrorKind::InvalidLanguage => write!(f, "The given language subtag is invalid"),
498 TagParseErrorKind::SubtagTooLong => {
499 write!(f, "A subtag may be eight characters in length at maximum")
500 }
501 TagParseErrorKind::EmptySubtag => write!(f, "A subtag should not be empty"),
502 TagParseErrorKind::TooManyExtlangs => {
503 write!(f, "At maximum three extlangs are allowed")
504 }
505 }
506 }
507 }
508
509 impl Error for LanguageTagParseError {}
510
511 #[derive(Debug)]
512 enum TagParseErrorKind {
513 /// If an extension subtag is present, it must not be empty.
514 EmptyExtension,
515 /// If the `x` subtag is present, it must not be empty.
516 EmptyPrivateUse,
517 /// The langtag contains a char that is not A-Z, a-z, 0-9 or the dash.
518 ForbiddenChar,
519 /// A subtag fails to parse, it does not match any other subtags.
520 InvalidSubtag,
521 /// The given language subtag is invalid.
522 InvalidLanguage,
523 /// A subtag may be eight characters in length at maximum.
524 SubtagTooLong,
525 /// A subtag should not be empty.
526 EmptySubtag,
527 /// At maximum three extlangs are allowed, but zero to one extlangs are preferred.
528 TooManyExtlangs,
529 }
530
531 #[derive(Copy, Clone, Debug)]
532 struct TagElementsPositions {
533 language_end: usize,
534 extlang_end: usize,
535 script_end: usize,
536 region_end: usize,
537 variant_end: usize,
538 extension_end: usize,
539 }
540
541 trait OutputBuffer: Extend<char> {
542 fn push(&mut self, c: char);
543
544 fn push_str(&mut self, s: &str);
545 }
546
547 #[derive(Default)]
548 struct VoidOutputBuffer {}
549
550 impl OutputBuffer for VoidOutputBuffer {
551 #[inline]
552 fn push(&mut self, _: char) {}
553
554 #[inline]
555 fn push_str(&mut self, _: &str) {}
556 }
557
558 impl Extend<char> for VoidOutputBuffer {
559 #[inline]
560 fn extend<T: IntoIterator<Item = char>>(&mut self, _: T) {}
561 }
562
563 impl OutputBuffer for String {
564 #[inline]
565 fn push(&mut self, c: char) {
566 self.push(c);
567 }
568
569 #[inline]
570 fn push_str(&mut self, s: &str) {
571 self.push_str(s);
572 }
573 }
574
575 /// Parses language tag following [the RFC5646 grammar](https://tools.ietf.org/html/rfc5646#section-2.1)
576 fn parse_language_tag(
577 input: &str,
578 output: &mut impl OutputBuffer,
579 ) -> Result<TagElementsPositions, LanguageTagParseError> {
580 //grandfathered tags
581 if let Some(tag) = GRANDFATHEREDS
582 .iter()
583 .find(|record| record.eq_ignore_ascii_case(input))
584 {
585 output.push_str(tag);
586 Ok(TagElementsPositions {
587 language_end: tag.len(),
588 extlang_end: tag.len(),
589 script_end: tag.len(),
590 region_end: tag.len(),
591 variant_end: tag.len(),
592 extension_end: tag.len(),
593 })
594 } else if input.starts_with("x-") || input.starts_with("X-") {
595 // private use
596 if !is_alphanumeric_or_dash(input) {
597 Err(LanguageTagParseError {
598 kind: TagParseErrorKind::ForbiddenChar,
599 })
600 } else if input.len() == 2 {
601 Err(LanguageTagParseError {
602 kind: TagParseErrorKind::EmptyPrivateUse,
603 })
604 } else {
605 output.extend(input.chars().map(|c| c.to_ascii_lowercase()));
606 Ok(TagElementsPositions {
607 language_end: input.len(),
608 extlang_end: input.len(),
609 script_end: input.len(),
610 region_end: input.len(),
611 variant_end: input.len(),
612 extension_end: input.len(),
613 })
614 }
615 } else {
616 parse_langtag(input, output)
617 }
618 }
619
620 /// Handles normal tags.
621 fn parse_langtag(
622 input: &str,
623 output: &mut impl OutputBuffer,
624 ) -> Result<TagElementsPositions, LanguageTagParseError> {
625 #[derive(PartialEq, Eq)]
626 enum State {
627 Start,
628 AfterLanguage,
629 AfterExtLang,
630 AfterScript,
631 AfterRegion,
632 InExtension { expected: bool },
633 InPrivateUse { expected: bool },
634 }
635
636 let mut state = State::Start;
637 let mut language_end = 0;
638 let mut extlang_end = 0;
639 let mut script_end = 0;
640 let mut region_end = 0;
641 let mut variant_end = 0;
642 let mut extension_end = 0;
643 let mut extlangs_count = 0;
644 for (subtag, end) in SubTagIterator::new(input) {
645 if subtag.is_empty() {
646 return Err(LanguageTagParseError {
647 kind: TagParseErrorKind::EmptySubtag,
648 });
649 }
650 if subtag.len() > 8 {
651 return Err(LanguageTagParseError {
652 kind: TagParseErrorKind::SubtagTooLong,
653 });
654 }
655 if state == State::Start {
656 // Primary language
657 if subtag.len() < 2 || !is_alphabetic(subtag) {
658 return Err(LanguageTagParseError {
659 kind: TagParseErrorKind::InvalidLanguage,
660 });
661 }
662 language_end = end;
663 output.extend(to_lowercase(subtag));
664 if subtag.len() < 4 {
665 // extlangs are only allowed for short language tags
666 state = State::AfterLanguage;
667 } else {
668 state = State::AfterExtLang;
669 }
670 } else if let State::InPrivateUse { .. } = state {
671 if !is_alphanumeric(subtag) {
672 return Err(LanguageTagParseError {
673 kind: TagParseErrorKind::InvalidSubtag,
674 });
675 }
676 output.push('-');
677 output.extend(to_lowercase(subtag));
678 state = State::InPrivateUse { expected: false };
679 } else if subtag == "x" || subtag == "X" {
680 // We make sure extension is found
681 if let State::InExtension { expected: true } = state {
682 return Err(LanguageTagParseError {
683 kind: TagParseErrorKind::EmptyExtension,
684 });
685 }
686 output.push('-');
687 output.push('x');
688 state = State::InPrivateUse { expected: true };
689 } else if subtag.len() == 1 && is_alphanumeric(subtag) {
690 // We make sure extension is found
691 if let State::InExtension { expected: true } = state {
692 return Err(LanguageTagParseError {
693 kind: TagParseErrorKind::EmptyExtension,
694 });
695 }
696 let extension_tag = subtag.chars().next().unwrap().to_ascii_lowercase();
697 output.push('-');
698 output.push(extension_tag);
699 state = State::InExtension { expected: true };
700 } else if let State::InExtension { .. } = state {
701 if !is_alphanumeric(subtag) {
702 return Err(LanguageTagParseError {
703 kind: TagParseErrorKind::InvalidSubtag,
704 });
705 }
706 extension_end = end;
707 output.push('-');
708 output.extend(to_lowercase(subtag));
709 state = State::InExtension { expected: false };
710 } else if state == State::AfterLanguage && subtag.len() == 3 && is_alphabetic(subtag) {
711 extlangs_count += 1;
712 if extlangs_count > 3 {
713 return Err(LanguageTagParseError {
714 kind: TagParseErrorKind::TooManyExtlangs,
715 });
716 }
717 // valid extlangs
718 extlang_end = end;
719 output.push('-');
720 output.extend(to_lowercase(subtag));
721 } else if (state == State::AfterLanguage || state == State::AfterExtLang)
722 && subtag.len() == 4
723 && is_alphabetic(subtag)
724 {
725 // Script
726 script_end = end;
727 output.push('-');
728 output.extend(to_uppercase_first(subtag));
729 state = State::AfterScript;
730 } else if (state == State::AfterLanguage
731 || state == State::AfterExtLang
732 || state == State::AfterScript)
733 && (subtag.len() == 2 && is_alphabetic(subtag)
734 || subtag.len() == 3 && is_numeric(subtag))
735 {
736 // Region
737 region_end = end;
738 output.push('-');
739 output.extend(to_uppercase(subtag));
740 state = State::AfterRegion;
741 } else if (state == State::AfterLanguage
742 || state == State::AfterExtLang
743 || state == State::AfterScript
744 || state == State::AfterRegion)
745 && is_alphanumeric(subtag)
746 && (subtag.len() >= 5 && is_alphabetic(&subtag[0..1])
747 || subtag.len() >= 4 && is_numeric(&subtag[0..1]))
748 {
749 // Variant
750 variant_end = end;
751 output.push('-');
752 output.extend(to_lowercase(subtag));
753 state = State::AfterRegion;
754 } else {
755 return Err(LanguageTagParseError {
756 kind: TagParseErrorKind::InvalidSubtag,
757 });
758 }
759 }
760
761 //We make sure we are in a correct final state
762 if let State::InExtension { expected: true } = state {
763 return Err(LanguageTagParseError {
764 kind: TagParseErrorKind::EmptyExtension,
765 });
766 }
767 if let State::InPrivateUse { expected: true } = state {
768 return Err(LanguageTagParseError {
769 kind: TagParseErrorKind::EmptyPrivateUse,
770 });
771 }
772
773 //We make sure we have not skipped anyone
774 if extlang_end < language_end {
775 extlang_end = language_end;
776 }
777 if script_end < extlang_end {
778 script_end = extlang_end;
779 }
780 if region_end < script_end {
781 region_end = script_end;
782 }
783 if variant_end < region_end {
784 variant_end = region_end;
785 }
786 if extension_end < variant_end {
787 extension_end = variant_end;
788 }
789
790 Ok(TagElementsPositions {
791 language_end,
792 extlang_end,
793 script_end,
794 region_end,
795 variant_end,
796 extension_end,
797 })
798 }
799
800 struct ExtensionsIterator<'a> {
801 input: &'a str,
802 }
803
804 impl<'a> ExtensionsIterator<'a> {
805 fn new(input: &'a str) -> Self {
806 Self { input }
807 }
808 }
809
810 impl<'a> Iterator for ExtensionsIterator<'a> {
811 type Item = (char, &'a str);
812
813 fn next(&mut self) -> Option<(char, &'a str)> {
814 let mut parts_iterator = self.input.split_terminator('-');
815 let singleton = parts_iterator.next()?.chars().next().unwrap();
816 let mut content_size: usize = 2;
817 for part in parts_iterator {
818 if part.len() == 1 {
819 let content = &self.input[2..content_size - 1];
820 self.input = &self.input[content_size..];
821 return Some((singleton, content));
822 } else {
823 content_size += part.len() + 1;
824 }
825 }
826 let result = self.input.get(2..).map(|content| (singleton, content));
827 self.input = "";
828 result
829 }
830 }
831
832 struct SubTagIterator<'a> {
833 split: Split<'a, char>,
834 position: usize,
835 }
836
837 impl<'a> SubTagIterator<'a> {
838 #[inline]
839 fn new(input: &'a str) -> Self {
840 Self {
841 split: input.split('-'),
842 position: 0,
843 }
844 }
845 }
846
847 impl<'a> Iterator for SubTagIterator<'a> {
848 type Item = (&'a str, usize);
849
850 #[inline]
851 fn next(&mut self) -> Option<(&'a str, usize)> {
852 let tag = self.split.next()?;
853 let tag_end = self.position + tag.len();
854 self.position = tag_end + 1;
855 Some((tag, tag_end))
856 }
857 }
858
859 #[inline]
860 fn is_alphabetic(s: &str) -> bool {
861 s.chars().all(|x| x.is_ascii_alphabetic())
862 }
863
864 #[inline]
865 fn is_numeric(s: &str) -> bool {
866 s.chars().all(|x| x.is_ascii_digit())
867 }
868
869 #[inline]
870 fn is_alphanumeric(s: &str) -> bool {
871 s.chars().all(|x| x.is_ascii_alphanumeric())
872 }
873
874 #[inline]
875 fn is_alphanumeric_or_dash(s: &str) -> bool {
876 s.chars().all(|x| x.is_ascii_alphanumeric() || x == '-')
877 }
878
879 #[inline]
880 fn to_uppercase(s: &str) -> impl Iterator<Item = char> + '_ {
881 s.chars().map(|c| c.to_ascii_uppercase())
882 }
883
884 // Beware: panics if s.len() == 0 (should never happen in our code)
885 #[inline]
886 fn to_uppercase_first(s: &str) -> impl Iterator<Item = char> + '_ {
887 let mut chars = s.chars();
888 once(chars.next().unwrap().to_ascii_uppercase()).chain(chars.map(|c| c.to_ascii_lowercase()))
889 }
890
891 #[inline]
892 fn to_lowercase(s: &str) -> impl Iterator<Item = char> + '_ {
893 s.chars().map(|c| c.to_ascii_lowercase())
894 }
895
896 const GRANDFATHEREDS: [&str; 26] = [
897 "art-lojban",
898 "cel-gaulish",
899 "en-GB-oed",
900 "i-ami",
901 "i-bnn",
902 "i-default",
903 "i-enochian",
904 "i-hak",
905 "i-klingon",
906 "i-lux",
907 "i-mingo",
908 "i-navajo",
909 "i-pwn",
910 "i-tao",
911 "i-tay",
912 "i-tsu",
913 "no-bok",
914 "no-nyn",
915 "sgn-BE-FR",
916 "sgn-BE-NL",
917 "sgn-CH-DE",
918 "zh-guoyu",
919 "zh-hakka",
920 "zh-min",
921 "zh-min-nan",
922 "zh-xiang",
923 ];