1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
//! Utilities to validate language tags following [RFC 5646](https://tools.ietf.org/html/rfc5646)
//! ([BCP 47](https://tools.ietf.org/html/bcp47)).
//!
//! ```
//! use oxilangtag::LanguageTag;
//!
//! let language_tag = LanguageTag::parse("en-US").unwrap();
//! assert_eq!("en-US", language_tag.into_inner())
//! ```
#![deny(
    future_incompatible,
    nonstandard_style,
    rust_2018_idioms,
    missing_copy_implementations,
    trivial_casts,
    trivial_numeric_casts,
    unsafe_code,
    unused_qualifications
)]

use std::borrow::{Borrow, Cow};
use std::cmp::Ordering;
use std::error::Error;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::iter::once;
use std::ops::Deref;
use std::str::{FromStr, Split};

/// A [RFC 5646](https://tools.ietf.org/html/rfc5646) language tag.
///
/// ```
/// use oxilangtag::LanguageTag;
///
/// let language_tag = LanguageTag::parse("en-us").unwrap();
/// assert_eq!("en-us", language_tag.into_inner())
/// ```
#[derive(Clone, Copy)]
pub struct LanguageTag<T> {
    tag: T,
    positions: TagElementsPositions,
}

impl<T: Deref<Target = str>> LanguageTag<T> {
    /// Parses a language tag acccording to [RFC 5646](https://tools.ietf.org/html/rfc5646).
    /// and checks if the tag is ["well-formed"](https://tools.ietf.org/html/rfc5646#section-2.2.9).
    ///
    /// This operation keeps internally the `tag` parameter and does not allocate on the heap.
    ///
    /// ```
    /// use oxilangtag::LanguageTag;
    ///
    /// let language_tag = LanguageTag::parse("en-us").unwrap();
    /// assert_eq!("en-us", language_tag.into_inner())
    /// ```
    pub fn parse(tag: T) -> Result<Self, LanguageTagParseError> {
        let positions = parse_language_tag(&tag, &mut VoidOutputBuffer::default())?;
        Ok(Self { tag, positions })
    }

    /// Returns the underlying language tag representation.
    #[inline]
    pub fn as_str(&self) -> &str {
        &self.tag
    }

    /// Returns the underlying language tag representation.
    #[inline]
    pub fn into_inner(self) -> T {
        self.tag
    }

    /// Returns the [primary language subtag](https://tools.ietf.org/html/rfc5646#section-2.2.1).
    #[inline]
    pub fn primary_language(&self) -> &str {
        &self.tag[..self.positions.language_end]
    }

    /// Returns the [extended language subtags](https://tools.ietf.org/html/rfc5646#section-2.2.2).
    ///
    /// Valid language tags have at most one extended language.
    #[inline]
    pub fn extended_language(&self) -> Option<&str> {
        if self.positions.language_end == self.positions.extlang_end {
            None
        } else {
            Some(&self.tag[self.positions.language_end + 1..self.positions.extlang_end])
        }
    }

    /// Iterates on the [extended language subtags](https://tools.ietf.org/html/rfc5646#section-2.2.2).
    ///
    /// Valid language tags have at most one extended language.
    #[inline]
    pub fn extended_language_subtags(&self) -> impl Iterator<Item = &str> {
        self.extended_language().unwrap_or("").split_terminator('-')
    }

    /// Returns the [primary language subtag](https://tools.ietf.org/html/rfc5646#section-2.2.1)
    /// and its [extended language subtags](https://tools.ietf.org/html/rfc5646#section-2.2.2).
    #[inline]
    pub fn full_language(&self) -> &str {
        &self.tag[..self.positions.extlang_end]
    }

    /// Returns the [script subtag](https://tools.ietf.org/html/rfc5646#section-2.2.3).
    #[inline]
    pub fn script(&self) -> Option<&str> {
        if self.positions.extlang_end == self.positions.script_end {
            None
        } else {
            Some(&self.tag[self.positions.extlang_end + 1..self.positions.script_end])
        }
    }

    /// Returns the [region subtag](https://tools.ietf.org/html/rfc5646#section-2.2.4).
    #[inline]
    pub fn region(&self) -> Option<&str> {
        if self.positions.script_end == self.positions.region_end {
            None
        } else {
            Some(&self.tag[self.positions.script_end + 1..self.positions.region_end])
        }
    }

    /// Returns the [variant subtags](https://tools.ietf.org/html/rfc5646#section-2.2.5).
    #[inline]
    pub fn variant(&self) -> Option<&str> {
        if self.positions.region_end == self.positions.variant_end {
            None
        } else {
            Some(&self.tag[self.positions.region_end + 1..self.positions.variant_end])
        }
    }

    /// Iterates on the [variant subtags](https://tools.ietf.org/html/rfc5646#section-2.2.5).
    #[inline]
    pub fn variant_subtags(&self) -> impl Iterator<Item = &str> {
        self.variant().unwrap_or("").split_terminator('-')
    }

    /// Returns the [extension subtags](https://tools.ietf.org/html/rfc5646#section-2.2.6).
    #[inline]
    pub fn extension(&self) -> Option<&str> {
        if self.positions.variant_end == self.positions.extension_end {
            None
        } else {
            Some(&self.tag[self.positions.variant_end + 1..self.positions.extension_end])
        }
    }

    /// Iterates on the [extension subtags](https://tools.ietf.org/html/rfc5646#section-2.2.6).
    #[inline]
    pub fn extension_subtags(&self) -> impl Iterator<Item = (char, &str)> {
        match self.extension() {
            Some(parts) => ExtensionsIterator::new(parts),
            None => ExtensionsIterator::new(""),
        }
    }

    /// Returns the [private use subtags](https://tools.ietf.org/html/rfc5646#section-2.2.7).
    #[inline]
    pub fn private_use(&self) -> Option<&str> {
        if self.tag.starts_with("x-") {
            Some(&self.tag)
        } else if self.positions.extension_end == self.tag.len() {
            None
        } else {
            Some(&self.tag[self.positions.extension_end + 1..])
        }
    }

    /// Iterates on the [private use subtags](https://tools.ietf.org/html/rfc5646#section-2.2.7).
    #[inline]
    pub fn private_use_subtags(&self) -> impl Iterator<Item = &str> {
        self.private_use()
            .map(|part| &part[2..])
            .unwrap_or("")
            .split_terminator('-')
    }
}

impl LanguageTag<String> {
    /// Parses a language tag acccording to [RFC 5646](https://tools.ietf.org/html/rfc5646)
    /// and normalizes its case.
    ///
    /// This parser accepts the language tags that are "well-formed" according to
    /// [RFC 5646](https://tools.ietf.org/html/rfc5646#section-2.2.9).
    ///
    /// This operation does heap allocation.
    ///
    /// ```
    /// use oxilangtag::LanguageTag;
    ///
    /// let language_tag = LanguageTag::parse_and_normalize("en-us").unwrap();
    /// assert_eq!("en-US", language_tag.into_inner())
    /// ```
    pub fn parse_and_normalize(tag: &str) -> Result<Self, LanguageTagParseError> {
        let mut output_buffer = String::with_capacity(tag.len());
        let positions = parse_language_tag(&tag, &mut output_buffer)?;
        Ok(Self {
            tag: output_buffer,
            positions,
        })
    }
}

impl<Lft: PartialEq<Rhs>, Rhs> PartialEq<LanguageTag<Rhs>> for LanguageTag<Lft> {
    #[inline]
    fn eq(&self, other: &LanguageTag<Rhs>) -> bool {
        self.tag.eq(&other.tag)
    }
}

impl<T: PartialEq<str>> PartialEq<str> for LanguageTag<T> {
    #[inline]
    fn eq(&self, other: &str) -> bool {
        self.tag.eq(other)
    }
}

impl<'a, T: PartialEq<&'a str>> PartialEq<&'a str> for LanguageTag<T> {
    #[inline]
    fn eq(&self, other: &&'a str) -> bool {
        self.tag.eq(other)
    }
}

impl<T: PartialEq<String>> PartialEq<String> for LanguageTag<T> {
    #[inline]
    fn eq(&self, other: &String) -> bool {
        self.tag.eq(other)
    }
}

impl<'a, T: PartialEq<Cow<'a, str>>> PartialEq<Cow<'a, str>> for LanguageTag<T> {
    #[inline]
    fn eq(&self, other: &Cow<'a, str>) -> bool {
        self.tag.eq(other)
    }
}

impl<T: PartialEq<str>> PartialEq<LanguageTag<T>> for str {
    #[inline]
    fn eq(&self, other: &LanguageTag<T>) -> bool {
        other.tag.eq(self)
    }
}

impl<'a, T: PartialEq<&'a str>> PartialEq<LanguageTag<T>> for &'a str {
    #[inline]
    fn eq(&self, other: &LanguageTag<T>) -> bool {
        other.tag.eq(self)
    }
}

impl<T: PartialEq<String>> PartialEq<LanguageTag<T>> for String {
    #[inline]
    fn eq(&self, other: &LanguageTag<T>) -> bool {
        other.tag.eq(self)
    }
}

impl<'a, T: PartialEq<Cow<'a, str>>> PartialEq<LanguageTag<T>> for Cow<'a, str> {
    #[inline]
    fn eq(&self, other: &LanguageTag<T>) -> bool {
        other.tag.eq(self)
    }
}

impl<T: Eq> Eq for LanguageTag<T> {}

impl<T: Hash> Hash for LanguageTag<T> {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.tag.hash(state)
    }
}

impl<T: PartialOrd> PartialOrd for LanguageTag<T> {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.tag.partial_cmp(&other.tag)
    }
}

impl<T: Ord> Ord for LanguageTag<T> {
    #[inline]
    fn cmp(&self, other: &Self) -> Ordering {
        self.tag.cmp(&other.tag)
    }
}

impl<T: Deref<Target = str>> Deref for LanguageTag<T> {
    type Target = str;

    #[inline]
    fn deref(&self) -> &str {
        self.tag.deref()
    }
}

impl<T: AsRef<str>> AsRef<str> for LanguageTag<T> {
    #[inline]
    fn as_ref(&self) -> &str {
        self.tag.as_ref()
    }
}

impl<T: Borrow<str>> Borrow<str> for LanguageTag<T> {
    #[inline]
    fn borrow(&self) -> &str {
        self.tag.borrow()
    }
}

impl<T: fmt::Debug> fmt::Debug for LanguageTag<T> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.tag.fmt(f)
    }
}

impl<T: fmt::Display> fmt::Display for LanguageTag<T> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.tag.fmt(f)
    }
}

impl FromStr for LanguageTag<String> {
    type Err = LanguageTagParseError;

    #[inline]
    fn from_str(tag: &str) -> Result<Self, LanguageTagParseError> {
        Self::parse_and_normalize(tag)
    }
}

impl<'a> From<LanguageTag<&'a str>> for LanguageTag<String> {
    #[inline]
    fn from(tag: LanguageTag<&'a str>) -> Self {
        Self {
            tag: tag.tag.into(),
            positions: tag.positions,
        }
    }
}

impl<'a> From<LanguageTag<Cow<'a, str>>> for LanguageTag<String> {
    #[inline]
    fn from(tag: LanguageTag<Cow<'a, str>>) -> Self {
        Self {
            tag: tag.tag.into(),
            positions: tag.positions,
        }
    }
}

impl From<LanguageTag<Box<str>>> for LanguageTag<String> {
    #[inline]
    fn from(tag: LanguageTag<Box<str>>) -> Self {
        Self {
            tag: tag.tag.into(),
            positions: tag.positions,
        }
    }
}

impl<'a> From<LanguageTag<&'a str>> for LanguageTag<Cow<'a, str>> {
    #[inline]
    fn from(tag: LanguageTag<&'a str>) -> Self {
        Self {
            tag: tag.tag.into(),
            positions: tag.positions,
        }
    }
}

impl<'a> From<LanguageTag<String>> for LanguageTag<Cow<'a, str>> {
    #[inline]
    fn from(tag: LanguageTag<String>) -> Self {
        Self {
            tag: tag.tag.into(),
            positions: tag.positions,
        }
    }
}

/// An error raised during `LanguageTag` validation.
#[derive(Debug)]
pub struct LanguageTagParseError {
    kind: TagParseErrorKind,
}

impl fmt::Display for LanguageTagParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.kind {
            TagParseErrorKind::EmptyExtension => {
                write!(f, "If an extension subtag is present, it must not be empty")
            }
            TagParseErrorKind::EmptyPrivateUse => {
                write!(f, "If the `x` subtag is present, it must not be empty")
            }
            TagParseErrorKind::ForbiddenChar => {
                write!(f, "The langtag contains a char not allowed")
            }
            TagParseErrorKind::InvalidSubtag => write!(
                f,
                "A subtag fails to parse, it does not match any other subtags"
            ),
            TagParseErrorKind::InvalidLanguage => write!(f, "The given language subtag is invalid"),
            TagParseErrorKind::SubtagTooLong => {
                write!(f, "A subtag may be eight characters in length at maximum")
            }
            TagParseErrorKind::EmptySubtag => write!(f, "A subtag should not be empty"),
            TagParseErrorKind::TooManyExtlangs => {
                write!(f, "At maximum three extlangs are allowed")
            }
        }
    }
}

impl Error for LanguageTagParseError {}

#[derive(Debug)]
enum TagParseErrorKind {
    /// If an extension subtag is present, it must not be empty.
    EmptyExtension,
    /// If the `x` subtag is present, it must not be empty.
    EmptyPrivateUse,
    /// The langtag contains a char that is not A-Z, a-z, 0-9 or the dash.
    ForbiddenChar,
    /// A subtag fails to parse, it does not match any other subtags.
    InvalidSubtag,
    /// The given language subtag is invalid.
    InvalidLanguage,
    /// A subtag may be eight characters in length at maximum.
    SubtagTooLong,
    /// A subtag should not be empty.
    EmptySubtag,
    /// At maximum three extlangs are allowed, but zero to one extlangs are preferred.
    TooManyExtlangs,
}

#[derive(Debug, Clone, Copy)]
struct TagElementsPositions {
    language_end: usize,
    extlang_end: usize,
    script_end: usize,
    region_end: usize,
    variant_end: usize,
    extension_end: usize,
}

trait OutputBuffer: Extend<char> {
    fn push(&mut self, c: char);

    fn push_str(&mut self, s: &str);
}

#[derive(Default)]
struct VoidOutputBuffer {}

impl OutputBuffer for VoidOutputBuffer {
    #[inline]
    fn push(&mut self, _: char) {}

    #[inline]
    fn push_str(&mut self, _: &str) {}
}

impl Extend<char> for VoidOutputBuffer {
    #[inline]
    fn extend<T: IntoIterator<Item = char>>(&mut self, _: T) {}
}

impl OutputBuffer for String {
    #[inline]
    fn push(&mut self, c: char) {
        self.push(c);
    }

    #[inline]
    fn push_str(&mut self, s: &str) {
        self.push_str(s);
    }
}

/// Parses language tag following [the RFC5646 grammar](https://tools.ietf.org/html/rfc5646#section-2.1)
fn parse_language_tag(
    input: &str,
    output: &mut impl OutputBuffer,
) -> Result<TagElementsPositions, LanguageTagParseError> {
    //grandfathered tags
    if let Some(tag) = GRANDFATHEREDS
        .iter()
        .find(|record| record.eq_ignore_ascii_case(input))
    {
        output.push_str(tag);
        Ok(TagElementsPositions {
            language_end: tag.len(),
            extlang_end: tag.len(),
            script_end: tag.len(),
            region_end: tag.len(),
            variant_end: tag.len(),
            extension_end: tag.len(),
        })
    } else if input.starts_with("x-") || input.starts_with("X-") {
        // private use
        if !is_alphanumeric_or_dash(input) {
            Err(LanguageTagParseError {
                kind: TagParseErrorKind::ForbiddenChar,
            })
        } else if input.len() == 2 {
            Err(LanguageTagParseError {
                kind: TagParseErrorKind::EmptyPrivateUse,
            })
        } else {
            output.extend(input.chars().map(|c| c.to_ascii_lowercase()));
            Ok(TagElementsPositions {
                language_end: input.len(),
                extlang_end: input.len(),
                script_end: input.len(),
                region_end: input.len(),
                variant_end: input.len(),
                extension_end: input.len(),
            })
        }
    } else {
        parse_langtag(input, output)
    }
}

/// Handles normal tags.
fn parse_langtag(
    input: &str,
    output: &mut impl OutputBuffer,
) -> Result<TagElementsPositions, LanguageTagParseError> {
    #[derive(PartialEq, Eq)]
    enum State {
        Start,
        AfterLanguage,
        AfterExtLang,
        AfterScript,
        AfterRegion,
        InExtension { expected: bool },
        InPrivateUse { expected: bool },
    }

    let mut state = State::Start;
    let mut language_end = 0;
    let mut extlang_end = 0;
    let mut script_end = 0;
    let mut region_end = 0;
    let mut variant_end = 0;
    let mut extension_end = 0;
    let mut extlangs_count = 0;
    for (subtag, end) in SubTagIterator::new(input) {
        if subtag.is_empty() {
            // All subtags have a maximum length of eight characters.
            return Err(LanguageTagParseError {
                kind: TagParseErrorKind::EmptySubtag,
            });
        }
        if subtag.len() > 8 {
            // All subtags have a maximum length of eight characters.
            return Err(LanguageTagParseError {
                kind: TagParseErrorKind::SubtagTooLong,
            });
        }
        if state == State::Start {
            // Primary language
            if subtag.len() < 2 || !is_alphabetic(subtag) {
                return Err(LanguageTagParseError {
                    kind: TagParseErrorKind::InvalidLanguage,
                });
            }
            language_end = end;
            output.extend(to_lowercase(subtag));
            if subtag.len() < 4 {
                // extlangs are only allowed for short language tags
                state = State::AfterLanguage;
            } else {
                state = State::AfterExtLang;
            }
        } else if let State::InPrivateUse { .. } = state {
            if !is_alphanumeric(subtag) {
                return Err(LanguageTagParseError {
                    kind: TagParseErrorKind::InvalidSubtag,
                });
            }
            output.push('-');
            output.extend(to_lowercase(subtag));
            state = State::InPrivateUse { expected: false };
        } else if subtag == "x" || subtag == "X" {
            // We make sure extension is found
            if let State::InExtension { expected: true } = state {
                return Err(LanguageTagParseError {
                    kind: TagParseErrorKind::EmptyExtension,
                });
            }
            output.push('-');
            output.push('x');
            state = State::InPrivateUse { expected: true };
        } else if subtag.len() == 1 && is_alphanumeric(subtag) {
            // We make sure extension is found
            if let State::InExtension { expected: true } = state {
                return Err(LanguageTagParseError {
                    kind: TagParseErrorKind::EmptyExtension,
                });
            }
            let extension_tag = subtag.chars().next().unwrap().to_ascii_lowercase();
            output.push('-');
            output.push(extension_tag);
            state = State::InExtension { expected: true };
        } else if let State::InExtension { .. } = state {
            if !is_alphanumeric(subtag) {
                return Err(LanguageTagParseError {
                    kind: TagParseErrorKind::InvalidSubtag,
                });
            }
            extension_end = end;
            output.push('-');
            output.extend(to_lowercase(subtag));
            state = State::InExtension { expected: false };
        } else if state == State::AfterLanguage && subtag.len() == 3 && is_alphabetic(subtag) {
            extlangs_count += 1;
            if extlangs_count > 3 {
                return Err(LanguageTagParseError {
                    kind: TagParseErrorKind::TooManyExtlangs,
                });
            }
            // valid extlangs
            extlang_end = end;
            output.push('-');
            output.extend(to_lowercase(subtag));
        } else if (state == State::AfterLanguage || state == State::AfterExtLang)
            && subtag.len() == 4
            && is_alphabetic(subtag)
        {
            // Script
            script_end = end;
            output.push('-');
            output.extend(to_uppercase_first(subtag));
            state = State::AfterScript;
        } else if (state == State::AfterLanguage
            || state == State::AfterExtLang
            || state == State::AfterScript)
            && (subtag.len() == 2 && is_alphabetic(subtag)
                || subtag.len() == 3 && is_numeric(subtag))
        {
            // Region
            region_end = end;
            output.push('-');
            output.extend(to_uppercase(subtag));
            state = State::AfterRegion;
        } else if (state == State::AfterLanguage
            || state == State::AfterExtLang
            || state == State::AfterScript
            || state == State::AfterRegion)
            && is_alphanumeric(subtag)
            && (subtag.len() >= 5 && is_alphabetic(&subtag[0..1])
                || subtag.len() >= 4 && is_numeric(&subtag[0..1]))
        {
            // Variant
            variant_end = end;
            output.push('-');
            output.extend(to_lowercase(subtag));
            state = State::AfterRegion;
        } else {
            return Err(LanguageTagParseError {
                kind: TagParseErrorKind::InvalidSubtag,
            });
        }
    }

    //We make sure we are in a correct final state
    if let State::InExtension { expected: true } = state {
        return Err(LanguageTagParseError {
            kind: TagParseErrorKind::EmptyExtension,
        });
    }
    if let State::InPrivateUse { expected: true } = state {
        return Err(LanguageTagParseError {
            kind: TagParseErrorKind::EmptyPrivateUse,
        });
    }

    //We make sure we have not skipped anyone
    if extlang_end < language_end {
        extlang_end = language_end;
    }
    if script_end < extlang_end {
        script_end = extlang_end;
    }
    if region_end < script_end {
        region_end = script_end;
    }
    if variant_end < region_end {
        variant_end = region_end;
    }
    if extension_end < variant_end {
        extension_end = variant_end;
    }

    Ok(TagElementsPositions {
        language_end,
        extlang_end,
        script_end,
        region_end,
        variant_end,
        extension_end,
    })
}

struct ExtensionsIterator<'a> {
    input: &'a str,
}

impl<'a> ExtensionsIterator<'a> {
    fn new(input: &'a str) -> Self {
        Self { input }
    }
}

impl<'a> Iterator for ExtensionsIterator<'a> {
    type Item = (char, &'a str);

    fn next(&mut self) -> Option<(char, &'a str)> {
        let mut parts_iterator = self.input.split_terminator('-');
        let singleton = parts_iterator.next()?.chars().next().unwrap();
        let mut content_size: usize = 2;
        for part in parts_iterator {
            if part.len() == 1 {
                let content = &self.input[2..content_size - 1];
                self.input = &self.input[content_size..];
                return Some((singleton, content));
            } else {
                content_size += part.len() + 1;
            }
        }
        let result = self.input.get(2..).map(|content| (singleton, content));
        self.input = "";
        result
    }
}

struct SubTagIterator<'a> {
    split: Split<'a, char>,
    position: usize,
}

impl<'a> SubTagIterator<'a> {
    #[inline]
    fn new(input: &'a str) -> Self {
        Self {
            split: input.split('-'),
            position: 0,
        }
    }
}

impl<'a> Iterator for SubTagIterator<'a> {
    type Item = (&'a str, usize);

    #[inline]
    fn next(&mut self) -> Option<(&'a str, usize)> {
        let tag = self.split.next()?;
        let tag_end = self.position + tag.len();
        self.position = tag_end + 1;
        Some((tag, tag_end))
    }
}

#[inline]
fn is_alphabetic(s: &str) -> bool {
    s.chars().all(|x| x.is_ascii_alphabetic())
}

#[inline]
fn is_numeric(s: &str) -> bool {
    s.chars().all(|x| x.is_ascii_digit())
}

#[inline]
fn is_alphanumeric(s: &str) -> bool {
    s.chars().all(|x| x.is_ascii_alphanumeric())
}

#[inline]
fn is_alphanumeric_or_dash(s: &str) -> bool {
    s.chars().all(|x| x.is_ascii_alphanumeric() || x == '-')
}

#[inline]
fn to_uppercase<'a>(s: &'a str) -> impl Iterator<Item = char> + 'a {
    s.chars().map(|c| c.to_ascii_uppercase())
}

// Beware: panics if s.len() == 0 (should never happen in our code)
#[inline]
fn to_uppercase_first<'a>(s: &'a str) -> impl Iterator<Item = char> + 'a {
    let mut chars = s.chars();
    once(chars.next().unwrap().to_ascii_uppercase()).chain(chars.map(|c| c.to_ascii_lowercase()))
}

#[inline]
fn to_lowercase<'a>(s: &'a str) -> impl Iterator<Item = char> + 'a {
    s.chars().map(|c| c.to_ascii_lowercase())
}

const GRANDFATHEREDS: [&str; 26] = [
    "art-lojban",
    "cel-gaulish",
    "en-GB-oed",
    "i-ami",
    "i-bnn",
    "i-default",
    "i-enochian",
    "i-hak",
    "i-klingon",
    "i-lux",
    "i-mingo",
    "i-navajo",
    "i-pwn",
    "i-tao",
    "i-tay",
    "i-tsu",
    "no-bok",
    "no-nyn",
    "sgn-BE-FR",
    "sgn-BE-NL",
    "sgn-CH-DE",
    "zh-guoyu",
    "zh-hakka",
    "zh-min",
    "zh-min-nan",
    "zh-xiang",
];