Skip to main content

lux_lib/package/version/
spec_rev.rs

1use std::fmt::Display;
2
3use miette::Diagnostic;
4use thiserror::Error;
5
6/// The revision of a rov
7#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
8pub struct SpecRev(u16);
9
10impl From<u16> for SpecRev {
11    fn from(value: u16) -> Self {
12        Self(value)
13    }
14}
15
16impl Display for SpecRev {
17    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18        self.0.fmt(f)
19    }
20}
21
22impl Default for SpecRev {
23    fn default() -> Self {
24        Self(1)
25    }
26}
27
28/// Iterates `SpecRev`s upwards, starting from `1`.
29pub(crate) struct SpecRevIterator {
30    current: u16,
31}
32
33impl SpecRevIterator {
34    pub fn new() -> Self {
35        SpecRevIterator {
36            current: SpecRev::default().0,
37        }
38    }
39}
40
41impl Iterator for SpecRevIterator {
42    type Item = SpecRev;
43
44    fn next(&mut self) -> Option<Self::Item> {
45        let current = self.current;
46        self.current += 1;
47        if self.current == 0 {
48            None // overflow
49        } else {
50            Some(SpecRev(current))
51        }
52    }
53}
54
55#[derive(Error, Debug, Diagnostic)]
56#[non_exhaustive]
57pub enum SpecRevParseError {
58    #[error("specrev {specrev} in version {full_version} contains non-numeric characters")]
59    InvalidSpecrev {
60        specrev: String,
61        full_version: String,
62    },
63    #[error("could not parse specrev in version {0}")]
64    InvalidVersion(String),
65}
66
67pub(super) fn split_specrev(version_str: &str) -> Result<(&str, SpecRev), SpecRevParseError> {
68    if let Some(pos) = version_str.rfind('-') {
69        if let Some(specrev_str) = version_str.get(pos + 1..) {
70            if specrev_str.chars().all(|c| c.is_ascii_digit()) {
71                let specrev =
72                    specrev_str
73                        .parse::<u16>()
74                        .map_err(|_| SpecRevParseError::InvalidSpecrev {
75                            specrev: specrev_str.into(),
76                            full_version: version_str.into(),
77                        })?;
78                Ok((&version_str[..pos], specrev.into()))
79            } else {
80                // A non-numeric suffix is a semver prerelease, not a specrev.
81                Ok((version_str, 1.into()))
82            }
83        } else {
84            Err(SpecRevParseError::InvalidVersion(version_str.into()))
85        }
86    } else {
87        // We assume a specrev of 1 if none can be found.
88        Ok((version_str, 1.into()))
89    }
90}