1use std::cmp::Ordering;
13use std::fmt;
14
15#[cfg(test)]
16mod tests;
17
18const MAX_VERSION_LEN: usize = 256;
20const MAX_CONSTRAINT_LEN: usize = 512;
22const MAX_CONSTRAINT_GROUPS: usize = 32;
24
25#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
27#[non_exhaustive]
28pub enum Error {
29 #[error("version string is too long (max {MAX_VERSION_LEN} bytes)")]
31 VersionTooLong,
32
33 #[error("invalid semantic version")]
35 InvalidVersion,
36
37 #[error("version segment starts with 0")]
39 SegmentStartsZero,
40
41 #[error("error parsing version segment: number too large")]
43 SegmentTooLarge,
44
45 #[error("constraint string is too long (max {MAX_CONSTRAINT_LEN} bytes)")]
47 ConstraintTooLong,
48
49 #[error("too many constraint groups (max {MAX_CONSTRAINT_GROUPS})")]
51 TooManyConstraintGroups,
52
53 #[error("improper constraint: {0:?}")]
55 ImproperConstraint(String),
56
57 #[error("constraint parser error")]
59 ConstraintParser,
60}
61
62#[derive(Debug, Clone, PartialEq, Eq, Default)]
65pub struct Version {
66 pub major: u64,
68 pub minor: u64,
70 pub patch: u64,
72 pub pre: String,
74 pub metadata: String,
76}
77
78fn is_ident(byte: u8) -> bool {
80 byte.is_ascii_alphanumeric() || byte == b'-'
81}
82
83fn run(bytes: &[u8], from: usize, pred: impl Fn(u8) -> bool) -> usize {
85 from + bytes[from..].iter().take_while(|b| pred(**b)).count()
86}
87
88fn at(bytes: &[u8], index: usize, pred: impl Fn(u8) -> bool) -> bool {
90 bytes.get(index).is_some_and(|b| pred(*b))
91}
92
93fn dotted(bytes: &[u8], from: usize, prefix: u8) -> Option<(&[u8], usize)> {
96 if !(bytes.get(from) == Some(&prefix) && at(bytes, from + 1, is_ident)) {
97 return None;
98 }
99
100 let mut end = run(bytes, from + 1, is_ident);
101
102 while bytes.get(end) == Some(&b'.') && at(bytes, end + 1, is_ident) {
103 end = run(bytes, end + 1, is_ident);
104 }
105
106 Some((&bytes[from + 1..end], end))
107}
108
109fn number(digits: &[u8]) -> Result<u64, Error> {
111 std::str::from_utf8(digits)
112 .ok()
113 .and_then(|d| d.parse().ok())
114 .ok_or(Error::SegmentTooLarge)
115}
116
117impl Version {
118 pub fn parse(text: &str) -> Result<Self, Error> {
121 if text.len() > MAX_VERSION_LEN {
122 return Err(Error::VersionTooLong);
123 }
124
125 let bytes = text.as_bytes();
126 let start = usize::from(bytes.first() == Some(&b'v'));
127 let digit = |b: u8| b.is_ascii_digit();
128 let mut numbers = [0u64; 3];
129 let mut end = run(bytes, start, digit);
130
131 if end == start {
132 return Err(Error::InvalidVersion);
133 }
134
135 numbers[0] = number(&bytes[start..end])?;
136
137 for slot in &mut numbers[1..] {
138 if bytes.get(end) == Some(&b'.') && at(bytes, end + 1, digit) {
139 let next = run(bytes, end + 1, digit);
140
141 *slot = number(&bytes[end + 1..next])?;
142 end = next;
143 }
144 }
145
146 let pre = dotted(bytes, end, b'-');
147
148 end = pre.map_or(end, |(_, next)| next);
149
150 let metadata = dotted(bytes, end, b'+');
151
152 end = metadata.map_or(end, |(_, next)| next);
153
154 if end != bytes.len() {
155 return Err(Error::InvalidVersion);
156 }
157
158 let pre = pre.map_or(&[][..], |(ident, _)| ident);
159
160 for segment in pre.split(|b| *b == b'.').filter(|s| !s.is_empty()) {
161 if segment.len() > 1 && segment[0] == b'0' && segment.iter().all(u8::is_ascii_digit) {
162 return Err(Error::SegmentStartsZero);
163 }
164 }
165
166 Ok(Self {
167 major: numbers[0],
168 minor: numbers[1],
169 patch: numbers[2],
170 pre: String::from_utf8_lossy(pre).into_owned(),
171 metadata: metadata
172 .map(|(ident, _)| String::from_utf8_lossy(ident).into_owned())
173 .unwrap_or_default(),
174 })
175 }
176
177 #[must_use]
179 pub fn compare(&self, other: &Self) -> Ordering {
180 let core =
181 (self.major, self.minor, self.patch).cmp(&(other.major, other.minor, other.patch));
182
183 core.then_with(|| match (self.pre.is_empty(), other.pre.is_empty()) {
184 (true, true) => Ordering::Equal,
185 (true, false) => Ordering::Greater,
186 (false, true) => Ordering::Less,
187 (false, false) => compare_prerelease(&self.pre, &other.pre),
188 })
189 }
190}
191
192impl fmt::Display for Version {
193 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194 write!(f, "{}.{}.{}", self.major, self.minor, self.patch)?;
195
196 if !self.pre.is_empty() {
197 write!(f, "-{}", self.pre)?;
198 }
199
200 if !self.metadata.is_empty() {
201 write!(f, "+{}", self.metadata)?;
202 }
203
204 Ok(())
205 }
206}
207
208fn compare_prerelease(a: &str, b: &str) -> Ordering {
211 let mut left = a.split('.');
212 let mut right = b.split('.');
213
214 loop {
215 let order = match (left.next(), right.next()) {
216 (None, None) => return Ordering::Equal,
217 (l, r) => compare_segment(l.unwrap_or(""), r.unwrap_or("")),
218 };
219
220 if order != Ordering::Equal {
221 return order;
222 }
223 }
224}
225
226fn compare_segment(a: &str, b: &str) -> Ordering {
229 match (a, b) {
230 _ if a == b => Ordering::Equal,
231 ("", _) => Ordering::Less,
232 (_, "") => Ordering::Greater,
233 _ => match (a.parse::<u64>(), b.parse::<u64>()) {
234 (Ok(x), Ok(y)) => x.cmp(&y),
235 (Err(_), Err(_)) => a.cmp(b),
236 (Ok(_), Err(_)) => Ordering::Less,
237 (Err(_), Ok(_)) => Ordering::Greater,
238 },
239 }
240}
241
242mod constraints;
243
244pub use constraints::Constraints;