Skip to content

Instantly share code, notes, and snippets.

@matthewjberger
Created November 13, 2023 07:39
Show Gist options
  • Save matthewjberger/ac03d84657f84a356f894ff176fe767c to your computer and use it in GitHub Desktop.
Save matthewjberger/ac03d84657f84a356f894ff176fe767c to your computer and use it in GitHub Desktop.
semantic version
use std::convert::TryFrom;
use std::num::ParseIntError;
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
struct SemanticVersion {
major: u32,
minor: u32,
patch: u32,
}
impl SemanticVersion {
pub fn new(major: u32, minor: u32, patch: u32) -> Self {
SemanticVersion { major, minor, patch }
}
}
impl TryFrom<&str> for SemanticVersion {
type Error = String;
fn try_from(value: &str) -> Result<Self, Self::Error> {
let parts: Vec<Result<u32, ParseIntError>> = value.split('.').map(str::parse).collect();
if parts.len() != 3 {
return Err("Incorrect number of version components".to_string());
}
let major = parts[0].clone().map_err(|_| "Invalid major version")?;
let minor = parts[1].clone().map_err(|_| "Invalid minor version")?;
let patch = parts[2].clone().map_err(|_| "Invalid patch version")?;
Ok(SemanticVersion { major, minor, patch })
}
}
impl std::fmt::Display for SemanticVersion {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
}
}
fn main() {
let version = SemanticVersion::new(1, 2, 3);
println!("Version: {}", version);
match SemanticVersion::try_from("2.1.3") {
Ok(v) => println!("Parsed Version: {}", v),
Err(e) => println!("Error: {}", e),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment