libtea-core 0.2.0

Independent Rust types and protocol rules for the CycloneDX Transparency Exchange API. No network I/O.
Documentation
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
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
//! Package URL (ECMA-427) parsing and canonical form, for comparison only.
//!
//! **Experimental:** may change in a 0.x minor release.
//!
//! TEA asks a client to use a TEI "exactly as received" and to send the `purl`
//! query parameter as the caller's "logical PURL string". So nothing in this
//! SDK rewrites a PURL it sends, stores, locks or prints as the server's. This
//! module exists so a caller can ask whether two PURLs name the same package:
//! [`Purl`] keeps the text it was parsed from ([`Purl::as_str`]), and the
//! canonical form is a separate type, [`CanonicalPurl`], that cannot be passed
//! where a `Purl` is expected.
//!
//! The rules ECMA-427 gives for every type are always applied
//! ([`PurlRules::Generic`]): lowercase scheme, type and qualifier keys;
//! percent-encoding normalized; empty qualifier values dropped and keys sorted;
//! empty, `.` and `..` subpath segments dropped. On top of those, the
//! components a purl-spec type definition marks case-insensitive are
//! lowercased ([`PurlRules::CaseInsensitive`]), and `pypi` names follow
//! PEP 503 ([`PurlRules::Pypi`]). Rules the definitions give only in prose
//! (for example `hackage`'s "kebab-case", `pub`'s underscores or `cpan`'s
//! uppercase author) are not applied, so two spellings that a type-aware tool
//! would treat as the same package may still compare unequal.
//! [`CanonicalPurl::rules`] says which rules applied.
//!
//! [`Purl::check_type`] checks the requirements the definitions give as data:
//! a required or prohibited namespace, required qualifiers, and the
//! permitted characters of a name or version. [`Purl::parse`] does not apply
//! them, so a PURL its type does not allow still parses.
//!
//! See `docs/design/purl.md` and the test-suite data under `spec/purl/`.

use std::collections::BTreeMap;
use std::fmt;

use thiserror::Error;

/// Inputs longer than this, or whose canonical form would be, are rejected
/// with [`PurlError::TooLong`].
pub const MAX_PURL_BYTES: usize = 4096;

/// Why a string is not a Package URL.
///
/// **Experimental:** may change in a 0.x minor release.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum PurlError {
    /// The text, or its canonical form, is longer than [`MAX_PURL_BYTES`].
    #[error("Package URL is longer than {MAX_PURL_BYTES} bytes")]
    TooLong,
    /// The scheme is missing or is not `pkg`.
    #[error("Package URL must start with `pkg:`")]
    Scheme,
    /// The type is missing, does not start with a letter, or has characters
    /// other than ASCII letters, digits, `.` and `-`.
    #[error("Package URL type is missing or invalid")]
    Type,
    /// The name is missing.
    #[error("Package URL name is missing")]
    Name,
    /// A namespace segment decodes to text containing `/`.
    #[error("Package URL namespace segment contains a slash")]
    Namespace,
    /// A qualifier key is empty, has characters other than ASCII letters,
    /// digits, `.`, `-` and `_`, or does not start with a letter.
    #[error("Package URL qualifier key is invalid")]
    QualifierKey,
    /// A qualifier key appears twice.
    #[error("Package URL qualifier key appears more than once")]
    DuplicateQualifier,
    /// A subpath segment decodes to text containing `/`.
    #[error("Package URL subpath segment contains a slash")]
    Subpath,
    /// A `%` not followed by two hex digits, or decoded bytes that are not UTF-8.
    #[error("Package URL has an invalid percent-encoding")]
    Encoding,
    /// The identifier of a `purl` TEI is not unpadded Base64URL of UTF-8 text.
    #[error("TEI purl identifier is not unpadded Base64URL of UTF-8 text")]
    TeiIdentifier,
}

/// Which canonicalization rules produced a [`CanonicalPurl`].
///
/// **Experimental:** may change in a 0.x minor release. A type that gains
/// rules gets a new variant, so its canonical form changes in that release.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub enum PurlRules {
    /// The rules ECMA-427 gives for every type, and nothing type-specific.
    Generic,
    /// The generic rules, plus those of the purl-spec `pypi` type definition:
    /// the name is lowercased and each run of `-`, `_` and `.` becomes one
    /// `-` (PEP 503), and the version, which the definition marks
    /// case-insensitive, is lowercased. Only ASCII letters are lowercased;
    /// valid PyPI names and versions are ASCII.
    Pypi,
    /// The generic rules, plus lowercasing every component (namespace, name,
    /// version or subpath) that the purl-spec type definition marks
    /// `"case_sensitive": false`, for example the namespace and name of
    /// `github`, `deb` and `composer` PURLs. Only ASCII letters are lowercased.
    CaseInsensitive,
}

impl PurlRules {
    /// The rules for a lowercased type.
    fn for_type(package_type: &str) -> Self {
        match (package_type, type_rule(package_type)) {
            ("pypi", _) => Self::Pypi,
            (_, Some(rule)) if rule.lowercase != 0 => Self::CaseInsensitive,
            _ => Self::Generic,
        }
    }
}

/// Why a PURL breaks a rule of its purl-spec type definition
/// ([`Purl::check_type`]).
///
/// **Experimental:** may change in a 0.x minor release.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum PurlTypeError {
    /// The type requires a namespace and there is none.
    #[error("this Package URL type requires a namespace")]
    NamespaceRequired,
    /// The type has no namespace and one is given.
    #[error("this Package URL type does not allow a namespace")]
    NamespaceProhibited,
    /// A qualifier the type requires is missing.
    #[error("this Package URL type requires the qualifier `{0}`")]
    QualifierRequired(&'static str),
    /// The name has characters the type does not permit.
    #[error("the Package URL name has characters this type does not permit")]
    NameCharacters,
    /// The version has characters the type does not permit.
    #[error("the Package URL version has characters this type does not permit")]
    VersionCharacters,
}

const NAMESPACE: u8 = 1;
const NAME: u8 = 2;
const VERSION: u8 = 4;
const SUBPATH: u8 = 8;

#[derive(Clone, Copy)]
enum Requirement {
    Required,
    Prohibited,
    Optional,
}

/// What a purl-spec type definition (`spec/purl/types/`) gives as data,
/// except `permitted_characters` (see [`check_characters`]). Sorted by type.
/// `tests/purl_spec_suite.rs` checks it against the vendored definitions.
struct TypeRule {
    package_type: &'static str,
    /// The components marked `"case_sensitive": false`.
    lowercase: u8,
    namespace: Requirement,
    required_qualifiers: &'static [&'static str],
}

#[rustfmt::skip]
const TYPE_RULES: &[TypeRule] = &[
    TypeRule { package_type: "alpm", lowercase: NAMESPACE | NAME, namespace: Requirement::Required, required_qualifiers: &[] },
    TypeRule { package_type: "apk", lowercase: NAMESPACE | NAME, namespace: Requirement::Required, required_qualifiers: &[] },
    TypeRule { package_type: "bazel", lowercase: 0, namespace: Requirement::Prohibited, required_qualifiers: &[] },
    TypeRule { package_type: "bitbucket", lowercase: NAMESPACE | NAME, namespace: Requirement::Required, required_qualifiers: &[] },
    TypeRule { package_type: "bitnami", lowercase: NAME, namespace: Requirement::Prohibited, required_qualifiers: &[] },
    TypeRule { package_type: "brew", lowercase: NAMESPACE | NAME, namespace: Requirement::Optional, required_qualifiers: &[] },
    TypeRule { package_type: "cargo", lowercase: 0, namespace: Requirement::Prohibited, required_qualifiers: &[] },
    TypeRule { package_type: "chrome-extension", lowercase: NAME, namespace: Requirement::Prohibited, required_qualifiers: &[] },
    TypeRule { package_type: "cocoapods", lowercase: 0, namespace: Requirement::Prohibited, required_qualifiers: &[] },
    TypeRule { package_type: "composer", lowercase: NAMESPACE | NAME, namespace: Requirement::Required, required_qualifiers: &[] },
    TypeRule { package_type: "conan", lowercase: 0, namespace: Requirement::Optional, required_qualifiers: &[] },
    TypeRule { package_type: "conda", lowercase: 0, namespace: Requirement::Prohibited, required_qualifiers: &[] },
    TypeRule { package_type: "cpan", lowercase: 0, namespace: Requirement::Optional, required_qualifiers: &[] },
    TypeRule { package_type: "cran", lowercase: 0, namespace: Requirement::Prohibited, required_qualifiers: &[] },
    TypeRule { package_type: "deb", lowercase: NAMESPACE | NAME, namespace: Requirement::Required, required_qualifiers: &[] },
    TypeRule { package_type: "docker", lowercase: 0, namespace: Requirement::Optional, required_qualifiers: &[] },
    TypeRule { package_type: "gem", lowercase: 0, namespace: Requirement::Prohibited, required_qualifiers: &[] },
    TypeRule { package_type: "generic", lowercase: 0, namespace: Requirement::Optional, required_qualifiers: &[] },
    TypeRule { package_type: "git", lowercase: 0, namespace: Requirement::Required, required_qualifiers: &[] },
    TypeRule { package_type: "github", lowercase: NAMESPACE | NAME, namespace: Requirement::Required, required_qualifiers: &[] },
    TypeRule { package_type: "golang", lowercase: 0, namespace: Requirement::Required, required_qualifiers: &[] },
    TypeRule { package_type: "hackage", lowercase: 0, namespace: Requirement::Prohibited, required_qualifiers: &[] },
    TypeRule { package_type: "hex", lowercase: NAMESPACE | NAME, namespace: Requirement::Optional, required_qualifiers: &[] },
    TypeRule { package_type: "huggingface", lowercase: VERSION, namespace: Requirement::Required, required_qualifiers: &[] },
    TypeRule { package_type: "julia", lowercase: 0, namespace: Requirement::Prohibited, required_qualifiers: &["uuid"] },
    TypeRule { package_type: "luarocks", lowercase: NAMESPACE | NAME, namespace: Requirement::Optional, required_qualifiers: &[] },
    TypeRule { package_type: "maven", lowercase: 0, namespace: Requirement::Required, required_qualifiers: &[] },
    TypeRule { package_type: "mlflow", lowercase: 0, namespace: Requirement::Prohibited, required_qualifiers: &[] },
    TypeRule { package_type: "npm", lowercase: 0, namespace: Requirement::Optional, required_qualifiers: &[] },
    TypeRule { package_type: "nuget", lowercase: 0, namespace: Requirement::Prohibited, required_qualifiers: &[] },
    TypeRule { package_type: "oci", lowercase: NAME | VERSION, namespace: Requirement::Prohibited, required_qualifiers: &[] },
    TypeRule { package_type: "opam", lowercase: 0, namespace: Requirement::Prohibited, required_qualifiers: &[] },
    TypeRule { package_type: "otp", lowercase: NAME | SUBPATH, namespace: Requirement::Prohibited, required_qualifiers: &[] },
    TypeRule { package_type: "pub", lowercase: NAME, namespace: Requirement::Prohibited, required_qualifiers: &[] },
    TypeRule { package_type: "pypi", lowercase: NAME | VERSION, namespace: Requirement::Prohibited, required_qualifiers: &[] },
    TypeRule { package_type: "qpkg", lowercase: NAMESPACE, namespace: Requirement::Required, required_qualifiers: &[] },
    TypeRule { package_type: "rpm", lowercase: NAMESPACE, namespace: Requirement::Required, required_qualifiers: &[] },
    TypeRule { package_type: "swid", lowercase: 0, namespace: Requirement::Optional, required_qualifiers: &["tag_id"] },
    TypeRule { package_type: "swift", lowercase: 0, namespace: Requirement::Required, required_qualifiers: &[] },
    TypeRule { package_type: "vcpkg", lowercase: 0, namespace: Requirement::Prohibited, required_qualifiers: &[] },
    TypeRule { package_type: "vscode-extension", lowercase: NAMESPACE | NAME | VERSION, namespace: Requirement::Required, required_qualifiers: &[] },
    TypeRule { package_type: "yocto", lowercase: NAMESPACE, namespace: Requirement::Optional, required_qualifiers: &[] },
];

fn type_rule(package_type: &str) -> Option<&'static TypeRule> {
    TYPE_RULES
        .binary_search_by(|rule| rule.package_type.cmp(package_type))
        .ok()
        .map(|index| &TYPE_RULES[index])
}

/// The `permitted_characters` patterns of the definitions, written out:
/// `chrome-extension` name `^[a-p]{32}$` and version `^\d+(\.\d+){0,3}$`, and
/// `pub` name `^[a-z0-9_]` (as written, it constrains the first character
/// only). The name is checked after case folding, as the definitions mark both
/// names case-insensitive.
fn check_characters(
    package_type: &str,
    name: &str,
    version: Option<&str>,
) -> Result<(), PurlTypeError> {
    let name = name.to_ascii_lowercase();
    let name_ok = match package_type {
        "chrome-extension" => name.len() == 32 && name.bytes().all(|b| (b'a'..=b'p').contains(&b)),
        "pub" => name
            .bytes()
            .next()
            .is_some_and(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_'),
        _ => true,
    };
    if !name_ok {
        return Err(PurlTypeError::NameCharacters);
    }
    let version_ok = match (package_type, version) {
        ("chrome-extension", Some(version)) => {
            let parts: Vec<_> = version.split('.').collect();
            parts.len() <= 4
                && parts
                    .iter()
                    .all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit()))
        }
        _ => true,
    };
    if !version_ok {
        return Err(PurlTypeError::VersionCharacters);
    }
    Ok(())
}

/// A parsed Package URL. Holds the original text and never rewrites it.
///
/// **Experimental:** may change in a 0.x minor release.
///
/// Equality compares the original text and components exactly. To ask
/// whether two spellings name the same package, compare
/// [`Purl::canonical`] values or use [`same_package_url`].
///
/// ```
/// use libtea_core::purl::{same_package_url, Purl};
///
/// let a = Purl::parse("PKG:Maven/org.apache/commons-io@2.11.0?Type=jar&classifier=").unwrap();
/// let b = Purl::parse("pkg:maven/org.apache/commons-io@2.11.0?type=jar").unwrap();
/// assert_eq!(a.as_str(), "PKG:Maven/org.apache/commons-io@2.11.0?Type=jar&classifier=");
/// assert_eq!(a.canonical().as_str(), "pkg:maven/org.apache/commons-io@2.11.0?type=jar");
/// assert!(same_package_url(&a, &b));
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Purl {
    original: String,
    package_type: String,
    namespace: Vec<String>,
    name: String,
    version: Option<String>,
    qualifiers: BTreeMap<String, String>,
    subpath: Vec<String>,
}

/// A PURL in canonical form under [`Self::rules`]. Comparable and hashable.
///
/// **Experimental:** may change in a 0.x minor release.
///
/// It is computed from a [`Purl`] and cannot be turned back into one without
/// parsing, so it cannot be sent by mistake where the original was meant.
///
/// Equality, hashing and ordering compare the text. The rules follow from the
/// type in it, so equal texts always have equal rules.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct CanonicalPurl {
    text: String,
    rules: PurlRules,
}

impl CanonicalPurl {
    /// The canonical text.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.text
    }

    /// The rules that were applied: [`PurlRules::Generic`], or the
    /// type-specific variant for a type that has one.
    #[must_use]
    pub fn rules(&self) -> PurlRules {
        self.rules
    }
}

impl fmt::Display for CanonicalPurl {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.text)
    }
}

/// Whether two PURLs have the same canonical form ([`Purl::canonical`]).
#[must_use]
pub fn same_package_url(a: &Purl, b: &Purl) -> bool {
    a.canonical() == b.canonical()
}

impl Purl {
    /// Parse a Package URL as ECMA-427 describes, right to left.
    ///
    /// Accepts what the specification says a parser should accept, such as
    /// `pkg://` and redundant slashes, and keeps `text` unchanged for
    /// [`Self::as_str`].
    ///
    /// # Errors
    ///
    /// Returns [`PurlError`] when a required component is missing, a type or
    /// qualifier key has characters ECMA-427 does not allow, a qualifier key
    /// repeats, a decoded namespace or subpath segment contains `/`, the
    /// percent-encoding is invalid, or the text or its canonical form is
    /// longer than [`MAX_PURL_BYTES`].
    pub fn parse(text: &str) -> Result<Self, PurlError> {
        if text.len() > MAX_PURL_BYTES {
            return Err(PurlError::TooLong);
        }
        let (remainder, subpath) = match text.rsplit_once('#') {
            Some((left, right)) => (left, parse_subpath(right)?),
            None => (text, Vec::new()),
        };
        let (remainder, qualifiers) = match remainder.rsplit_once('?') {
            Some((left, right)) => (left, parse_qualifiers(right)?),
            None => (remainder, BTreeMap::new()),
        };
        let (scheme, remainder) = remainder.split_once(':').ok_or(PurlError::Scheme)?;
        if !scheme.eq_ignore_ascii_case("pkg") {
            return Err(PurlError::Scheme);
        }
        let remainder = remainder.trim_start_matches('/');
        let (package_type, remainder) = remainder.split_once('/').ok_or(PurlError::Name)?;
        let package_type = package_type.to_ascii_lowercase();
        if !valid_type(&package_type) {
            return Err(PurlError::Type);
        }
        // The version separator is the last '@' of the last path segment, so an
        // unencoded '@' that starts a namespace segment (`pkg:npm/@babel/core`)
        // is not taken for one. A version's own '/' is percent-encoded.
        let last_segment = remainder.rfind('/').map_or(0, |index| index + 1);
        let (remainder, version) = match remainder[last_segment..].rfind('@') {
            Some(at) => {
                let at = last_segment + at;
                let version = percent_decode(&remainder[at + 1..])?;
                (&remainder[..at], (!version.is_empty()).then_some(version))
            }
            None => (remainder, None),
        };
        let remainder = remainder.trim_end_matches('/');
        let (remainder, name) = match remainder.rsplit_once('/') {
            Some((left, right)) => (left, right),
            None => ("", remainder),
        };
        let name = percent_decode(name)?;
        if name.is_empty() {
            return Err(PurlError::Name);
        }
        let mut namespace = Vec::new();
        for segment in remainder.split('/').filter(|segment| !segment.is_empty()) {
            let segment = percent_decode(segment)?;
            if segment.contains('/') {
                return Err(PurlError::Namespace);
            }
            namespace.push(segment);
        }
        let purl = Self {
            original: text.to_owned(),
            package_type,
            namespace,
            name,
            version,
            qualifiers,
            subpath,
        };
        // Percent-encoding can triple a component's length. Refusing here keeps
        // the promise that every canonical form parses again.
        if purl.canonical().text.len() > MAX_PURL_BYTES {
            return Err(PurlError::TooLong);
        }
        Ok(purl)
    }

    /// Exactly the text that was parsed.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.original
    }

    /// The type, lowercased.
    #[must_use]
    pub fn package_type(&self) -> &str {
        &self.package_type
    }

    /// The decoded namespace segments joined with `/`, or `None` when there
    /// are none. No type-specific normalization is applied (see
    /// [`Self::canonical`]).
    #[must_use]
    pub fn namespace(&self) -> Option<String> {
        (!self.namespace.is_empty()).then(|| self.namespace.join("/"))
    }

    /// The decoded name, as written. No type-specific normalization is
    /// applied (see [`Self::canonical`]).
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The decoded version, as written, or `None` when absent or empty.
    #[must_use]
    pub fn version(&self) -> Option<&str> {
        self.version.as_deref()
    }

    /// Decoded qualifiers with non-empty values, keys lowercased, in key order.
    pub fn qualifiers(&self) -> impl Iterator<Item = (&str, &str)> {
        self.qualifiers
            .iter()
            .map(|(key, value)| (key.as_str(), value.as_str()))
    }

    /// The decoded value of one qualifier; `key` is matched in lowercase.
    #[must_use]
    pub fn qualifier(&self, key: &str) -> Option<&str> {
        self.qualifiers
            .get(&key.to_ascii_lowercase())
            .map(String::as_str)
    }

    /// The decoded subpath segments joined with `/`, without empty, `.` and
    /// `..` segments, or `None` when none remain.
    #[must_use]
    pub fn subpath(&self) -> Option<String> {
        (!self.subpath.is_empty()).then(|| self.subpath.join("/"))
    }

    /// The canonical form: the generic rules, plus the type's own rules when
    /// [`PurlRules`] has them ([`CanonicalPurl::rules`] says which).
    ///
    /// ```
    /// use libtea_core::purl::{Purl, PurlRules};
    ///
    /// let purl = Purl::parse("pkg:PyPI/Django_Allauth@0.61.1RC1").unwrap();
    /// assert_eq!(purl.name(), "Django_Allauth");
    /// let canonical = purl.canonical();
    /// assert_eq!(canonical.as_str(), "pkg:pypi/django-allauth@0.61.1rc1");
    /// assert_eq!(canonical.rules(), PurlRules::Pypi);
    /// ```
    #[must_use]
    pub fn canonical(&self) -> CanonicalPurl {
        let rules = PurlRules::for_type(&self.package_type);
        let lowercase = type_rule(&self.package_type).map_or(0, |rule| rule.lowercase);
        let fold = |text: &str, component: u8, out: &mut String| {
            if lowercase & component == 0 {
                percent_encode_into(text, out);
            } else {
                percent_encode_into(&text.to_ascii_lowercase(), out);
            }
        };
        let mut out = String::with_capacity(self.original.len());
        out.push_str("pkg:");
        out.push_str(&self.package_type);
        out.push('/');
        for segment in &self.namespace {
            fold(segment, NAMESPACE, &mut out);
            out.push('/');
        }
        if rules == PurlRules::Pypi {
            percent_encode_into(&pypi_name(&self.name), &mut out);
        } else {
            fold(&self.name, NAME, &mut out);
        }
        if let Some(version) = &self.version {
            out.push('@');
            fold(version, VERSION, &mut out);
        }
        for (index, (key, value)) in self.qualifiers.iter().enumerate() {
            out.push(if index == 0 { '?' } else { '&' });
            out.push_str(key);
            out.push('=');
            percent_encode_into(value, &mut out);
        }
        for (index, segment) in self.subpath.iter().enumerate() {
            out.push(if index == 0 { '#' } else { '/' });
            fold(segment, SUBPATH, &mut out);
        }
        CanonicalPurl { text: out, rules }
    }

    /// Check the rules the purl-spec type definition gives as data: whether a
    /// namespace is required or prohibited, which qualifiers are required, and
    /// the permitted characters of the name and version. A type without a
    /// definition passes. Rules given only in prose are not checked.
    ///
    /// ```
    /// use libtea_core::purl::{Purl, PurlTypeError};
    ///
    /// assert_eq!(Purl::parse("pkg:github/package-url/purl-spec").unwrap().check_type(), Ok(()));
    /// let purl = Purl::parse("pkg:github/purl-spec").unwrap();
    /// assert_eq!(purl.check_type(), Err(PurlTypeError::NamespaceRequired));
    /// let purl = Purl::parse("pkg:julia/Dates").unwrap();
    /// assert_eq!(purl.check_type(), Err(PurlTypeError::QualifierRequired("uuid")));
    /// ```
    ///
    /// # Errors
    ///
    /// The first rule the PURL breaks, as a [`PurlTypeError`].
    pub fn check_type(&self) -> Result<(), PurlTypeError> {
        let Some(rule) = type_rule(&self.package_type) else {
            return Ok(());
        };
        match (rule.namespace, self.namespace.is_empty()) {
            (Requirement::Required, true) => return Err(PurlTypeError::NamespaceRequired),
            (Requirement::Prohibited, false) => return Err(PurlTypeError::NamespaceProhibited),
            _ => {}
        }
        if let Some(key) = rule
            .required_qualifiers
            .iter()
            .find(|key| !self.qualifiers.contains_key(**key))
        {
            return Err(PurlTypeError::QualifierRequired(key));
        }
        check_characters(&self.package_type, &self.name, self.version.as_deref())
    }
}

