Skip to content

Commit

Permalink
Replace parse return type with ParseResult enum
Browse files Browse the repository at this point in the history
  • Loading branch information
dtolnay committed Jul 16, 2022
1 parent b136ccd commit 1aa68e8
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 6 deletions.
4 changes: 2 additions & 2 deletions build/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ fn main() {
};

let version = match rustc::parse(&string) {
Some(version) => version,
None => {
rustc::ParseResult::Success(version) => version,
rustc::ParseResult::Unrecognized => {
eprintln!(
"Error: unexpected output from `rustc --version`: {:?}\n\n\
Please file an issue in https://github.com/dtolnay/rustversion",
Expand Down
15 changes: 12 additions & 3 deletions build/rustc.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
use self::Channel::*;
use std::fmt::{self, Debug};

pub enum ParseResult {
Success(Version),
Unrecognized,
}

#[cfg_attr(test, derive(PartialEq))]
pub struct Version {
pub minor: u16,
Expand All @@ -23,14 +28,18 @@ pub struct Date {
pub day: u8,
}

pub fn parse(string: &str) -> Option<Version> {
pub fn parse(string: &str) -> ParseResult {
let last_line = string.lines().last().unwrap_or(string);
let mut words = last_line.trim().split(' ');

if words.next()? != "rustc" {
return None;
if words.next() != Some("rustc") {
return ParseResult::Unrecognized;
}

parse_words(&mut words).map_or(ParseResult::Unrecognized, ParseResult::Success)
}

fn parse_words(words: &mut dyn Iterator<Item = &str>) -> Option<Version> {
let mut version_channel = words.next()?.split('-');
let version = version_channel.next()?;
let channel = version_channel.next();
Expand Down
5 changes: 4 additions & 1 deletion tests/test_parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,9 @@ fn test_parse() {
];

for (string, expected) in cases {
assert_eq!(parse(string).unwrap(), *expected);
match parse(string) {
ParseResult::Success(version) => assert_eq!(version, *expected),
ParseResult::Unrecognized => panic!("unrecognized: {:?}", string),
}
}
}

0 comments on commit 1aa68e8

Please sign in to comment.