use std::cmp::Ordering;
use thiserror::Error;
pub const MAX_VERS_BYTES: usize = 4096;
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum VersError {
#[error("vers range is longer than {MAX_VERS_BYTES} bytes")]
TooLong,
#[error("vers range must start with `vers:`")]
Scheme,
#[error("vers type is missing or invalid")]
Type,
#[error("vers constraints are empty")]
Empty,
#[error("vers range contains whitespace")]
Whitespace,
#[error("vers constraints have an empty segment")]
EmptyConstraint,
#[error("vers constraint starts with `=`")]
LeadingEquals,
#[error("vers constraint has no version")]
EmptyVersion,
#[error("vers `*` must stand alone")]
Asterisk,
#[error("vers version has an invalid percent-encoding")]
Encoding,
#[error("vers type is not evaluated as SemVer")]
UnsupportedType,
#[error("vers version is not a SemVer version")]
NotSemver,
#[error("vers constraints are not sorted by version or repeat one")]
Order,
#[error("vers constraints have an invalid comparator sequence")]
Sequence,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Comparator {
Equal,
NotEqual,
Less,
LessOrEqual,
Greater,
GreaterOrEqual,
}
impl Comparator {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Equal => "",
Self::NotEqual => "!=",
Self::Less => "<",
Self::LessOrEqual => "<=",
Self::Greater => ">",
Self::GreaterOrEqual => ">=",
}
}
fn is_upper(self) -> bool {
matches!(self, Self::Less | Self::LessOrEqual)
}
fn is_lower(self) -> bool {
matches!(self, Self::Greater | Self::GreaterOrEqual)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Constraint {
comparator: Comparator,
version: String,
}
impl Constraint {
#[must_use]
pub fn comparator(&self) -> Comparator {
self.comparator
}
#[must_use]
pub fn version(&self) -> &str {
&self.version
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct VersRange {
version_type: String,
any: bool,
constraints: Vec<Constraint>,
}
impl VersRange {
pub fn parse(text: &str) -> Result<Self, VersError> {
if text.len() > MAX_VERS_BYTES {
return Err(VersError::TooLong);
}
if text.bytes().any(|b| b.is_ascii_whitespace()) {
return Err(VersError::Whitespace);
}
let (scheme, specifier) = text.split_once(':').ok_or(VersError::Scheme)?;
if scheme != "vers" {
return Err(VersError::Scheme);
}
let (version_type, constraints) = specifier.split_once('/').ok_or(VersError::Type)?;
if !valid_type(version_type) {
return Err(VersError::Type);
}
if constraints.is_empty() {
return Err(VersError::Empty);
}
if constraints == "*" {
return Ok(Self {
version_type: version_type.to_owned(),
any: true,
constraints: Vec::new(),
});
}
let mut parsed = Vec::new();
for segment in constraints.split('|') {
if segment.is_empty() {
return Err(VersError::EmptyConstraint);
}
if segment.contains('*') {
return Err(VersError::Asterisk);
}
let (comparator, rest) = split_comparator(segment)?;
if rest.is_empty() {
return Err(VersError::EmptyVersion);
}
if rest.contains(['<', '>', '=', '!']) {
return Err(VersError::Encoding);
}
let version = percent_decode(rest)?;
if version
.bytes()
.any(|b| b.is_ascii_whitespace() && b != b' ')
{
return Err(VersError::Whitespace);
}
parsed.push(Constraint {
comparator,
version,
});
}
Ok(Self {
version_type: version_type.to_owned(),
any: false,
constraints: parsed,
})
}
#[must_use]
pub fn version_type(&self) -> &str {
&self.version_type
}
#[must_use]
pub fn is_any(&self) -> bool {
self.any
}
#[must_use]
pub fn constraints(&self) -> &[Constraint] {
&self.constraints
}
#[must_use]
pub fn is_semver_type(&self) -> bool {
matches!(self.version_type.as_str(), "semver" | "npm")
}
pub fn contains_semver(&self, version: &semver::Version) -> Result<bool, VersError> {
if !self.is_semver_type() {
return Err(VersError::UnsupportedType);
}
if self.any {
return Ok(true);
}
let mut bounds = Vec::with_capacity(self.constraints.len());
for constraint in &self.constraints {
let parsed =
semver::Version::parse(&constraint.version).map_err(|_| VersError::NotSemver)?;
bounds.push((constraint.comparator, parsed));
}
validate(&bounds)?;
for (comparator, bound) in &bounds {
if precedence(version, bound) == Ordering::Equal {
return Ok(!matches!(
comparator,
Comparator::NotEqual | Comparator::Less | Comparator::Greater
));
}
}
let ranges: Vec<_> = bounds
.iter()
.filter(|(comparator, _)| comparator.is_lower() || comparator.is_upper())
.collect();
for (index, (comparator, bound)) in ranges.iter().enumerate() {
let below = precedence(version, bound) == Ordering::Less;
if comparator.is_upper() {
let opened = match index.checked_sub(1).map(|i| ranges[i]) {
None => true,
Some((previous, lower)) => {
previous.is_lower() && precedence(version, lower) == Ordering::Greater
}
};
if opened && below {
return Ok(true);
}
} else if index + 1 == ranges.len() && precedence(version, bound) == Ordering::Greater {
return Ok(true);
}
}
Ok(false)
}
}
fn precedence(a: &semver::Version, b: &semver::Version) -> Ordering {
(a.major, a.minor, a.patch, &a.pre).cmp(&(b.major, b.minor, b.patch, &b.pre))
}
fn validate(bounds: &[(Comparator, semver::Version)]) -> Result<(), VersError> {
if bounds
.windows(2)
.any(|pair| precedence(&pair[0].1, &pair[1].1) != Ordering::Less)
{
return Err(VersError::Order);
}
let without_unequal: Vec<_> = bounds
.iter()
.map(|(comparator, _)| *comparator)
.filter(|comparator| *comparator != Comparator::NotEqual)
.collect();
for pair in without_unequal.windows(2) {
if (pair[0] == Comparator::Equal && pair[1].is_upper())
|| (pair[0].is_lower() && pair[1] == Comparator::Equal)
{
return Err(VersError::Sequence);
}
}
let bounds_only: Vec<_> = without_unequal
.iter()
.filter(|comparator| **comparator != Comparator::Equal)
.collect();
for pair in bounds_only.windows(2) {
if pair[0].is_upper() == pair[1].is_upper() {
return Err(VersError::Sequence);
}
}
Ok(())
}
fn split_comparator(segment: &str) -> Result<(Comparator, &str), VersError> {
for (prefix, comparator) in [
(">=", Comparator::GreaterOrEqual),
("<=", Comparator::LessOrEqual),
("!=", Comparator::NotEqual),
("<", Comparator::Less),
(">", Comparator::Greater),
] {
if let Some(rest) = segment.strip_prefix(prefix) {
return Ok((comparator, rest));
}
}
if segment.starts_with('=') {
return Err(VersError::LeadingEquals);
}
Ok((Comparator::Equal, segment))
}
fn valid_type(version_type: &str) -> bool {
let mut chars = version_type.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 percent_decode(text: &str) -> Result<String, VersError> {
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 digit = |offset: usize| {
bytes
.get(index + offset)
.and_then(|b| char::from(*b).to_digit(16))
};
let (Some(high), Some(low)) = (digit(1), digit(2)) else {
return Err(VersError::Encoding);
};
out.push((high * 16 + low) as u8);
index += 3;
} else {
out.push(bytes[index]);
index += 1;
}
}
String::from_utf8(out).map_err(|_| VersError::Encoding)
}
#[cfg(test)]
mod tests {
use super::*;
fn v(text: &str) -> semver::Version {
semver::Version::parse(text).unwrap()
}
fn contains(range: &str, version: &str) -> bool {
VersRange::parse(range)
.unwrap()
.contains_semver(&v(version))
.unwrap()
}
#[test]
fn single_bounds_and_equality() {
assert!(contains("vers:semver/>=1.0.0", "1.0.0"));
assert!(contains("vers:semver/>=1.0.0", "9.0.0"));
assert!(!contains("vers:semver/>=1.0.0", "0.9.9"));
assert!(!contains("vers:semver/>1.0.0", "1.0.0"));
assert!(contains("vers:semver/<2.0.0", "0.0.1"));
assert!(!contains("vers:semver/<2.0.0", "2.0.0"));
assert!(contains("vers:semver/<=2.0.0", "2.0.0"));
assert!(contains("vers:semver/1.2.3", "1.2.3"));
assert!(!contains("vers:semver/1.2.3", "1.2.4"));
assert!(contains("vers:semver/*", "0.0.0"));
}
#[test]
fn several_intervals_exclusions_and_points() {
let range = "vers:npm/<1.4.1|>=2.0.0|<2.17.2";
assert!(contains(range, "1.0.0"));
assert!(!contains(range, "1.4.1"));
assert!(!contains(range, "1.9.0"));
assert!(contains(range, "2.0.0"));
assert!(contains(range, "2.17.1"));
assert!(!contains(range, "2.17.2"));
let gaps = "vers:npm/>=2.2.6|<2.47.0|>2.51.0|<=2.67.0";
assert!(!contains(gaps, "2.51.0"));
assert!(contains(gaps, "2.60.0"));
assert!(contains(gaps, "2.67.0"));
assert!(!contains(gaps, "2.68.0"));
let points = "vers:semver/1.0.0|1.1.0|>=2.0.0";
assert!(contains(points, "1.1.0"));
assert!(!contains(points, "1.0.5"));
assert!(contains(points, "3.0.0"));
let excluded = "vers:semver/>=1.0.0|!=1.5.0|<2.0.0";
assert!(!contains(excluded, "1.5.0"));
assert!(contains(excluded, "1.5.1"));
}
#[test]
fn prerelease_and_build_metadata() {
assert!(contains("vers:semver/<1.0.0", "1.0.0-rc.1"));
assert!(contains("vers:semver/>=1.0.0-rc.1|<1.0.0", "1.0.0-rc.2"));
assert!(contains("vers:semver/1.0.0", "1.0.0+build.7"));
assert!(contains("vers:semver/1.0.0+a", "1.0.0"));
}
#[test]
fn invalid_ranges_are_errors_not_corrected() {
let check = |range: &str| {
VersRange::parse(range)
.and_then(|r| r.contains_semver(&v("1.0.0")))
.unwrap_err()
};
assert_eq!(check("vers:semver/<2.0.0|>=1.0.0"), VersError::Order);
assert_eq!(check("vers:semver/>=1.0.0|<1.0.0"), VersError::Order);
assert_eq!(check("vers:semver/>=1.0.0|>=2.0.0"), VersError::Sequence);
assert_eq!(check("vers:semver/<1.0.0|<2.0.0"), VersError::Sequence);
assert_eq!(check("vers:semver/1.0.0|<2.0.0"), VersError::Sequence);
assert_eq!(check("vers:semver/>=1.0.0|1.5.0"), VersError::Sequence);
assert_eq!(
check("vers:semver/>=1.0.0|1.5.0|<2.0.0"),
VersError::Sequence
);
assert_eq!(check("vers:semver/1.0"), VersError::NotSemver);
assert_eq!(check("vers:pypi/>=1.0"), VersError::UnsupportedType);
}
#[test]
fn syntax_errors() {
let cases: &[(&str, VersError)] = &[
("npm/>=1.0.0", VersError::Scheme),
("VERS:npm/1.0.0", VersError::Scheme),
("vers:NPM/1.0.0", VersError::Type),
("vers:1npm/1.0.0", VersError::Type),
("vers:npm", VersError::Type),
("vers:npm/", VersError::Empty),
("vers:npm/>=1.0.0| <2.0.0", VersError::Whitespace),
("vers:npm/|1.0.0", VersError::EmptyConstraint),
("vers:npm/1.0.0|", VersError::EmptyConstraint),
("vers:npm/1.0.0||2.0.0", VersError::EmptyConstraint),
("vers:npm/=1.0.0", VersError::LeadingEquals),
("vers:npm/>=", VersError::EmptyVersion),
("vers:npm/*|1.0.0", VersError::Asterisk),
("vers:npm/>=*", VersError::Asterisk),
("vers:npm/1.0%zz", VersError::Encoding),
("vers:npm/>==1.0.0", VersError::Encoding),
];
for (range, error) in cases {
assert_eq!(
VersRange::parse(range).as_ref().err(),
Some(error),
"{range}"
);
}
}
#[test]
fn versions_are_decoded_once() {
let range = VersRange::parse("vers:generic/1.0%2520a").unwrap();
assert_eq!(range.constraints()[0].version(), "1.0%20a");
assert_eq!(range.constraints()[0].comparator().as_str(), "");
}
}