Skip to content

Commit

Permalink
Fix rational_numbers example (from_str now returns Result, not Option).
Browse files Browse the repository at this point in the history
Also: Remove warning about unnecessary `mut`.
  • Loading branch information
timhabermaas committed Feb 3, 2015
1 parent 6d5d165 commit 96468d0
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
17 changes: 11 additions & 6 deletions examples/rational_numbers.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! This example shows how to write your own custom implementation of
//! `Decodable` to parse rational numbers.

#![feature(collections, core)]
#![feature(core)]

extern crate csv;
extern crate regex;
Expand All @@ -23,22 +23,27 @@ impl Decodable for Rational {
let field = try!(d.read_str());
// This uses the `FromStr` impl below.
match field.parse() {
Some(rat) => Ok(rat),
None => Err(d.error(&*format!(
Ok(rat) => Ok(rat),
Err(_) => Err(d.error(&*format!(
"Could not parse '{}' as a rational.", field))),
}
}
}

impl str::FromStr for Rational {
type Err = csv::Error;

/// Parse a string into a Rational. Allow for the possibility of whitespace
/// around `/`.
fn from_str(s: &str) -> Option<Rational> {
fn from_str(s: &str) -> Result<Rational, csv::Error> {
let re = Regex::new(r"^([0-9]+)\s*/\s*([0-9]+)$").unwrap();
re.captures(s).map(|caps| Rational {
match re.captures(s).map(|caps| Rational {
numerator: caps.at(1).unwrap().parse().unwrap(),
denominator: caps.at(2).unwrap().parse().unwrap(),
})
}) {
Some(r) => Ok(r),
None => Err(csv::Error::Encode(format!("Failed to parse Rational {}", s))),
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ impl<W: io::Writer> Writer<W> {
/// Writes a record of results. If any of the results resolve to an error,
/// then writing stops and that error is returned.
#[doc(hidden)]
pub fn write_iter<'a, I, F>(&mut self, mut r: I) -> CsvResult<()>
pub fn write_iter<'a, I, F>(&mut self, r: I) -> CsvResult<()>
where I: Iterator<Item=CsvResult<F>>, F: BorrowBytes {
let delim = self.delimiter;
let mut count = 0;
Expand Down

0 comments on commit 96468d0

Please sign in to comment.