/// PEP 503: lowercase, and each run of `-`, `_` and `.` becomes one `-`.
fn pypi_name(name: &str) -> String {
    let mut out = String::with_capacity(name.len());
    let mut in_run = false;
    for c in name.chars() {
        if matches!(c, '-' | '_' | '.') {
            if !in_run {
                out.push('-');
            }
            in_run = true;
        } else {
            out.push(c.to_ascii_lowercase());
            in_run = false;
        }
    }
    out
}

/// ECMA-427 5.6.2: ASCII letters, digits, `.` and `-`, starting with a letter.
fn valid_type(package_type: &str) -> bool {
    let mut chars = package_type.chars();
    chars.next().is_some_and(|c| c.is_ascii_alphabetic())
        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-'))
}

/// ECMA-427 5.6.6, keys already lowercased: letters, digits, `.`, `-` and `_`,
/// starting with a letter.
fn valid_qualifier_key(key: &str) -> bool {
    let mut chars = key.chars();
    chars.next().is_some_and(|c| c.is_ascii_lowercase())
        && chars
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '.' | '-' | '_'))
}

fn parse_qualifiers(text: &str) -> Result<BTreeMap<String, String>, PurlError> {
    let mut qualifiers = BTreeMap::new();
    for pair in text.split('&').filter(|pair| !pair.is_empty()) {
        let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
        let key = key.to_ascii_lowercase();
        if !valid_qualifier_key(&key) {
            return Err(PurlError::QualifierKey);
        }
        let value = percent_decode(value)?;
        if value.is_empty() {
            continue;
        }
        if qualifiers.insert(key, value).is_some() {
            return Err(PurlError::DuplicateQualifier);
        }
    }
    Ok(qualifiers)
}

fn parse_subpath(text: &str) -> Result<Vec<String>, PurlError> {
    let mut segments = Vec::new();
    for segment in text.split('/') {
        let segment = percent_decode(segment)?;
        if segment.is_empty() || segment == "." || segment == ".." {
            continue;
        }
        if segment.contains('/') {
            return Err(PurlError::Subpath);
        }
        segments.push(segment);
    }
    Ok(segments)
}

fn percent_decode(text: &str) -> Result<String, PurlError> {
    if !text.contains('%') {
        return Ok(text.to_owned());
    }
    let bytes = text.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut index = 0;
    while index < bytes.len() {
        if bytes[index] == b'%' {
            let high = bytes.get(index + 1).and_then(|b| hex_value(*b));
            let low = bytes.get(index + 2).and_then(|b| hex_value(*b));
            let (Some(high), Some(low)) = (high, low) else {
                return Err(PurlError::Encoding);
            };
            out.push(high << 4 | low);
            index += 3;
        } else {
            out.push(bytes[index]);
            index += 1;
        }
    }
    String::from_utf8(out).map_err(|_| PurlError::Encoding)
}

fn hex_value(byte: u8) -> Option<u8> {
    match byte {
        b'0'..=b'9' => Some(byte - b'0'),
        b'a'..=b'f' => Some(byte - b'a' + 10),
        b'A'..=b'F' => Some(byte - b'A' + 10),
        _ => None,
    }
}

/// ECMA-427 5.4: alphanumerics, `.-_~` and `:` stay; every other UTF-8 octet
/// becomes `%XX` with uppercase hex.
fn percent_encode_into(text: &str, out: &mut String) {
    const HEX: &[u8; 16] = b"0123456789ABCDEF";
    for &byte in text.as_bytes() {
        if byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_' | b'~' | b':') {
            out.push(char::from(byte));
        } else {
            out.push('%');
            out.push(char::from(HEX[usize::from(byte >> 4)]));
            out.push(char::from(HEX[usize::from(byte & 0x0f)]));
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn original_text_is_kept_and_canonical_is_separate() {
        let text = "pkg://NPM//%40angular/animation@12.3.1?B=2&a=1#/x/./y/";
        let purl = Purl::parse(text).unwrap();
        assert_eq!(purl.as_str(), text);
        assert_eq!(purl.package_type(), "npm");
        assert_eq!(purl.namespace().as_deref(), Some("@angular"));
        assert_eq!(purl.name(), "animation");
        assert_eq!(purl.version(), Some("12.3.1"));
        assert_eq!(purl.qualifier("A"), Some("1"));
        assert_eq!(purl.subpath().as_deref(), Some("x/y"));
        assert_eq!(
            purl.canonical().as_str(),
            "pkg:npm/%40angular/animation@12.3.1?a=1&b=2#x/y"
        );
        assert_eq!(purl.canonical().rules(), PurlRules::Generic);
    }

    #[test]
    fn an_unencoded_scope_is_not_a_version() {
        let purl = Purl::parse("pkg:npm/@babel/core#lib").unwrap();
        assert_eq!(purl.namespace().as_deref(), Some("@babel"));
        assert_eq!(purl.name(), "core");
        assert_eq!(purl.version(), None);
        assert_eq!(purl.canonical().as_str(), "pkg:npm/%40babel/core#lib");
        let versioned = Purl::parse("pkg:npm/@babel/core@7.0.0").unwrap();
        assert_eq!(versioned.version(), Some("7.0.0"));
    }

    #[test]
    fn canonical_is_idempotent_on_its_own_output() {
        for text in [
            "pkg:generic/a%20b@1.0%2B2?checksum=sha1:ab,sha256:cd",
            "pkg:deb/debian/curl@7.50.3-1?arch=i386&distro=jessie",
            "pkg:golang/github.com/gorilla/context@234fd47e07d1004f0aed9c#api",
            "pkg:generic/%E2%82%AC@%C3%A9",
        ] {
            let once = Purl::parse(text).unwrap().canonical();
            let twice = Purl::parse(once.as_str()).unwrap().canonical();
            assert_eq!(once, twice, "{text}");
        }
    }

    #[test]
    fn rejected_inputs() {
        let cases: &[(&str, PurlError)] = &[
            ("EnterpriseLibrary.Common@6.0.1304", PurlError::Scheme),
            ("http:npm/a", PurlError::Scheme),
            ("pkg:npm", PurlError::Name),
            ("pkg:npm/", PurlError::Name),
            ("pkg:npm/@1.0", PurlError::Name),
            ("pkg:/a", PurlError::Name),
            ("pkg:9pm/a", PurlError::Type),
            ("pkg:n+m/a", PurlError::Type),
            ("pkg:n%70m/a", PurlError::Type),
            ("pkg:npm/a?1key=v", PurlError::QualifierKey),
            ("pkg:npm/a?k%65y=v", PurlError::QualifierKey),
            ("pkg:npm/a?=v", PurlError::QualifierKey),
            ("pkg:npm/a?k=1&K=2", PurlError::DuplicateQualifier),
            ("pkg:npm/a%2Fb/c", PurlError::Namespace),
            ("pkg:npm/a#b%2Fc", PurlError::Subpath),
            ("pkg:npm/a%zz", PurlError::Encoding),
            ("pkg:npm/a%c3", PurlError::Encoding),
            ("pkg:npm/a@1%", PurlError::Encoding),
        ];
        for (text, error) in cases {
            assert_eq!(Purl::parse(text).as_ref().err(), Some(error), "{text}");
        }
        let long = format!("pkg:generic/{}", "a".repeat(MAX_PURL_BYTES));
        assert_eq!(Purl::parse(&long), Err(PurlError::TooLong));
        // Short enough as text, too long once each space becomes `%20`.
        let spaces = format!("pkg:generic/{}", " ".repeat(2000));
        assert!(spaces.len() <= MAX_PURL_BYTES);
        assert_eq!(Purl::parse(&spaces), Err(PurlError::TooLong));
    }

    #[test]
    fn empty_qualifier_values_are_dropped_and_empty_version_is_none() {
        let purl = Purl::parse("pkg:generic/a@?x=&y").unwrap();
        assert_eq!(purl.version(), None);
        assert_eq!(purl.qualifiers().count(), 0);
        assert_eq!(purl.canonical().as_str(), "pkg:generic/a");
    }

    #[test]
    fn names_are_not_case_folded_without_a_type_rule() {
        // npm and maven names are case-sensitive in their type definitions.
        for (a, b) in [
            ("pkg:npm/Lodash@4.0.0", "pkg:npm/lodash@4.0.0"),
            (
                "pkg:maven/org.Apache/Commons@1",
                "pkg:maven/org.apache/commons@1",
            ),
            ("pkg:generic/a_b@1", "pkg:generic/a-b@1"),
        ] {
            let (a, b) = (Purl::parse(a).unwrap(), Purl::parse(b).unwrap());
            assert!(!same_package_url(&a, &b));
            assert_eq!(a.canonical().rules(), PurlRules::Generic);
        }
    }

    #[test]
    fn pypi_names_and_versions_follow_the_type_definition() {
        for (input, canonical) in [
            ("pkg:pypi/Django@1.11.1", "pkg:pypi/django@1.11.1"),
            ("pkg:pypi/friendly.bard@1.0", "pkg:pypi/friendly-bard@1.0"),
            ("pkg:pypi/friendly--bard", "pkg:pypi/friendly-bard"),
            (
                "pkg:pypi/My.PyPI_.--._Package@1.11.1.DEV1",
                "pkg:pypi/my-pypi-package@1.11.1.dev1",
            ),
            ("pkg:pypi/-a_", "pkg:pypi/-a-"),
            ("pkg:pypi/a%2Eb", "pkg:pypi/a-b"),
            // Qualifier values and the subpath keep their case.
            (
                "pkg:pypi/Django@1.0?file_name=Django-1.0.tar.gz#Docs",
                "pkg:pypi/django@1.0?file_name=Django-1.0.tar.gz#Docs",
            ),
        ] {
            let purl = Purl::parse(input).unwrap();
            assert_eq!(purl.as_str(), input);
            assert_eq!(purl.canonical().as_str(), canonical, "{input}");
            assert_eq!(purl.canonical().rules(), PurlRules::Pypi);
            let again = Purl::parse(canonical).unwrap().canonical();
            assert_eq!(again.as_str(), canonical, "idempotent: {input}");
        }
        let a = Purl::parse("pkg:pypi/Zope.Interface@5.0").unwrap();
        let b = Purl::parse("pkg:pypi/zope-interface@5.0").unwrap();
        assert!(same_package_url(&a, &b));
        // The accessors keep what was written.
        assert_eq!(a.name(), "Zope.Interface");
    }

    #[test]
    fn case_insensitive_components_follow_the_type_definition() {
        for (input, canonical) in [
            (
                "pkg:github/Package-URL/Purl-Spec@244FD47",
                "pkg:github/package-url/purl-spec@244FD47",
            ),
            (
                "pkg:deb/Debian/CURL@7.50.3-1?Arch=I386",
                "pkg:deb/debian/curl@7.50.3-1?arch=I386",
            ),
            ("pkg:rpm/Fedora/Curl@7.50", "pkg:rpm/fedora/Curl@7.50"),
            ("pkg:oci/Debian@SHA256%3AABC", "pkg:oci/debian@sha256:abc"),
            (
                "pkg:otp/Hex@2.1.1#Src/Hex.erl",
                "pkg:otp/hex@2.1.1#src/hex.erl",
            ),
            (
                "pkg:huggingface/EleutherAI/GPT@797ABC",
                "pkg:huggingface/EleutherAI/GPT@797abc",
            ),
        ] {
            let purl = Purl::parse(input).unwrap();
            assert_eq!(purl.as_str(), input);
            assert_eq!(purl.canonical().as_str(), canonical, "{input}");
            assert_eq!(purl.canonical().rules(), PurlRules::CaseInsensitive);
            let again = Purl::parse(canonical).unwrap().canonical();
            assert_eq!(again.as_str(), canonical, "idempotent: {input}");
        }
        // golang and swift are case-sensitive in their definitions.
        for input in [
            "pkg:golang/GitHub.com/Sirupsen/Logrus",
            "pkg:swift/github.com/Alamofire/Alamofire",
        ] {
            let purl = Purl::parse(input).unwrap();
            assert_eq!(purl.canonical().as_str(), input);
            assert_eq!(purl.canonical().rules(), PurlRules::Generic);
        }
        let a = Purl::parse("pkg:github/Package-url/purl-Spec").unwrap();
        let b = Purl::parse("pkg:github/package-url/purl-spec").unwrap();
        assert!(same_package_url(&a, &b));
        assert_eq!(a.namespace().as_deref(), Some("Package-url"));
    }

    #[test]
    fn check_type_applies_the_definition_requirements() {
        let check = |text: &str| Purl::parse(text).unwrap().check_type();
        assert_eq!(check("pkg:maven/org.apache/commons-io@2.11.0"), Ok(()));
        assert_eq!(
            check("pkg:maven/commons-io"),
            Err(PurlTypeError::NamespaceRequired)
        );
        assert_eq!(
            check("pkg:cargo/rust-lang/serde"),
            Err(PurlTypeError::NamespaceProhibited)
        );
        assert_eq!(check("pkg:npm/left-pad"), Ok(()));
        assert_eq!(check("pkg:npm/%40babel/core"), Ok(()));
        assert_eq!(
            check("pkg:julia/Dates"),
            Err(PurlTypeError::QualifierRequired("uuid"))
        );
        assert_eq!(
            check("pkg:julia/Dates?uuid=ade2ca70-3891-5945-98fb-dc099432e06a"),
            Ok(())
        );
        assert_eq!(
            check("pkg:swid/Acme/example.com/Enterprise+Server@1.0.0"),
            Err(PurlTypeError::QualifierRequired("tag_id"))
        );
        // A type without a definition, or one the parser lowercased, is checked by its type.
        assert_eq!(check("pkg:notatype/a/b"), Ok(()));
        assert_eq!(
            check("pkg:GitHub/purl-spec"),
            Err(PurlTypeError::NamespaceRequired)
        );
    }
}