Skip to main content

libtea_core/
purl.rs

1//! Package URL (ECMA-427) parsing and canonical form, for comparison only.
2//!
3//! **Experimental:** may change in a 0.x minor release.
4//!
5//! TEA asks a client to use a TEI "exactly as received" and to send the `purl`
6//! query parameter as the caller's "logical PURL string". So nothing in this
7//! SDK rewrites a PURL it sends, stores, locks or prints as the server's. This
8//! module exists so a caller can ask whether two PURLs name the same package:
9//! [`Purl`] keeps the text it was parsed from ([`Purl::as_str`]), and the
10//! canonical form is a separate type, [`CanonicalPurl`], that cannot be passed
11//! where a `Purl` is expected.
12//!
13//! The rules ECMA-427 gives for every type are always applied
14//! ([`PurlRules::Generic`]): lowercase scheme, type and qualifier keys;
15//! percent-encoding normalized; empty qualifier values dropped and keys sorted;
16//! empty, `.` and `..` subpath segments dropped. Type-specific rules are
17//! applied only for the types [`PurlRules`] names (so far `pypi`); for every
18//! other type, two spellings that a type-aware tool would treat as the same
19//! package may compare unequal. [`CanonicalPurl::rules`] says which applied.
20//!
21//! See `docs/design/purl.md` and the test-suite data under `spec/purl/`.
22
23use std::collections::BTreeMap;
24use std::fmt;
25
26use thiserror::Error;
27
28/// Inputs longer than this, or whose canonical form would be, are rejected
29/// with [`PurlError::TooLong`].
30pub const MAX_PURL_BYTES: usize = 4096;
31
32/// Why a string is not a Package URL.
33///
34/// **Experimental:** may change in a 0.x minor release.
35#[derive(Debug, Clone, PartialEq, Eq, Error)]
36#[non_exhaustive]
37pub enum PurlError {
38    /// The text, or its canonical form, is longer than [`MAX_PURL_BYTES`].
39    #[error("Package URL is longer than {MAX_PURL_BYTES} bytes")]
40    TooLong,
41    /// The scheme is missing or is not `pkg`.
42    #[error("Package URL must start with `pkg:`")]
43    Scheme,
44    /// The type is missing, does not start with a letter, or has characters
45    /// other than ASCII letters, digits, `.` and `-`.
46    #[error("Package URL type is missing or invalid")]
47    Type,
48    /// The name is missing.
49    #[error("Package URL name is missing")]
50    Name,
51    /// A namespace segment decodes to text containing `/`.
52    #[error("Package URL namespace segment contains a slash")]
53    Namespace,
54    /// A qualifier key is empty, has characters other than ASCII letters,
55    /// digits, `.`, `-` and `_`, or does not start with a letter.
56    #[error("Package URL qualifier key is invalid")]
57    QualifierKey,
58    /// A qualifier key appears twice.
59    #[error("Package URL qualifier key appears more than once")]
60    DuplicateQualifier,
61    /// A subpath segment decodes to text containing `/`.
62    #[error("Package URL subpath segment contains a slash")]
63    Subpath,
64    /// A `%` not followed by two hex digits, or decoded bytes that are not UTF-8.
65    #[error("Package URL has an invalid percent-encoding")]
66    Encoding,
67    /// The identifier of a `purl` TEI is not unpadded Base64URL of UTF-8 text.
68    #[error("TEI purl identifier is not unpadded Base64URL of UTF-8 text")]
69    TeiIdentifier,
70}
71
72/// Which canonicalization rules produced a [`CanonicalPurl`].
73///
74/// **Experimental:** may change in a 0.x minor release. A type that gains
75/// rules gets a new variant, so its canonical form changes in that release.
76#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
77#[non_exhaustive]
78pub enum PurlRules {
79    /// The rules ECMA-427 gives for every type, and nothing type-specific.
80    Generic,
81    /// The generic rules, plus those of the purl-spec `pypi` type definition:
82    /// the name is lowercased and each run of `-`, `_` and `.` becomes one
83    /// `-` (PEP 503), and the version, which the definition marks
84    /// case-insensitive, is lowercased. Only ASCII letters are lowercased;
85    /// valid PyPI names and versions are ASCII.
86    Pypi,
87}
88
89impl PurlRules {
90    /// The rules for a lowercased type.
91    fn for_type(package_type: &str) -> Self {
92        match package_type {
93            "pypi" => Self::Pypi,
94            _ => Self::Generic,
95        }
96    }
97}
98
99/// A parsed Package URL. Holds the original text and never rewrites it.
100///
101/// **Experimental:** may change in a 0.x minor release.
102///
103/// Equality compares the original text and components exactly. To ask
104/// whether two spellings name the same package, compare
105/// [`Purl::canonical`] values or use [`same_package_url`].
106///
107/// ```
108/// use libtea_core::purl::{same_package_url, Purl};
109///
110/// let a = Purl::parse("PKG:Maven/org.apache/commons-io@2.11.0?Type=jar&classifier=").unwrap();
111/// let b = Purl::parse("pkg:maven/org.apache/commons-io@2.11.0?type=jar").unwrap();
112/// assert_eq!(a.as_str(), "PKG:Maven/org.apache/commons-io@2.11.0?Type=jar&classifier=");
113/// assert_eq!(a.canonical().as_str(), "pkg:maven/org.apache/commons-io@2.11.0?type=jar");
114/// assert!(same_package_url(&a, &b));
115/// ```
116#[derive(Debug, Clone, PartialEq, Eq, Hash)]
117pub struct Purl {
118    original: String,
119    package_type: String,
120    namespace: Vec<String>,
121    name: String,
122    version: Option<String>,
123    qualifiers: BTreeMap<String, String>,
124    subpath: Vec<String>,
125}
126
127/// A PURL in canonical form under [`Self::rules`]. Comparable and hashable.
128///
129/// **Experimental:** may change in a 0.x minor release.
130///
131/// It is computed from a [`Purl`] and cannot be turned back into one without
132/// parsing, so it cannot be sent by mistake where the original was meant.
133///
134/// Equality, hashing and ordering compare the text. The rules follow from the
135/// type in it, so equal texts always have equal rules.
136#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
137pub struct CanonicalPurl {
138    text: String,
139    rules: PurlRules,
140}
141
142impl CanonicalPurl {
143    /// The canonical text.
144    #[must_use]
145    pub fn as_str(&self) -> &str {
146        &self.text
147    }
148
149    /// The rules that were applied: [`PurlRules::Generic`], or the
150    /// type-specific variant for a type that has one.
151    #[must_use]
152    pub fn rules(&self) -> PurlRules {
153        self.rules
154    }
155}
156
157impl fmt::Display for CanonicalPurl {
158    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159        f.write_str(&self.text)
160    }
161}
162
163/// Whether two PURLs have the same canonical form ([`Purl::canonical`]).
164#[must_use]
165pub fn same_package_url(a: &Purl, b: &Purl) -> bool {
166    a.canonical() == b.canonical()
167}
168
169impl Purl {
170    /// Parse a Package URL as ECMA-427 describes, right to left.
171    ///
172    /// Accepts what the specification says a parser should accept, such as
173    /// `pkg://` and redundant slashes, and keeps `text` unchanged for
174    /// [`Self::as_str`].
175    ///
176    /// # Errors
177    ///
178    /// Returns [`PurlError`] when a required component is missing, a type or
179    /// qualifier key has characters ECMA-427 does not allow, a qualifier key
180    /// repeats, a decoded namespace or subpath segment contains `/`, the
181    /// percent-encoding is invalid, or the text or its canonical form is
182    /// longer than [`MAX_PURL_BYTES`].
183    pub fn parse(text: &str) -> Result<Self, PurlError> {
184        if text.len() > MAX_PURL_BYTES {
185            return Err(PurlError::TooLong);
186        }
187        let (remainder, subpath) = match text.rsplit_once('#') {
188            Some((left, right)) => (left, parse_subpath(right)?),
189            None => (text, Vec::new()),
190        };
191        let (remainder, qualifiers) = match remainder.rsplit_once('?') {
192            Some((left, right)) => (left, parse_qualifiers(right)?),
193            None => (remainder, BTreeMap::new()),
194        };
195        let (scheme, remainder) = remainder.split_once(':').ok_or(PurlError::Scheme)?;
196        if !scheme.eq_ignore_ascii_case("pkg") {
197            return Err(PurlError::Scheme);
198        }
199        let remainder = remainder.trim_start_matches('/');
200        let (package_type, remainder) = remainder.split_once('/').ok_or(PurlError::Name)?;
201        let package_type = package_type.to_ascii_lowercase();
202        if !valid_type(&package_type) {
203            return Err(PurlError::Type);
204        }
205        // The version separator is the last '@' of the last path segment, so an
206        // unencoded '@' that starts a namespace segment (`pkg:npm/@babel/core`)
207        // is not taken for one. A version's own '/' is percent-encoded.
208        let last_segment = remainder.rfind('/').map_or(0, |index| index + 1);
209        let (remainder, version) = match remainder[last_segment..].rfind('@') {
210            Some(at) => {
211                let at = last_segment + at;
212                let version = percent_decode(&remainder[at + 1..])?;
213                (&remainder[..at], (!version.is_empty()).then_some(version))
214            }
215            None => (remainder, None),
216        };
217        let remainder = remainder.trim_end_matches('/');
218        let (remainder, name) = match remainder.rsplit_once('/') {
219            Some((left, right)) => (left, right),
220            None => ("", remainder),
221        };
222        let name = percent_decode(name)?;
223        if name.is_empty() {
224            return Err(PurlError::Name);
225        }
226        let mut namespace = Vec::new();
227        for segment in remainder.split('/').filter(|segment| !segment.is_empty()) {
228            let segment = percent_decode(segment)?;
229            if segment.contains('/') {
230                return Err(PurlError::Namespace);
231            }
232            namespace.push(segment);
233        }
234        let purl = Self {
235            original: text.to_owned(),
236            package_type,
237            namespace,
238            name,
239            version,
240            qualifiers,
241            subpath,
242        };
243        // Percent-encoding can triple a component's length. Refusing here keeps
244        // the promise that every canonical form parses again.
245        if purl.canonical().text.len() > MAX_PURL_BYTES {
246            return Err(PurlError::TooLong);
247        }
248        Ok(purl)
249    }
250
251    /// Exactly the text that was parsed.
252    #[must_use]
253    pub fn as_str(&self) -> &str {
254        &self.original
255    }
256
257    /// The type, lowercased.
258    #[must_use]
259    pub fn package_type(&self) -> &str {
260        &self.package_type
261    }
262
263    /// The decoded namespace segments joined with `/`, or `None` when there
264    /// are none. No type-specific normalization is applied (see
265    /// [`Self::canonical`]).
266    #[must_use]
267    pub fn namespace(&self) -> Option<String> {
268        (!self.namespace.is_empty()).then(|| self.namespace.join("/"))
269    }
270
271    /// The decoded name, as written. No type-specific normalization is
272    /// applied (see [`Self::canonical`]).
273    #[must_use]
274    pub fn name(&self) -> &str {
275        &self.name
276    }
277
278    /// The decoded version, as written, or `None` when absent or empty.
279    #[must_use]
280    pub fn version(&self) -> Option<&str> {
281        self.version.as_deref()
282    }
283
284    /// Decoded qualifiers with non-empty values, keys lowercased, in key order.
285    pub fn qualifiers(&self) -> impl Iterator<Item = (&str, &str)> {
286        self.qualifiers
287            .iter()
288            .map(|(key, value)| (key.as_str(), value.as_str()))
289    }
290
291    /// The decoded value of one qualifier; `key` is matched in lowercase.
292    #[must_use]
293    pub fn qualifier(&self, key: &str) -> Option<&str> {
294        self.qualifiers
295            .get(&key.to_ascii_lowercase())
296            .map(String::as_str)
297    }
298
299    /// The decoded subpath segments joined with `/`, without empty, `.` and
300    /// `..` segments, or `None` when none remain.
301    #[must_use]
302    pub fn subpath(&self) -> Option<String> {
303        (!self.subpath.is_empty()).then(|| self.subpath.join("/"))
304    }
305
306    /// The canonical form: the generic rules, plus the type's own rules when
307    /// [`PurlRules`] has them ([`CanonicalPurl::rules`] says which).
308    ///
309    /// ```
310    /// use libtea_core::purl::{Purl, PurlRules};
311    ///
312    /// let purl = Purl::parse("pkg:PyPI/Django_Allauth@0.61.1RC1").unwrap();
313    /// assert_eq!(purl.name(), "Django_Allauth");
314    /// let canonical = purl.canonical();
315    /// assert_eq!(canonical.as_str(), "pkg:pypi/django-allauth@0.61.1rc1");
316    /// assert_eq!(canonical.rules(), PurlRules::Pypi);
317    /// ```
318    #[must_use]
319    pub fn canonical(&self) -> CanonicalPurl {
320        let rules = PurlRules::for_type(&self.package_type);
321        let mut out = String::with_capacity(self.original.len());
322        out.push_str("pkg:");
323        out.push_str(&self.package_type);
324        out.push('/');
325        for segment in &self.namespace {
326            percent_encode_into(segment, &mut out);
327            out.push('/');
328        }
329        match rules {
330            PurlRules::Pypi => percent_encode_into(&pypi_name(&self.name), &mut out),
331            PurlRules::Generic => percent_encode_into(&self.name, &mut out),
332        }
333        if let Some(version) = &self.version {
334            out.push('@');
335            match rules {
336                PurlRules::Pypi => percent_encode_into(&version.to_ascii_lowercase(), &mut out),
337                PurlRules::Generic => percent_encode_into(version, &mut out),
338            }
339        }
340        for (index, (key, value)) in self.qualifiers.iter().enumerate() {
341            out.push(if index == 0 { '?' } else { '&' });
342            out.push_str(key);
343            out.push('=');
344            percent_encode_into(value, &mut out);
345        }
346        for (index, segment) in self.subpath.iter().enumerate() {
347            out.push(if index == 0 { '#' } else { '/' });
348            percent_encode_into(segment, &mut out);
349        }
350        CanonicalPurl { text: out, rules }
351    }
352}
353
354/// PEP 503: lowercase, and each run of `-`, `_` and `.` becomes one `-`.
355fn pypi_name(name: &str) -> String {
356    let mut out = String::with_capacity(name.len());
357    let mut in_run = false;
358    for c in name.chars() {
359        if matches!(c, '-' | '_' | '.') {
360            if !in_run {
361                out.push('-');
362            }
363            in_run = true;
364        } else {
365            out.push(c.to_ascii_lowercase());
366            in_run = false;
367        }
368    }
369    out
370}
371
372/// ECMA-427 5.6.2: ASCII letters, digits, `.` and `-`, starting with a letter.
373fn valid_type(package_type: &str) -> bool {
374    let mut chars = package_type.chars();
375    chars.next().is_some_and(|c| c.is_ascii_alphabetic())
376        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-'))
377}
378
379/// ECMA-427 5.6.6, keys already lowercased: letters, digits, `.`, `-` and `_`,
380/// starting with a letter.
381fn valid_qualifier_key(key: &str) -> bool {
382    let mut chars = key.chars();
383    chars.next().is_some_and(|c| c.is_ascii_lowercase())
384        && chars
385            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '.' | '-' | '_'))
386}
387
388fn parse_qualifiers(text: &str) -> Result<BTreeMap<String, String>, PurlError> {
389    let mut qualifiers = BTreeMap::new();
390    for pair in text.split('&').filter(|pair| !pair.is_empty()) {
391        let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
392        let key = key.to_ascii_lowercase();
393        if !valid_qualifier_key(&key) {
394            return Err(PurlError::QualifierKey);
395        }
396        let value = percent_decode(value)?;
397        if value.is_empty() {
398            continue;
399        }
400        if qualifiers.insert(key, value).is_some() {
401            return Err(PurlError::DuplicateQualifier);
402        }
403    }
404    Ok(qualifiers)
405}
406
407fn parse_subpath(text: &str) -> Result<Vec<String>, PurlError> {
408    let mut segments = Vec::new();
409    for segment in text.split('/') {
410        let segment = percent_decode(segment)?;
411        if segment.is_empty() || segment == "." || segment == ".." {
412            continue;
413        }
414        if segment.contains('/') {
415            return Err(PurlError::Subpath);
416        }
417        segments.push(segment);
418    }
419    Ok(segments)
420}
421
422fn percent_decode(text: &str) -> Result<String, PurlError> {
423    if !text.contains('%') {
424        return Ok(text.to_owned());
425    }
426    let bytes = text.as_bytes();
427    let mut out = Vec::with_capacity(bytes.len());
428    let mut index = 0;
429    while index < bytes.len() {
430        if bytes[index] == b'%' {
431            let high = bytes.get(index + 1).and_then(|b| hex_value(*b));
432            let low = bytes.get(index + 2).and_then(|b| hex_value(*b));
433            let (Some(high), Some(low)) = (high, low) else {
434                return Err(PurlError::Encoding);
435            };
436            out.push(high << 4 | low);
437            index += 3;
438        } else {
439            out.push(bytes[index]);
440            index += 1;
441        }
442    }
443    String::from_utf8(out).map_err(|_| PurlError::Encoding)
444}
445
446fn hex_value(byte: u8) -> Option<u8> {
447    match byte {
448        b'0'..=b'9' => Some(byte - b'0'),
449        b'a'..=b'f' => Some(byte - b'a' + 10),
450        b'A'..=b'F' => Some(byte - b'A' + 10),
451        _ => None,
452    }
453}
454
455/// ECMA-427 5.4: alphanumerics, `.-_~` and `:` stay; every other UTF-8 octet
456/// becomes `%XX` with uppercase hex.
457fn percent_encode_into(text: &str, out: &mut String) {
458    const HEX: &[u8; 16] = b"0123456789ABCDEF";
459    for &byte in text.as_bytes() {
460        if byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_' | b'~' | b':') {
461            out.push(char::from(byte));
462        } else {
463            out.push('%');
464            out.push(char::from(HEX[usize::from(byte >> 4)]));
465            out.push(char::from(HEX[usize::from(byte & 0x0f)]));
466        }
467    }
468}
469
470#[cfg(test)]
471mod tests {
472    use super::*;
473
474    #[test]
475    fn original_text_is_kept_and_canonical_is_separate() {
476        let text = "pkg://NPM//%40angular/animation@12.3.1?B=2&a=1#/x/./y/";
477        let purl = Purl::parse(text).unwrap();
478        assert_eq!(purl.as_str(), text);
479        assert_eq!(purl.package_type(), "npm");
480        assert_eq!(purl.namespace().as_deref(), Some("@angular"));
481        assert_eq!(purl.name(), "animation");
482        assert_eq!(purl.version(), Some("12.3.1"));
483        assert_eq!(purl.qualifier("A"), Some("1"));
484        assert_eq!(purl.subpath().as_deref(), Some("x/y"));
485        assert_eq!(
486            purl.canonical().as_str(),
487            "pkg:npm/%40angular/animation@12.3.1?a=1&b=2#x/y"
488        );
489        assert_eq!(purl.canonical().rules(), PurlRules::Generic);
490    }
491
492    #[test]
493    fn an_unencoded_scope_is_not_a_version() {
494        let purl = Purl::parse("pkg:npm/@babel/core#lib").unwrap();
495        assert_eq!(purl.namespace().as_deref(), Some("@babel"));
496        assert_eq!(purl.name(), "core");
497        assert_eq!(purl.version(), None);
498        assert_eq!(purl.canonical().as_str(), "pkg:npm/%40babel/core#lib");
499        let versioned = Purl::parse("pkg:npm/@babel/core@7.0.0").unwrap();
500        assert_eq!(versioned.version(), Some("7.0.0"));
501    }
502
503    #[test]
504    fn canonical_is_idempotent_on_its_own_output() {
505        for text in [
506            "pkg:generic/a%20b@1.0%2B2?checksum=sha1:ab,sha256:cd",
507            "pkg:deb/debian/curl@7.50.3-1?arch=i386&distro=jessie",
508            "pkg:golang/github.com/gorilla/context@234fd47e07d1004f0aed9c#api",
509            "pkg:generic/%E2%82%AC@%C3%A9",
510        ] {
511            let once = Purl::parse(text).unwrap().canonical();
512            let twice = Purl::parse(once.as_str()).unwrap().canonical();
513            assert_eq!(once, twice, "{text}");
514        }
515    }
516
517    #[test]
518    fn rejected_inputs() {
519        let cases: &[(&str, PurlError)] = &[
520            ("EnterpriseLibrary.Common@6.0.1304", PurlError::Scheme),
521            ("http:npm/a", PurlError::Scheme),
522            ("pkg:npm", PurlError::Name),
523            ("pkg:npm/", PurlError::Name),
524            ("pkg:npm/@1.0", PurlError::Name),
525            ("pkg:/a", PurlError::Name),
526            ("pkg:9pm/a", PurlError::Type),
527            ("pkg:n+m/a", PurlError::Type),
528            ("pkg:n%70m/a", PurlError::Type),
529            ("pkg:npm/a?1key=v", PurlError::QualifierKey),
530            ("pkg:npm/a?k%65y=v", PurlError::QualifierKey),
531            ("pkg:npm/a?=v", PurlError::QualifierKey),
532            ("pkg:npm/a?k=1&K=2", PurlError::DuplicateQualifier),
533            ("pkg:npm/a%2Fb/c", PurlError::Namespace),
534            ("pkg:npm/a#b%2Fc", PurlError::Subpath),
535            ("pkg:npm/a%zz", PurlError::Encoding),
536            ("pkg:npm/a%c3", PurlError::Encoding),
537            ("pkg:npm/a@1%", PurlError::Encoding),
538        ];
539        for (text, error) in cases {
540            assert_eq!(Purl::parse(text).as_ref().err(), Some(error), "{text}");
541        }
542        let long = format!("pkg:generic/{}", "a".repeat(MAX_PURL_BYTES));
543        assert_eq!(Purl::parse(&long), Err(PurlError::TooLong));
544        // Short enough as text, too long once each space becomes `%20`.
545        let spaces = format!("pkg:generic/{}", " ".repeat(2000));
546        assert!(spaces.len() <= MAX_PURL_BYTES);
547        assert_eq!(Purl::parse(&spaces), Err(PurlError::TooLong));
548    }
549
550    #[test]
551    fn empty_qualifier_values_are_dropped_and_empty_version_is_none() {
552        let purl = Purl::parse("pkg:generic/a@?x=&y").unwrap();
553        assert_eq!(purl.version(), None);
554        assert_eq!(purl.qualifiers().count(), 0);
555        assert_eq!(purl.canonical().as_str(), "pkg:generic/a");
556    }
557
558    #[test]
559    fn names_are_not_case_folded_without_a_type_rule() {
560        // npm and maven names are case-sensitive in their type definitions.
561        for (a, b) in [
562            ("pkg:npm/Lodash@4.0.0", "pkg:npm/lodash@4.0.0"),
563            (
564                "pkg:maven/org.Apache/Commons@1",
565                "pkg:maven/org.apache/commons@1",
566            ),
567            ("pkg:generic/a_b@1", "pkg:generic/a-b@1"),
568        ] {
569            let (a, b) = (Purl::parse(a).unwrap(), Purl::parse(b).unwrap());
570            assert!(!same_package_url(&a, &b));
571            assert_eq!(a.canonical().rules(), PurlRules::Generic);
572        }
573    }
574
575    #[test]
576    fn pypi_names_and_versions_follow_the_type_definition() {
577        for (input, canonical) in [
578            ("pkg:pypi/Django@1.11.1", "pkg:pypi/django@1.11.1"),
579            ("pkg:pypi/friendly.bard@1.0", "pkg:pypi/friendly-bard@1.0"),
580            ("pkg:pypi/friendly--bard", "pkg:pypi/friendly-bard"),
581            (
582                "pkg:pypi/My.PyPI_.--._Package@1.11.1.DEV1",
583                "pkg:pypi/my-pypi-package@1.11.1.dev1",
584            ),
585            ("pkg:pypi/-a_", "pkg:pypi/-a-"),
586            ("pkg:pypi/a%2Eb", "pkg:pypi/a-b"),
587            // Qualifier values and the subpath keep their case.
588            (
589                "pkg:pypi/Django@1.0?file_name=Django-1.0.tar.gz#Docs",
590                "pkg:pypi/django@1.0?file_name=Django-1.0.tar.gz#Docs",
591            ),
592        ] {
593            let purl = Purl::parse(input).unwrap();
594            assert_eq!(purl.as_str(), input);
595            assert_eq!(purl.canonical().as_str(), canonical, "{input}");
596            assert_eq!(purl.canonical().rules(), PurlRules::Pypi);
597            let again = Purl::parse(canonical).unwrap().canonical();
598            assert_eq!(again.as_str(), canonical, "idempotent: {input}");
599        }
600        let a = Purl::parse("pkg:pypi/Zope.Interface@5.0").unwrap();
601        let b = Purl::parse("pkg:pypi/zope-interface@5.0").unwrap();
602        assert!(same_package_url(&a, &b));
603        // The accessors keep what was written.
604        assert_eq!(a.name(), "Zope.Interface");
605    }
606}