-
-
Save JIghtuse/b6b48ce2fe1a384274d4 to your computer and use it in GitHub Desktop.
Shared via Rust Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::str::FromStr; | |
#[derive(Debug)] | |
enum Version { Version1, Version2 } | |
#[derive(Debug)] | |
enum ParseError { InvalidSyntax, UnsupportedVersion } | |
struct NameValue { | |
name: String, | |
value: i32 | |
} | |
impl From<std::num::ParseIntError> for ParseError { | |
fn from(_: std::num::ParseIntError) -> ParseError { | |
ParseError::InvalidSyntax | |
} | |
} | |
// Parse "name=value" strings | |
fn parse_line(line: String) -> Result<NameValue, ParseError> { | |
let mut split = line.split("="); | |
if split.clone().count() != 2 { | |
return Err(ParseError::InvalidSyntax); | |
} | |
let name = match split.next() { | |
Some(s) => s, | |
None => return Err(ParseError::InvalidSyntax), | |
}; | |
let name = String::from(name); | |
let value = match split.next() { | |
Some(v) => v, | |
None => return Err(ParseError::InvalidSyntax), | |
}; | |
let value = try!(i32::from_str(value)); | |
Ok(NameValue{name: name, value: value}) | |
} | |
// Parse "version=N" strings. Assumes "Version1" if string looks differently | |
fn parse_version(line: String) -> Result<Version, ParseError> { | |
let nameval = match parse_line(line) { | |
Ok(v) => v, | |
// old config without version number, assume Version1 | |
Err(_) => return Ok(Version::Version1), | |
}; | |
if nameval.name != "version" { | |
return Err(ParseError::InvalidSyntax); | |
} | |
match nameval.value { | |
1 => Ok(Version::Version1), | |
2 => Ok(Version::Version2), | |
_ => Err(ParseError::UnsupportedVersion), | |
} | |
} | |
fn main() { | |
println!("{:?}", parse_version(String::from("something"))); | |
println!("{:?}", parse_version(String::from("version=1"))); | |
println!("{:?}", parse_version(String::from("version=2"))); | |
println!("{:?}", parse_version(String::from("version=3"))); | |
println!("{:?}", parse_version(String::from("something=3"))); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment