vc-types 0.1.0

Domain types for Visual Compiler
Documentation
//! Compiler version type.

use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;

/// Semantic version of the compiler.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct CompilerVersion {
    pub major: u16,
    pub minor: u16,
    pub patch: u16,
}

impl CompilerVersion {
    pub const fn new(major: u16, minor: u16, patch: u16) -> Self {
        Self { major, minor, patch }
    }

    pub fn parse(s: &str) -> Result<Self, String> {
        let mut parts = s.split('.');
        let major = parts
            .next()
            .ok_or_else(|| "missing major version".to_string())?
            .parse()
            .map_err(|_| "invalid major version")?;
        let minor = parts
            .next()
            .ok_or_else(|| "missing minor version".to_string())?
            .parse()
            .map_err(|_| "invalid minor version")?;
        let patch = parts
            .next()
            .ok_or_else(|| "missing patch version".to_string())?
            .parse()
            .map_err(|_| "invalid patch version")?;
        if parts.next().is_some() {
            return Err("extra version parts".to_string());
        }
        Ok(Self { major, minor, patch })
    }
}

impl fmt::Display for CompilerVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
    }
}

impl FromStr for CompilerVersion {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s)
    }
}

impl Default for CompilerVersion {
    fn default() -> Self {
        Self::new(0, 0, 0)
    }
}