Skip to main content

argenv/
version.rs

1//! Version — a parsed, ordered project version. Never a bare string.
2use std::fmt;
3
4/// A project version (`major[.minor[.patch]]`).
5///
6/// Constructed only via [`Version::parse`], so a malformed literal is a **compile
7/// error** when used in a `const`. Ordered, which makes `since <= THIS_VERSION`
8/// a checkable invariant rather than a comment.
9///
10/// ```
11/// # use argenv::Version;
12/// const V: Version = Version::parse("2.1");
13/// assert_eq!(V.to_string(), "2.1.0");
14/// assert!(Version::parse("2.1") < Version::parse("2.2"));
15/// ```
16#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
17pub struct Version {
18    /// Major component.
19    pub major: u16,
20    /// Minor component (0 when omitted).
21    pub minor: u16,
22    /// Patch component (0 when omitted).
23    pub patch: u16,
24}
25
26impl Version {
27    /// Parse `major[.minor[.patch]]` in a `const` context.
28    ///
29    /// A semantic-version pre-release or build suffix (`0.2.0-rc1`, `1.0.0+d34d`)
30    /// is accepted and ignored: only the numeric core is retained, so ordering
31    /// compares releases rather than release-candidate labels. This matters
32    /// because [`THIS_VERSION`] parses the crate's own version, and a project
33    /// that tags a pre-release must still compile.
34    ///
35    /// # Panics
36    /// At **compile time** (in a `const`) for a non-numeric character in the
37    /// numeric core, more than three components, or an empty string.
38    pub const fn parse(s: &str) -> Version {
39        let b = s.as_bytes();
40        if b.is_empty() {
41            panic!("version string is empty");
42        }
43        let mut n = [0u16; 3];
44        let mut idx = 0usize;
45        let mut i = 0usize;
46        while i < b.len() {
47            let c = b[i];
48            if c == b'-' || c == b'+' {
49                break; // pre-release or build metadata: not part of the ordering
50            } else if c == b'.' {
51                idx += 1;
52                if idx > 2 {
53                    panic!("version has more than three components");
54                }
55            } else if c >= b'0' && c <= b'9' {
56                n[idx] = n[idx] * 10 + (c - b'0') as u16;
57            } else {
58                panic!("invalid character in version string");
59            }
60            i += 1;
61        }
62        Version {
63            major: n[0],
64            minor: n[1],
65            patch: n[2],
66        }
67    }
68
69    /// Fallible runtime parse (for data read from JSON rather than authored).
70    ///
71    /// Accepts and ignores a pre-release or build suffix, as [`Version::parse`] does.
72    pub fn try_parse(s: &str) -> Option<Version> {
73        let mut n = [0u16; 3];
74        let mut idx = 0usize;
75        if s.is_empty() {
76            return None;
77        }
78        let core = s.split(['-', '+']).next().unwrap_or(s);
79        if core.is_empty() {
80            return None;
81        }
82        for c in core.bytes() {
83            if c == b'.' {
84                idx += 1;
85                if idx > 2 {
86                    return None;
87                }
88            } else if c.is_ascii_digit() {
89                n[idx] = n[idx].checked_mul(10)?.checked_add((c - b'0') as u16)?;
90            } else {
91                return None;
92            }
93        }
94        Some(Version {
95            major: n[0],
96            minor: n[1],
97            patch: n[2],
98        })
99    }
100}
101
102impl fmt::Display for Version {
103    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
105    }
106}
107
108/// The version of the crate currently building. Reference it via
109/// [`crate::Since::This`] for a variable added *now*, instead of hardcoding a
110/// number that would silently drift.
111pub const THIS_VERSION: Version = Version::parse(env!("CARGO_PKG_VERSION"));