use std::cmp::Ordering;
use super::{Error, MAX_CONSTRAINT_GROUPS, MAX_CONSTRAINT_LEN, Version, is_ident, run};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Constraints {
groups: Vec<Group>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Group {
terms: Vec<Term>,
contains_pre: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Term {
op: Op,
version: Version,
minor_dirty: bool,
patch_dirty: bool,
dirty: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Op {
TildeOrEqual,
NotEqual,
Greater,
Less,
GreaterEqual,
LessEqual,
Tilde,
Caret,
}
struct Operand<'a> {
whole: &'a str,
major: &'a str,
minor: &'a str,
patch: &'a str,
pre: &'a str,
}
fn is_num(byte: u8) -> bool {
byte.is_ascii_digit() || matches!(byte, b'|' | b'x' | b'X' | b'*')
}
fn is_x(text: &str) -> bool {
matches!(text, "x" | "X" | "*")
}
fn operand(text: &str, from: usize) -> Option<(Operand<'_>, usize)> {
let bytes = text.as_bytes();
let start = from + usize::from(bytes.get(from) == Some(&b'v'));
let major_end = run(bytes, start, is_num);
let mut end = major_end;
let mut parts = [""; 2];
if major_end == start {
return None;
}
for part in &mut parts {
if bytes.get(end) == Some(&b'.') && bytes.get(end + 1).is_some_and(|b| is_num(*b)) {
let next = run(bytes, end + 1, is_num);
*part = &text[end + 1..next];
end = next;
}
}
let pre_start = end;
if bytes.get(end) == Some(&b'-') && bytes.get(end + 1).is_some_and(|b| is_ident(*b)) {
end = run(bytes, end + 1, is_ident);
while bytes.get(end) == Some(&b'.') && bytes.get(end + 1).is_some_and(|b| is_ident(*b)) {
end = run(bytes, end + 1, is_ident);
}
}
let pre = &text[pre_start..end];
if bytes.get(end) == Some(&b'+') && bytes.get(end + 1).is_some_and(|b| is_ident(*b)) {
end = run(bytes, end + 1, is_ident);
while bytes.get(end) == Some(&b'.') && bytes.get(end + 1).is_some_and(|b| is_ident(*b)) {
end = run(bytes, end + 1, is_ident);
}
}
let operand = Operand {
whole: &text[from..end],
major: &text[start..major_end],
minor: parts[0],
patch: parts[1],
pre,
};
Some((operand, end))
}
fn skip_space(bytes: &[u8], from: usize) -> usize {
run(bytes, from, |b| {
matches!(b, b' ' | b'\t' | b'\n' | 0x0c | b'\r')
})
}
pub(super) fn rewrite_range(text: &str) -> String {
let bytes = text.as_bytes();
let mut rewritten = text.to_owned();
let mut index = 0;
while index < bytes.len() {
let Some((matched, low, high)) = range_at(text, index) else {
index += 1;
continue;
};
rewritten = rewritten.replacen(&text[index..matched], &format!(">= {low}, <= {high} "), 1);
index = matched;
}
rewritten
}
fn range_at(text: &str, from: usize) -> Option<(usize, &str, &str)> {
let bytes = text.as_bytes();
let (low, end) = operand(text, skip_space(bytes, from))?;
let after_low = skip_space(bytes, end);
if after_low == end || bytes.get(after_low) != Some(&b'-') {
return None;
}
let start_high = skip_space(bytes, after_low + 1);
if start_high == after_low + 1 {
return None;
}
let (high, end) = operand(text, start_high)?;
Some((skip_space(bytes, end), low.whole, high.whole))
}
fn operator(bytes: &[u8], from: usize) -> Option<(Op, usize)> {
let end = run(bytes, from, |b| {
matches!(b, b'=' | b'!' | b'<' | b'>' | b'~' | b'^')
});
let op = match &bytes[from..end] {
b"" | b"=" => Op::TildeOrEqual,
b"!=" => Op::NotEqual,
b">" => Op::Greater,
b"<" => Op::Less,
b">=" | b"=>" => Op::GreaterEqual,
b"<=" | b"=<" => Op::LessEqual,
b"~" | b"~>" => Op::Tilde,
b"^" => Op::Caret,
_ => return None,
};
Some((op, end))
}
impl Term {
fn new(op: Op, operand: &Operand<'_>) -> Result<Self, Error> {
let pre = operand.pre;
let mut term = Self {
op,
version: Version::default(),
minor_dirty: false,
patch_dirty: false,
dirty: false,
};
let text = if is_x(operand.major) {
term.dirty = true;
format!("0.0.0{pre}")
} else if operand.minor.is_empty() || is_x(operand.minor) {
term.minor_dirty = true;
term.dirty = true;
format!("{}.0.0{pre}", operand.major)
} else if operand.patch.is_empty() || is_x(operand.patch) {
term.patch_dirty = true;
term.dirty = true;
format!("{}.{}.0{pre}", operand.major, operand.minor)
} else {
operand.whole.to_owned()
};
term.version = Version::parse(&text).map_err(|_| Error::ConstraintParser)?;
Ok(term)
}
fn check(&self, v: &Version, include_pre: bool) -> bool {
let c = &self.version;
if !v.pre.is_empty() && !include_pre {
return false;
}
match self.op {
Op::NotEqual => self.not_equal(v),
Op::Greater => self.greater(v),
Op::Less => v.compare(c) == Ordering::Less,
Op::GreaterEqual => v.compare(c) != Ordering::Less,
Op::LessEqual => self.less_equal(v),
Op::Tilde => self.tilde(v),
Op::TildeOrEqual if self.dirty => self.tilde(v),
Op::TildeOrEqual => v.compare(c) == Ordering::Equal,
Op::Caret => self.caret(v),
}
}
fn not_equal(&self, v: &Version) -> bool {
let c = &self.version;
if self.dirty {
if c.major != v.major {
return true;
}
if c.minor != v.minor && !self.minor_dirty {
return true;
} else if self.minor_dirty {
return false;
} else if c.patch != v.patch && !self.patch_dirty {
return true;
} else if self.patch_dirty {
if !v.pre.is_empty() || !c.pre.is_empty() {
return super::compare_prerelease(&v.pre, &c.pre) != Ordering::Equal;
}
return false;
}
}
v.compare(c) != Ordering::Equal
}
fn greater(&self, v: &Version) -> bool {
let c = &self.version;
if !self.dirty {
return v.compare(c) == Ordering::Greater;
}
if v.major != c.major {
return v.major > c.major;
}
if self.minor_dirty {
return false;
}
if self.patch_dirty {
return v.minor > c.minor;
}
v.compare(c) == Ordering::Greater
}
fn less_equal(&self, v: &Version) -> bool {
let c = &self.version;
if !self.dirty {
return v.compare(c) != Ordering::Greater;
}
if v.major > c.major {
return false;
}
!(v.major == c.major && v.minor > c.minor && !self.minor_dirty)
}
fn tilde(&self, v: &Version) -> bool {
let c = &self.version;
if v.compare(c) == Ordering::Less {
return false;
}
if c.major == 0 && c.minor == 0 && c.patch == 0 && !self.minor_dirty && !self.patch_dirty {
return true;
}
if v.major != c.major {
return false;
}
v.minor == c.minor || self.minor_dirty
}
fn caret(&self, v: &Version) -> bool {
let c = &self.version;
if v.compare(c) == Ordering::Less {
return false;
}
if c.major > 0 || self.minor_dirty {
return v.major == c.major;
}
if v.major > 0 {
return false;
}
if c.minor > 0 || self.patch_dirty {
return v.minor == c.minor;
}
if v.minor > 0 {
return false;
}
c.patch == v.patch
}
}
fn parse_group(text: &str) -> Result<Group, Error> {
let improper = || Error::ImproperConstraint(text.to_owned());
let bytes = text.as_bytes();
let mut terms = Vec::new();
let mut index = skip_space(bytes, 0);
loop {
let (op, after_op) = operator(bytes, index).ok_or_else(improper)?;
let (operand, end) = operand(text, skip_space(bytes, after_op)).ok_or_else(improper)?;
let spaced = skip_space(bytes, end);
terms.push(Term::new(op, &operand)?);
if spaced == bytes.len() {
break;
}
index = if bytes[spaced] == b',' {
skip_space(bytes, spaced + 1)
} else if spaced > end {
spaced
} else {
return Err(improper());
};
if index == bytes.len() {
return Err(improper());
}
}
let contains_pre = terms.iter().any(|t| !t.version.pre.is_empty());
Ok(Group {
terms,
contains_pre,
})
}
impl Constraints {
pub fn parse(text: &str) -> Result<Self, Error> {
if text.len() > MAX_CONSTRAINT_LEN {
return Err(Error::ConstraintTooLong);
}
let rewritten = rewrite_range(text);
let groups: Vec<&str> = rewritten.split("||").collect();
if groups.len() > MAX_CONSTRAINT_GROUPS {
return Err(Error::TooManyConstraintGroups);
}
Ok(Self {
groups: groups
.into_iter()
.map(parse_group)
.collect::<Result<_, _>>()?,
})
}
#[must_use]
pub fn matches(&self, version: &Version) -> bool {
self.groups
.iter()
.any(|g| g.terms.iter().all(|t| t.check(version, g.contains_pre)))
}
}
#[cfg(test)]
impl Constraints {
pub(super) fn shape(&self) -> (usize, usize) {
(self.groups.len(), self.groups[0].terms.len())
}
}