use std::cmp::Ordering;
use std::fmt;
#[cfg(test)]
mod tests;
const MAX_VERSION_LEN: usize = 256;
const MAX_CONSTRAINT_LEN: usize = 512;
const MAX_CONSTRAINT_GROUPS: usize = 32;
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error("version string is too long (max {MAX_VERSION_LEN} bytes)")]
VersionTooLong,
#[error("invalid semantic version")]
InvalidVersion,
#[error("version segment starts with 0")]
SegmentStartsZero,
#[error("error parsing version segment: number too large")]
SegmentTooLarge,
#[error("constraint string is too long (max {MAX_CONSTRAINT_LEN} bytes)")]
ConstraintTooLong,
#[error("too many constraint groups (max {MAX_CONSTRAINT_GROUPS})")]
TooManyConstraintGroups,
#[error("improper constraint: {0:?}")]
ImproperConstraint(String),
#[error("constraint parser error")]
ConstraintParser,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Version {
pub major: u64,
pub minor: u64,
pub patch: u64,
pub pre: String,
pub metadata: String,
}
fn is_ident(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || byte == b'-'
}
fn run(bytes: &[u8], from: usize, pred: impl Fn(u8) -> bool) -> usize {
from + bytes[from..].iter().take_while(|b| pred(**b)).count()
}
fn at(bytes: &[u8], index: usize, pred: impl Fn(u8) -> bool) -> bool {
bytes.get(index).is_some_and(|b| pred(*b))
}
fn dotted(bytes: &[u8], from: usize, prefix: u8) -> Option<(&[u8], usize)> {
if !(bytes.get(from) == Some(&prefix) && at(bytes, from + 1, is_ident)) {
return None;
}
let mut end = run(bytes, from + 1, is_ident);
while bytes.get(end) == Some(&b'.') && at(bytes, end + 1, is_ident) {
end = run(bytes, end + 1, is_ident);
}
Some((&bytes[from + 1..end], end))
}
fn number(digits: &[u8]) -> Result<u64, Error> {
std::str::from_utf8(digits)
.ok()
.and_then(|d| d.parse().ok())
.ok_or(Error::SegmentTooLarge)
}
impl Version {
pub fn parse(text: &str) -> Result<Self, Error> {
if text.len() > MAX_VERSION_LEN {
return Err(Error::VersionTooLong);
}
let bytes = text.as_bytes();
let start = usize::from(bytes.first() == Some(&b'v'));
let digit = |b: u8| b.is_ascii_digit();
let mut numbers = [0u64; 3];
let mut end = run(bytes, start, digit);
if end == start {
return Err(Error::InvalidVersion);
}
numbers[0] = number(&bytes[start..end])?;
for slot in &mut numbers[1..] {
if bytes.get(end) == Some(&b'.') && at(bytes, end + 1, digit) {
let next = run(bytes, end + 1, digit);
*slot = number(&bytes[end + 1..next])?;
end = next;
}
}
let pre = dotted(bytes, end, b'-');
end = pre.map_or(end, |(_, next)| next);
let metadata = dotted(bytes, end, b'+');
end = metadata.map_or(end, |(_, next)| next);
if end != bytes.len() {
return Err(Error::InvalidVersion);
}
let pre = pre.map_or(&[][..], |(ident, _)| ident);
for segment in pre.split(|b| *b == b'.').filter(|s| !s.is_empty()) {
if segment.len() > 1 && segment[0] == b'0' && segment.iter().all(u8::is_ascii_digit) {
return Err(Error::SegmentStartsZero);
}
}
Ok(Self {
major: numbers[0],
minor: numbers[1],
patch: numbers[2],
pre: String::from_utf8_lossy(pre).into_owned(),
metadata: metadata
.map(|(ident, _)| String::from_utf8_lossy(ident).into_owned())
.unwrap_or_default(),
})
}
#[must_use]
pub fn compare(&self, other: &Self) -> Ordering {
let core =
(self.major, self.minor, self.patch).cmp(&(other.major, other.minor, other.patch));
core.then_with(|| match (self.pre.is_empty(), other.pre.is_empty()) {
(true, true) => Ordering::Equal,
(true, false) => Ordering::Greater,
(false, true) => Ordering::Less,
(false, false) => compare_prerelease(&self.pre, &other.pre),
})
}
}
impl fmt::Display for Version {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}.{}.{}", self.major, self.minor, self.patch)?;
if !self.pre.is_empty() {
write!(f, "-{}", self.pre)?;
}
if !self.metadata.is_empty() {
write!(f, "+{}", self.metadata)?;
}
Ok(())
}
}
fn compare_prerelease(a: &str, b: &str) -> Ordering {
let mut left = a.split('.');
let mut right = b.split('.');
loop {
let order = match (left.next(), right.next()) {
(None, None) => return Ordering::Equal,
(l, r) => compare_segment(l.unwrap_or(""), r.unwrap_or("")),
};
if order != Ordering::Equal {
return order;
}
}
}
fn compare_segment(a: &str, b: &str) -> Ordering {
match (a, b) {
_ if a == b => Ordering::Equal,
("", _) => Ordering::Less,
(_, "") => Ordering::Greater,
_ => match (a.parse::<u64>(), b.parse::<u64>()) {
(Ok(x), Ok(y)) => x.cmp(&y),
(Err(_), Err(_)) => a.cmp(b),
(Ok(_), Err(_)) => Ordering::Less,
(Err(_), Ok(_)) => Ordering::Greater,
},
}
}
mod constraints;
pub use constraints::Constraints;