Skip to main content

libtea_core/
vers.rs

1//! `vers` version ranges (the version-range notation CLE and PURL use),
2//! parsed in full and evaluated for SemVer and PyPI versions.
3//!
4//! **Experimental:** may change in a 0.x minor release.
5//!
6//! [`VersRange::parse`] checks the syntax of any `vers:<type>/<constraints>`
7//! string. [`VersRange::contains_semver`] then evaluates it when its type
8//! compares versions as SemVer 2.0 ([`VersRange::is_semver_type`]): `semver`,
9//! and `npm`, whose registered `vers` type uses node-semver versions.
10//! [`VersRange::contains_pypi`] evaluates the `pypi` type with PEP 440
11//! ordering ([`crate::pep440`]). Every other type is reported as unsupported,
12//! never guessed.
13//!
14//! The rules are from the `vers` specification, release `v1.2.1` of
15//! <https://github.com/package-url/vers-spec> (`docs/specification/`):
16//! constraints are sorted by version, each version occurs once, `*` stands
17//! alone, and outside `!=` the comparators alternate between lower and upper
18//! bounds. A range that breaks these rules is an error, not corrected.
19
20use std::cmp::Ordering;
21
22use thiserror::Error;
23
24use crate::pep440::Pep440Version;
25
26/// Inputs longer than this are rejected with [`VersError::TooLong`].
27pub const MAX_VERS_BYTES: usize = 4096;
28
29/// Why a string is not a valid `vers` range, or could not be evaluated.
30///
31/// **Experimental:** may change in a 0.x minor release.
32#[derive(Debug, Clone, PartialEq, Eq, Error)]
33#[non_exhaustive]
34pub enum VersError {
35    /// Longer than [`MAX_VERS_BYTES`].
36    #[error("vers range is longer than {MAX_VERS_BYTES} bytes")]
37    TooLong,
38    /// The scheme is missing or is not lowercase `vers`.
39    #[error("vers range must start with `vers:`")]
40    Scheme,
41    /// The type is missing, not lowercase, does not start with a letter, or
42    /// has characters other than ASCII letters, digits, `.` and `-`.
43    #[error("vers type is missing or invalid")]
44    Type,
45    /// Nothing after `vers:<type>/`.
46    #[error("vers constraints are empty")]
47    Empty,
48    /// Literal ASCII whitespace anywhere in the string, or a decoded version
49    /// with whitespace other than a space.
50    #[error("vers range contains whitespace")]
51    Whitespace,
52    /// A leading, trailing or repeated `|`.
53    #[error("vers constraints have an empty segment")]
54    EmptyConstraint,
55    /// A constraint starts with `=`; equality is a bare version.
56    #[error("vers constraint starts with `=`")]
57    LeadingEquals,
58    /// A comparator with no version after it.
59    #[error("vers constraint has no version")]
60    EmptyVersion,
61    /// `*` together with other constraints, or `*` followed by a version.
62    #[error("vers `*` must stand alone")]
63    Asterisk,
64    /// A `%` not followed by two hex digits, decoded bytes that are not UTF-8,
65    /// or an unencoded character the specification reserves.
66    #[error("vers version has an invalid percent-encoding")]
67    Encoding,
68    /// The type is not one the evaluating method handles (SemVer types for
69    /// [`VersRange::contains_semver`], `pypi` for [`VersRange::contains_pypi`]).
70    #[error("vers type is not evaluated by this method")]
71    UnsupportedType,
72    /// A constraint version is not a SemVer 2.0 version.
73    #[error("vers version is not a SemVer version")]
74    NotSemver,
75    /// Constraints are not sorted by version, or a version occurs twice.
76    #[error("vers constraints are not sorted by version or repeat one")]
77    Order,
78    /// Comparators do not alternate between lower and upper bounds.
79    #[error("vers constraints have an invalid comparator sequence")]
80    Sequence,
81    /// A constraint version of a `pypi` range is not a PEP 440 version.
82    #[error("vers version is not a PEP 440 version")]
83    NotPep440,
84}
85
86/// The comparator of one constraint.
87///
88/// **Experimental:** may change in a 0.x minor release.
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
90#[non_exhaustive]
91pub enum Comparator {
92    /// A bare version: equal to it.
93    Equal,
94    /// `!=`: excluded.
95    NotEqual,
96    /// `<`.
97    Less,
98    /// `<=`.
99    LessOrEqual,
100    /// `>`.
101    Greater,
102    /// `>=`.
103    GreaterOrEqual,
104}
105
106impl Comparator {
107    /// The comparator as written in a range (empty for [`Self::Equal`]).
108    #[must_use]
109    pub fn as_str(self) -> &'static str {
110        match self {
111            Self::Equal => "",
112            Self::NotEqual => "!=",
113            Self::Less => "<",
114            Self::LessOrEqual => "<=",
115            Self::Greater => ">",
116            Self::GreaterOrEqual => ">=",
117        }
118    }
119
120    fn is_upper(self) -> bool {
121        matches!(self, Self::Less | Self::LessOrEqual)
122    }
123
124    fn is_lower(self) -> bool {
125        matches!(self, Self::Greater | Self::GreaterOrEqual)
126    }
127}
128
129/// One constraint: a comparator and a percent-decoded version.
130///
131/// **Experimental:** may change in a 0.x minor release.
132#[derive(Debug, Clone, PartialEq, Eq, Hash)]
133pub struct Constraint {
134    comparator: Comparator,
135    version: String,
136}
137
138impl Constraint {
139    /// The comparator.
140    #[must_use]
141    pub fn comparator(&self) -> Comparator {
142        self.comparator
143    }
144
145    /// The version, percent-decoded once.
146    #[must_use]
147    pub fn version(&self) -> &str {
148        &self.version
149    }
150}
151
152/// A parsed `vers` range.
153///
154/// **Experimental:** may change in a 0.x minor release.
155///
156/// ```
157/// use libtea_core::vers::VersRange;
158///
159/// let range = VersRange::parse("vers:npm/>=1.0.0|!=1.2.0|<2.0.0").unwrap();
160/// let v = |s: &str| semver::Version::parse(s).unwrap();
161/// assert_eq!(range.contains_semver(&v("1.5.0")), Ok(true));
162/// assert_eq!(range.contains_semver(&v("1.2.0")), Ok(false));
163/// assert_eq!(range.contains_semver(&v("2.0.0")), Ok(false));
164/// assert_eq!(range.contains_semver(&v("2.0.0-rc.1")), Ok(true));
165/// ```
166#[derive(Debug, Clone, PartialEq, Eq, Hash)]
167pub struct VersRange {
168    version_type: String,
169    any: bool,
170    constraints: Vec<Constraint>,
171}
172
173impl VersRange {
174    /// Parse `vers:<type>/<constraints>` as the specification's
175    /// "How to parse" describes. Ordering and comparator rules depend on how
176    /// the type compares versions, so they are checked by
177    /// [`Self::contains_semver`], not here.
178    ///
179    /// # Errors
180    ///
181    /// Returns [`VersError`] for a missing or wrong scheme or type, empty
182    /// constraints or constraint segments, whitespace, a leading `=`, an empty
183    /// version, a misplaced `*`, invalid percent-encoding, or a string longer
184    /// than [`MAX_VERS_BYTES`].
185    pub fn parse(text: &str) -> Result<Self, VersError> {
186        if text.len() > MAX_VERS_BYTES {
187            return Err(VersError::TooLong);
188        }
189        if text.bytes().any(|b| b.is_ascii_whitespace()) {
190            return Err(VersError::Whitespace);
191        }
192        let (scheme, specifier) = text.split_once(':').ok_or(VersError::Scheme)?;
193        if scheme != "vers" {
194            return Err(VersError::Scheme);
195        }
196        let (version_type, constraints) = specifier.split_once('/').ok_or(VersError::Type)?;
197        if !valid_type(version_type) {
198            return Err(VersError::Type);
199        }
200        if constraints.is_empty() {
201            return Err(VersError::Empty);
202        }
203        if constraints == "*" {
204            return Ok(Self {
205                version_type: version_type.to_owned(),
206                any: true,
207                constraints: Vec::new(),
208            });
209        }
210        let mut parsed = Vec::new();
211        for segment in constraints.split('|') {
212            if segment.is_empty() {
213                return Err(VersError::EmptyConstraint);
214            }
215            if segment.contains('*') {
216                return Err(VersError::Asterisk);
217            }
218            let (comparator, rest) = split_comparator(segment)?;
219            if rest.is_empty() {
220                return Err(VersError::EmptyVersion);
221            }
222            if rest.contains(['<', '>', '=', '!']) {
223                return Err(VersError::Encoding);
224            }
225            let version = percent_decode(rest)?;
226            // Only an encoded space is allowed; `%09` is still a tab.
227            if version
228                .bytes()
229                .any(|b| b.is_ascii_whitespace() && b != b' ')
230            {
231                return Err(VersError::Whitespace);
232            }
233            parsed.push(Constraint {
234                comparator,
235                version,
236            });
237        }
238        Ok(Self {
239            version_type: version_type.to_owned(),
240            any: false,
241            constraints: parsed,
242        })
243    }
244
245    /// The `vers` type, such as `npm` or `semver`.
246    #[must_use]
247    pub fn version_type(&self) -> &str {
248        &self.version_type
249    }
250
251    /// Whether the range is `*` (every version).
252    #[must_use]
253    pub fn is_any(&self) -> bool {
254        self.any
255    }
256
257    /// The constraints in the order written. Empty for `*`.
258    #[must_use]
259    pub fn constraints(&self) -> &[Constraint] {
260        &self.constraints
261    }
262
263    /// Whether this type's versions are compared as SemVer 2.0 here:
264    /// `semver`, and `npm` (node-semver versions).
265    #[must_use]
266    pub fn is_semver_type(&self) -> bool {
267        matches!(self.version_type.as_str(), "semver" | "npm")
268    }
269
270    /// Whether `version` is in the range, comparing as SemVer 2.0 (build
271    /// metadata ignored, pre-releases ordered before their release).
272    ///
273    /// The range is validated first: constraint versions must be SemVer,
274    /// sorted, unique, and in a valid comparator sequence.
275    ///
276    /// # Errors
277    ///
278    /// [`VersError::UnsupportedType`] when [`Self::is_semver_type`] is false,
279    /// [`VersError::NotSemver`] for a constraint version that does not parse,
280    /// and [`VersError::Order`] or [`VersError::Sequence`] for a range the
281    /// specification calls invalid.
282    pub fn contains_semver(&self, version: &semver::Version) -> Result<bool, VersError> {
283        if !self.is_semver_type() {
284            return Err(VersError::UnsupportedType);
285        }
286        self.contains_with(
287            version,
288            |text| semver::Version::parse(text).map_err(|_| VersError::NotSemver),
289            precedence,
290        )
291    }
292
293    /// Whether this range's versions are compared as PEP 440 versions here:
294    /// the `pypi` type.
295    #[must_use]
296    pub fn is_pypi_type(&self) -> bool {
297        self.version_type == "pypi"
298    }
299
300    /// Whether `version` is in the range, comparing with PEP 440 ordering
301    /// ([`crate::pep440`]): `1.0 == 1.0.0`, and
302    /// `1.0.dev1 < 1.0a1 < 1.0 < 1.0.post1 < 1.0.1`.
303    ///
304    /// Only the ordering is used, as `vers` asks: PEP 440's own specifier
305    /// rules (such as `<1.0` excluding `1.0a1`) do not apply, so
306    /// `vers:pypi/<1.0` contains `1.0a1`. The range is validated first, as
307    /// for [`Self::contains_semver`].
308    ///
309    /// ```
310    /// use libtea_core::pep440::Pep440Version;
311    /// use libtea_core::vers::VersRange;
312    ///
313    /// let range = VersRange::parse("vers:pypi/>=1.0|<2.0").unwrap();
314    /// let v = |s: &str| Pep440Version::parse(s).unwrap();
315    /// assert_eq!(range.contains_pypi(&v("1.5.post1")), Ok(true));
316    /// assert_eq!(range.contains_pypi(&v("1.0.0")), Ok(true));
317    /// assert_eq!(range.contains_pypi(&v("2.0rc1")), Ok(true));
318    /// assert_eq!(range.contains_pypi(&v("2.0")), Ok(false));
319    /// ```
320    ///
321    /// # Errors
322    ///
323    /// [`VersError::UnsupportedType`] when [`Self::is_pypi_type`] is false,
324    /// [`VersError::NotPep440`] for a constraint version that does not parse,
325    /// and [`VersError::Order`] or [`VersError::Sequence`] for a range the
326    /// specification calls invalid (including `1.0|1.0.0`, which repeats a
327    /// version).
328    pub fn contains_pypi(&self, version: &Pep440Version) -> Result<bool, VersError> {
329        if !self.is_pypi_type() {
330            return Err(VersError::UnsupportedType);
331        }
332        self.contains_with(
333            version,
334            |text| Pep440Version::parse(text).map_err(|_| VersError::NotPep440),
335            Ord::cmp,
336        )
337    }
338
339    /// Validate the constraints and evaluate them for `version`, with
340    /// `parse` for constraint versions and `order` for comparing them.
341    fn contains_with<T>(
342        &self,
343        version: &T,
344        parse: impl Fn(&str) -> Result<T, VersError>,
345        order: impl Fn(&T, &T) -> Ordering,
346    ) -> Result<bool, VersError> {
347        if self.any {
348            return Ok(true);
349        }
350        let mut bounds = Vec::with_capacity(self.constraints.len());
351        for constraint in &self.constraints {
352            bounds.push((constraint.comparator, parse(&constraint.version)?));
353        }
354        validate(&bounds, &order)?;
355
356        // Equality first: an inclusive constraint on the version includes it,
357        // a `!=` on it excludes it. Versions are unique, so these never clash.
358        for (comparator, bound) in &bounds {
359            if order(version, bound) == Ordering::Equal {
360                // `!=` excludes it; `<` and `>` do not include their own version.
361                return Ok(!matches!(
362                    comparator,
363                    Comparator::NotEqual | Comparator::Less | Comparator::Greater
364                ));
365            }
366        }
367        // Then the intervals the remaining bounds describe, in version order.
368        let ranges: Vec<_> = bounds
369            .iter()
370            .filter(|(comparator, _)| comparator.is_lower() || comparator.is_upper())
371            .collect();
372        for (index, (comparator, bound)) in ranges.iter().enumerate() {
373            let below = order(version, bound) == Ordering::Less;
374            if comparator.is_upper() {
375                // An upper bound opens the range when it is the first bound,
376                // or closes the interval the previous lower bound opened.
377                let opened = match index.checked_sub(1).map(|i| ranges[i]) {
378                    None => true,
379                    Some((previous, lower)) => {
380                        previous.is_lower() && order(version, lower) == Ordering::Greater
381                    }
382                };
383                if opened && below {
384                    return Ok(true);
385                }
386            } else if index + 1 == ranges.len() && order(version, bound) == Ordering::Greater {
387                // A lower bound with nothing after it is open to the top.
388                return Ok(true);
389            }
390        }
391        Ok(false)
392    }
393}
394
395/// SemVer 2.0 precedence: build metadata does not count.
396fn precedence(a: &semver::Version, b: &semver::Version) -> Ordering {
397    (a.major, a.minor, a.patch, &a.pre).cmp(&(b.major, b.minor, b.patch, &b.pre))
398}
399
400/// Specification section 5.4: sorted and unique, then the comparator rules
401/// for contiguous constraints.
402fn validate<T>(
403    bounds: &[(Comparator, T)],
404    order: impl Fn(&T, &T) -> Ordering,
405) -> Result<(), VersError> {
406    if bounds
407        .windows(2)
408        .any(|pair| order(&pair[0].1, &pair[1].1) != Ordering::Less)
409    {
410        return Err(VersError::Order);
411    }
412    let without_unequal: Vec<_> = bounds
413        .iter()
414        .map(|(comparator, _)| *comparator)
415        .filter(|comparator| *comparator != Comparator::NotEqual)
416        .collect();
417    // A bare version is followed only by a bare version or a lower bound, and
418    // a lower bound is never followed by a bare version (it would be inside
419    // the interval already, which "How to parse" calls redundant).
420    for pair in without_unequal.windows(2) {
421        if (pair[0] == Comparator::Equal && pair[1].is_upper())
422            || (pair[0].is_lower() && pair[1] == Comparator::Equal)
423        {
424            return Err(VersError::Sequence);
425        }
426    }
427    let bounds_only: Vec<_> = without_unequal
428        .iter()
429        .filter(|comparator| **comparator != Comparator::Equal)
430        .collect();
431    for pair in bounds_only.windows(2) {
432        if pair[0].is_upper() == pair[1].is_upper() {
433            return Err(VersError::Sequence);
434        }
435    }
436    Ok(())
437}
438
439fn split_comparator(segment: &str) -> Result<(Comparator, &str), VersError> {
440    for (prefix, comparator) in [
441        (">=", Comparator::GreaterOrEqual),
442        ("<=", Comparator::LessOrEqual),
443        ("!=", Comparator::NotEqual),
444        ("<", Comparator::Less),
445        (">", Comparator::Greater),
446    ] {
447        if let Some(rest) = segment.strip_prefix(prefix) {
448            return Ok((comparator, rest));
449        }
450    }
451    if segment.starts_with('=') {
452        return Err(VersError::LeadingEquals);
453    }
454    Ok((Comparator::Equal, segment))
455}
456
457/// Section 5.3.2: lowercase ASCII letters, digits, `.` and `-`, starting with a letter.
458fn valid_type(version_type: &str) -> bool {
459    let mut chars = version_type.chars();
460    chars.next().is_some_and(|c| c.is_ascii_lowercase())
461        && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '.' | '-'))
462}
463
464fn percent_decode(text: &str) -> Result<String, VersError> {
465    let bytes = text.as_bytes();
466    let mut out = Vec::with_capacity(bytes.len());
467    let mut index = 0;
468    while index < bytes.len() {
469        if bytes[index] == b'%' {
470            let digit = |offset: usize| {
471                bytes
472                    .get(index + offset)
473                    .and_then(|b| char::from(*b).to_digit(16))
474            };
475            let (Some(high), Some(low)) = (digit(1), digit(2)) else {
476                return Err(VersError::Encoding);
477            };
478            out.push((high * 16 + low) as u8);
479            index += 3;
480        } else {
481            out.push(bytes[index]);
482            index += 1;
483        }
484    }
485    String::from_utf8(out).map_err(|_| VersError::Encoding)
486}
487
488#[cfg(test)]
489mod tests {
490    use super::*;
491
492    fn v(text: &str) -> semver::Version {
493        semver::Version::parse(text).unwrap()
494    }
495
496    fn contains(range: &str, version: &str) -> bool {
497        VersRange::parse(range)
498            .unwrap()
499            .contains_semver(&v(version))
500            .unwrap()
501    }
502
503    #[test]
504    fn single_bounds_and_equality() {
505        assert!(contains("vers:semver/>=1.0.0", "1.0.0"));
506        assert!(contains("vers:semver/>=1.0.0", "9.0.0"));
507        assert!(!contains("vers:semver/>=1.0.0", "0.9.9"));
508        assert!(!contains("vers:semver/>1.0.0", "1.0.0"));
509        assert!(contains("vers:semver/<2.0.0", "0.0.1"));
510        assert!(!contains("vers:semver/<2.0.0", "2.0.0"));
511        assert!(contains("vers:semver/<=2.0.0", "2.0.0"));
512        assert!(contains("vers:semver/1.2.3", "1.2.3"));
513        assert!(!contains("vers:semver/1.2.3", "1.2.4"));
514        assert!(contains("vers:semver/*", "0.0.0"));
515    }
516
517    #[test]
518    fn several_intervals_exclusions_and_points() {
519        let range = "vers:npm/<1.4.1|>=2.0.0|<2.17.2";
520        assert!(contains(range, "1.0.0"));
521        assert!(!contains(range, "1.4.1"));
522        assert!(!contains(range, "1.9.0"));
523        assert!(contains(range, "2.0.0"));
524        assert!(contains(range, "2.17.1"));
525        assert!(!contains(range, "2.17.2"));
526        let gaps = "vers:npm/>=2.2.6|<2.47.0|>2.51.0|<=2.67.0";
527        assert!(!contains(gaps, "2.51.0"));
528        assert!(contains(gaps, "2.60.0"));
529        assert!(contains(gaps, "2.67.0"));
530        assert!(!contains(gaps, "2.68.0"));
531        let points = "vers:semver/1.0.0|1.1.0|>=2.0.0";
532        assert!(contains(points, "1.1.0"));
533        assert!(!contains(points, "1.0.5"));
534        assert!(contains(points, "3.0.0"));
535        let excluded = "vers:semver/>=1.0.0|!=1.5.0|<2.0.0";
536        assert!(!contains(excluded, "1.5.0"));
537        assert!(contains(excluded, "1.5.1"));
538    }
539
540    #[test]
541    fn prerelease_and_build_metadata() {
542        assert!(contains("vers:semver/<1.0.0", "1.0.0-rc.1"));
543        assert!(contains("vers:semver/>=1.0.0-rc.1|<1.0.0", "1.0.0-rc.2"));
544        // Build metadata is not part of precedence.
545        assert!(contains("vers:semver/1.0.0", "1.0.0+build.7"));
546        assert!(contains("vers:semver/1.0.0+a", "1.0.0"));
547    }
548
549    #[test]
550    fn invalid_ranges_are_errors_not_corrected() {
551        let check = |range: &str| {
552            VersRange::parse(range)
553                .and_then(|r| r.contains_semver(&v("1.0.0")))
554                .unwrap_err()
555        };
556        assert_eq!(check("vers:semver/<2.0.0|>=1.0.0"), VersError::Order);
557        assert_eq!(check("vers:semver/>=1.0.0|<1.0.0"), VersError::Order);
558        assert_eq!(check("vers:semver/>=1.0.0|>=2.0.0"), VersError::Sequence);
559        assert_eq!(check("vers:semver/<1.0.0|<2.0.0"), VersError::Sequence);
560        assert_eq!(check("vers:semver/1.0.0|<2.0.0"), VersError::Sequence);
561        assert_eq!(check("vers:semver/>=1.0.0|1.5.0"), VersError::Sequence);
562        assert_eq!(
563            check("vers:semver/>=1.0.0|1.5.0|<2.0.0"),
564            VersError::Sequence
565        );
566        assert_eq!(check("vers:semver/1.0"), VersError::NotSemver);
567        assert_eq!(check("vers:pypi/>=1.0"), VersError::UnsupportedType);
568    }
569
570    fn contains_pypi(range: &str, version: &str) -> Result<bool, VersError> {
571        VersRange::parse(range)
572            .unwrap()
573            .contains_pypi(&Pep440Version::parse(version).unwrap())
574    }
575
576    #[test]
577    fn pypi_ranges_use_pep440_ordering() {
578        let range = "vers:pypi/>=1.0|!=1.5|<2.0";
579        assert_eq!(contains_pypi(range, "1.0.0"), Ok(true));
580        assert_eq!(contains_pypi(range, "1.0.dev1"), Ok(false));
581        assert_eq!(contains_pypi(range, "1.5.0"), Ok(false));
582        assert_eq!(contains_pypi(range, "1.5.post1"), Ok(true));
583        assert_eq!(contains_pypi(range, "2.0rc1"), Ok(true));
584        assert_eq!(contains_pypi(range, "2.0"), Ok(false));
585        assert_eq!(contains_pypi(range, "1!0.1"), Ok(false));
586        assert_eq!(contains_pypi("vers:pypi/1.0", "1.0.0+local"), Ok(false));
587        assert_eq!(contains_pypi("vers:pypi/*", "0"), Ok(true));
588        // Spelled differently, the same version twice.
589        assert_eq!(
590            contains_pypi("vers:pypi/1.0|1.0.0", "1"),
591            Err(VersError::Order)
592        );
593        assert_eq!(
594            contains_pypi("vers:pypi/2.0|<1.0", "1"),
595            Err(VersError::Order)
596        );
597        assert_eq!(
598            contains_pypi("vers:pypi/>=1.0|latest", "1"),
599            Err(VersError::NotPep440)
600        );
601        assert_eq!(
602            VersRange::parse("vers:npm/1.0.0")
603                .unwrap()
604                .contains_pypi(&Pep440Version::parse("1.0.0").unwrap()),
605            Err(VersError::UnsupportedType)
606        );
607        assert_eq!(
608            VersRange::parse("vers:pypi/1.0.0")
609                .unwrap()
610                .contains_semver(&v("1.0.0")),
611            Err(VersError::UnsupportedType)
612        );
613    }
614
615    #[test]
616    fn syntax_errors() {
617        let cases: &[(&str, VersError)] = &[
618            ("npm/>=1.0.0", VersError::Scheme),
619            ("VERS:npm/1.0.0", VersError::Scheme),
620            ("vers:NPM/1.0.0", VersError::Type),
621            ("vers:1npm/1.0.0", VersError::Type),
622            ("vers:npm", VersError::Type),
623            ("vers:npm/", VersError::Empty),
624            ("vers:npm/>=1.0.0| <2.0.0", VersError::Whitespace),
625            ("vers:npm/|1.0.0", VersError::EmptyConstraint),
626            ("vers:npm/1.0.0|", VersError::EmptyConstraint),
627            ("vers:npm/1.0.0||2.0.0", VersError::EmptyConstraint),
628            ("vers:npm/=1.0.0", VersError::LeadingEquals),
629            ("vers:npm/>=", VersError::EmptyVersion),
630            ("vers:npm/*|1.0.0", VersError::Asterisk),
631            ("vers:npm/>=*", VersError::Asterisk),
632            ("vers:npm/1.0%zz", VersError::Encoding),
633            ("vers:npm/>==1.0.0", VersError::Encoding),
634        ];
635        for (range, error) in cases {
636            assert_eq!(
637                VersRange::parse(range).as_ref().err(),
638                Some(error),
639                "{range}"
640            );
641        }
642    }
643
644    #[test]
645    fn versions_are_decoded_once() {
646        let range = VersRange::parse("vers:generic/1.0%2520a").unwrap();
647        assert_eq!(range.constraints()[0].version(), "1.0%20a");
648        assert_eq!(range.constraints()[0].comparator().as_str(), "");
649    }
650}