1use std::cmp::Ordering;
2use std::fmt;
3use std::hash::{Hash, Hasher};
4use std::str::FromStr;
5
6use crate::identifier::Identifiers;
7use crate::{Error, MAX_LENGTH, MAX_SAFE_INTEGER};
8
9#[derive(Clone)]
20pub struct Version {
21 pub major: u64,
23 pub minor: u64,
25 pub patch: u64,
27 meta: Option<Box<Meta>>,
28}
29
30#[derive(Clone, Default)]
31struct Meta {
32 pre: Identifiers,
33 build: Identifiers,
34 context: Option<Box<str>>,
35}
36
37static EMPTY: Identifiers = Identifiers::empty();
38
39impl fmt::Debug for Version {
40 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41 f.debug_struct("Version")
42 .field("major", &self.major)
43 .field("minor", &self.minor)
44 .field("patch", &self.patch)
45 .field("pre", self.pre())
46 .field("build", self.build())
47 .field("context", &self.context())
48 .finish()
49 }
50}
51
52pub fn split_reference(input: &str) -> (Option<&str>, std::borrow::Cow<'_, str>) {
57 if !input.as_bytes().contains(&b'@') {
58 return (None, std::borrow::Cow::Borrowed(input));
59 }
60 let first_space = input.find(|c: char| c.is_whitespace());
61 let (head, tail) = match first_space {
62 Some(i) => (&input[..i], &input[i..]),
63 None => (input, ""),
64 };
65 match head.rfind('@') {
66 Some(at) if at > 0 => {
67 let rest = &head[at + 1..];
68 let rest = if tail.is_empty() {
69 std::borrow::Cow::Borrowed(rest)
70 } else {
71 std::borrow::Cow::Owned(format!("{rest}{tail}"))
72 };
73 (Some(&head[..at]), rest)
74 }
75 _ => (None, std::borrow::Cow::Borrowed(input)),
76 }
77}
78
79impl Version {
80 pub fn new(major: u64, minor: u64, patch: u64) -> Self {
82 Version {
83 major,
84 minor,
85 patch,
86 meta: None,
87 }
88 }
89
90 pub(crate) fn from_parts(
91 major: u64,
92 minor: u64,
93 patch: u64,
94 pre: Identifiers,
95 build: Identifiers,
96 ) -> Self {
97 let meta = if pre.is_empty() && build.is_empty() {
98 None
99 } else {
100 Some(Box::new(Meta {
101 pre,
102 build,
103 context: None,
104 }))
105 };
106 Version {
107 major,
108 minor,
109 patch,
110 meta,
111 }
112 }
113
114 #[inline]
116 pub fn pre(&self) -> &Identifiers {
117 self.meta.as_ref().map_or(&EMPTY, |m| &m.pre)
118 }
119
120 #[inline]
122 pub fn build(&self) -> &Identifiers {
123 self.meta.as_ref().map_or(&EMPTY, |m| &m.build)
124 }
125
126 #[inline]
128 pub fn context(&self) -> Option<&str> {
129 self.meta.as_ref().and_then(|m| m.context.as_deref())
130 }
131
132 fn meta_mut(&mut self) -> &mut Meta {
133 self.meta.get_or_insert_with(Default::default)
134 }
135
136 pub fn with_pre(mut self, pre: Identifiers) -> Self {
138 if !(pre.is_empty() && self.meta.is_none()) {
139 self.meta_mut().pre = pre;
140 }
141 self
142 }
143
144 pub fn with_build(mut self, build: Identifiers) -> Self {
146 if !(build.is_empty() && self.meta.is_none()) {
147 self.meta_mut().build = build;
148 }
149 self
150 }
151
152 pub fn with_context(mut self, context: Option<&str>) -> Self {
154 if !(context.is_none() && self.meta.is_none()) {
155 self.meta_mut().context = context.map(Into::into);
156 }
157 self
158 }
159
160 pub fn parse(input: &str) -> Result<Self, Error> {
163 if input.len() > MAX_LENGTH {
164 return Err(Error::TooLong);
165 }
166 if let Ok(v) = parse_core(input, input) {
170 return Ok(v);
171 }
172 let (context, rest) = split_reference(input);
173 Ok(parse_core(rest.trim(), input)?.with_context(context))
174 }
175
176 pub fn is_prerelease(&self) -> bool {
178 !self.pre().is_empty()
179 }
180
181 pub fn without_build(&self) -> Version {
183 self.clone().with_build(Identifiers::empty())
184 }
185
186 pub fn reference(&self) -> String {
188 match self.context() {
189 Some(c) => format!("{c}@{self}"),
190 None => self.to_string(),
191 }
192 }
193
194 #[inline]
195 pub(crate) fn same_tuple(&self, other: &Version) -> bool {
196 self.major == other.major && self.minor == other.minor && self.patch == other.patch
197 }
198
199 #[inline]
202 pub(crate) fn cmp_ignoring_build(&self, other: &Version) -> Ordering {
203 match self.cmp_tuple(other) {
204 Ordering::Equal => cmp_pre(self.pre(), other.pre()),
205 o => o,
206 }
207 }
208
209 #[inline]
210 fn cmp_tuple(&self, other: &Version) -> Ordering {
211 self.major
212 .cmp(&other.major)
213 .then(self.minor.cmp(&other.minor))
214 .then(self.patch.cmp(&other.patch))
215 }
216}
217
218#[inline]
219fn cmp_pre(a: &Identifiers, b: &Identifiers) -> Ordering {
220 match (a.is_empty(), b.is_empty()) {
221 (true, true) => Ordering::Equal,
222 (false, true) => Ordering::Less, (true, false) => Ordering::Greater,
224 (false, false) => a.cmp_ids(b),
225 }
226}
227
228#[inline]
229fn cmp_build(a: &Identifiers, b: &Identifiers) -> Ordering {
230 match (a.is_empty(), b.is_empty()) {
231 (true, true) => Ordering::Equal,
232 (false, true) => Ordering::Greater, (true, false) => Ordering::Less,
234 (false, false) => a.cmp_ids(b),
235 }
236}
237
238impl Ord for Version {
239 #[inline]
240 fn cmp(&self, other: &Self) -> Ordering {
241 match self.cmp_tuple(other) {
242 Ordering::Equal => {}
243 o => return o,
244 }
245 if self.meta.is_none() && other.meta.is_none() {
247 return Ordering::Equal;
248 }
249 cmp_pre(self.pre(), other.pre()).then_with(|| cmp_build(self.build(), other.build()))
250 }
251}
252
253impl PartialOrd for Version {
254 #[inline]
255 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
256 Some(self.cmp(other))
257 }
258}
259
260impl PartialEq for Version {
261 #[inline]
262 fn eq(&self, other: &Self) -> bool {
263 self.cmp(other) == Ordering::Equal
264 }
265}
266
267impl Eq for Version {}
268
269impl Hash for Version {
270 fn hash<H: Hasher>(&self, state: &mut H) {
271 self.major.hash(state);
272 self.minor.hash(state);
273 self.patch.hash(state);
274 self.pre().hash(state);
275 for id in self.build().iter() {
276 match id {
277 crate::Identifier::Numeric(n) => n.trim_start_matches('0').hash(state),
278 crate::Identifier::AlphaNumeric(a) => a.hash(state),
279 }
280 }
281 }
282}
283
284impl fmt::Display for Version {
285 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
286 write!(f, "{}.{}.{}", self.major, self.minor, self.patch)?;
287 if let Some(m) = &self.meta {
288 if !m.pre.is_empty() {
289 write!(f, "-{}", m.pre)?;
290 }
291 if !m.build.is_empty() {
292 write!(f, "+{}", m.build)?;
293 }
294 }
295 Ok(())
296 }
297}
298
299impl FromStr for Version {
300 type Err = Error;
301 fn from_str(s: &str) -> Result<Self, Self::Err> {
302 Version::parse(s)
303 }
304}
305
306pub(crate) struct Cursor<'a> {
309 pub s: &'a [u8],
310 pub i: usize,
311}
312
313impl<'a> Cursor<'a> {
314 pub fn new(s: &'a str) -> Self {
315 Cursor {
316 s: s.as_bytes(),
317 i: 0,
318 }
319 }
320 #[inline]
321 pub fn peek(&self) -> Option<u8> {
322 self.s.get(self.i).copied()
323 }
324 #[inline]
325 pub fn eat(&mut self, c: u8) -> bool {
326 if self.peek() == Some(c) {
327 self.i += 1;
328 true
329 } else {
330 false
331 }
332 }
333 #[inline]
334 pub fn done(&self) -> bool {
335 self.i >= self.s.len()
336 }
337}
338
339const CLASS: [u8; 256] = {
342 let mut t = [0u8; 256];
343 let mut c = 0;
344 while c < 256 {
345 let b = c as u8;
346 t[c] = if b.is_ascii_digit() {
347 2
348 } else if b.is_ascii_alphabetic() || b == b'-' {
349 1
350 } else {
351 0
352 };
353 c += 1;
354 }
355 t
356};
357
358#[cold]
359#[inline(never)]
360pub(crate) fn invalid(input: &str) -> Error {
361 Error::InvalidVersion(input.to_string())
362}
363
364#[cold]
365#[inline(never)]
366fn too_large(input: &str) -> Error {
367 Error::TooLarge(input.to_string())
368}
369
370#[inline(always)]
372pub(crate) fn numeric(cur: &mut Cursor<'_>, input: &str) -> Result<u64, Error> {
373 let s = cur.s;
374 let start = cur.i;
375 let mut i = start;
376 let mut n: u64 = 0;
377 while i < s.len() {
378 let d = s[i].wrapping_sub(b'0');
379 if d > 9 {
380 break;
381 }
382 if i - start < 20 {
384 n = n.wrapping_mul(10).wrapping_add(u64::from(d));
385 }
386 i += 1;
387 }
388 let len = i - start;
389 if len == 0 || (len > 1 && s[start] == b'0') {
390 return Err(invalid(input));
391 }
392 if len > 16 || n > MAX_SAFE_INTEGER {
393 return Err(too_large(input));
394 }
395 cur.i = i;
396 Ok(n)
397}
398
399fn identifiers(cur: &mut Cursor<'_>, input: &str, pre: bool) -> Result<Identifiers, Error> {
402 let s = cur.s;
403 let start = cur.i;
404 let mut i = start;
405 loop {
406 let id_start = i;
407 let mut digits = true;
408 while i < s.len() {
409 let class = CLASS[s[i] as usize];
410 if class == 0 {
411 break;
412 }
413 digits &= class == 2;
414 i += 1;
415 }
416 let len = i - id_start;
417 if len == 0 {
418 return Err(invalid(input));
419 }
420 if pre && digits {
421 if len > 1 && s[id_start] == b'0' {
422 return Err(invalid(input));
423 }
424 if len >= 16 {
426 let n = s[id_start..i].iter().fold(0u64, |n, &c| {
427 n.saturating_mul(10).saturating_add(u64::from(c - b'0'))
428 });
429 if n >= MAX_SAFE_INTEGER {
430 return Err(too_large(input));
431 }
432 }
433 }
434 if i < s.len() && s[i] == b'.' {
435 i += 1;
436 continue;
437 }
438 break;
439 }
440 cur.i = i;
441 Ok(Identifiers::from_ascii(&s[start..i]))
443}
444
445pub(crate) fn pre_release(cur: &mut Cursor<'_>, input: &str) -> Result<Identifiers, Error> {
446 identifiers(cur, input, true)
447}
448
449pub(crate) fn build(cur: &mut Cursor<'_>, input: &str) -> Result<Identifiers, Error> {
450 identifiers(cur, input, false)
451}
452
453fn parse_core(s: &str, input: &str) -> Result<Version, Error> {
454 let bad = || invalid(input);
455 let mut cur = Cursor::new(s);
456 let major = numeric(&mut cur, input)?;
457 if !cur.eat(b'.') {
458 return Err(bad());
459 }
460 let minor = numeric(&mut cur, input)?;
461 if !cur.eat(b'.') {
462 return Err(bad());
463 }
464 let patch = numeric(&mut cur, input)?;
465 let pre = if cur.eat(b'-') {
466 pre_release(&mut cur, input)?
467 } else {
468 Identifiers::empty()
469 };
470 let build = if cur.eat(b'+') {
471 build(&mut cur, input)?
472 } else {
473 Identifiers::empty()
474 };
475 if !cur.done() {
476 return Err(bad());
477 }
478 Ok(Version::from_parts(major, minor, patch, pre, build))
479}