Skip to main content

vc_types/
compiler_version.rs

1//! Compiler version type.
2
3use serde::{Deserialize, Serialize};
4use std::fmt;
5use std::str::FromStr;
6
7/// Semantic version of the compiler.
8#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
9pub struct CompilerVersion {
10    pub major: u16,
11    pub minor: u16,
12    pub patch: u16,
13}
14
15impl CompilerVersion {
16    pub const fn new(major: u16, minor: u16, patch: u16) -> Self {
17        Self { major, minor, patch }
18    }
19
20    pub fn parse(s: &str) -> Result<Self, String> {
21        let mut parts = s.split('.');
22        let major = parts
23            .next()
24            .ok_or_else(|| "missing major version".to_string())?
25            .parse()
26            .map_err(|_| "invalid major version")?;
27        let minor = parts
28            .next()
29            .ok_or_else(|| "missing minor version".to_string())?
30            .parse()
31            .map_err(|_| "invalid minor version")?;
32        let patch = parts
33            .next()
34            .ok_or_else(|| "missing patch version".to_string())?
35            .parse()
36            .map_err(|_| "invalid patch version")?;
37        if parts.next().is_some() {
38            return Err("extra version parts".to_string());
39        }
40        Ok(Self { major, minor, patch })
41    }
42}
43
44impl fmt::Display for CompilerVersion {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
47    }
48}
49
50impl FromStr for CompilerVersion {
51    type Err = String;
52
53    fn from_str(s: &str) -> Result<Self, Self::Err> {
54        Self::parse(s)
55    }
56}
57
58impl Default for CompilerVersion {
59    fn default() -> Self {
60        Self::new(0, 0, 0)
61    }
62}