Commit 386228b1 authored by Scott Abbey's avatar Scott Abbey

Introduce lazy_static and return Result

parent 02cb736e
......@@ -5,3 +5,4 @@ authors = ["Steve Klabnik <steve@steveklabnik.com>"]
[dependencies]
regex = "0.1.69"
lazy_static = "0.2.1"
extern crate regex;
#[macro_use]
extern crate lazy_static;
use regex::Regex;
use std::error::Error;
lazy_static! {
static ref REGEX: Regex = {
let major = r"0|(:?[1-9][0-9]*)";
let minor = r"0|(:?[1-9][0-9]*)";
let patch = r"0|(:?[1-9][0-9]*)";
let regex = format!(r"^(?P<major>{})\.(?P<minor>{})\.(?P<patch>{})$", major, minor, patch);
let regex = Regex::new(&regex);
// this unwrap is okay because everything above here is const, so this will never fail.
regex.unwrap()
};
}
pub struct Version {
major: u64,
minor: u64,
patch: u64,
}
pub fn parse_version(version: &str) -> Version {
let re = Regex::new(r"(\d+).(\d+).(\d+)").unwrap();
let captures = re.captures(version).unwrap();
Version {
major: captures.at(1).unwrap().parse().unwrap(),
minor: captures.at(2).unwrap().parse().unwrap(),
patch: captures.at(3).unwrap().parse().unwrap(),
}
pub fn parse_version(version: &str) -> Result<Version, Box<Error>> {
let captures = match REGEX.captures(version) {
Some(captures) => captures,
None => return Err(From::from("Version did not parse properly.")),
};
Ok(Version {
major: captures.name("major").unwrap().parse().unwrap(),
minor: captures.name("minor").unwrap().parse().unwrap(),
patch: captures.name("patch").unwrap().parse().unwrap(),
})
}
#[cfg(test)]
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment