Skip to content

Instantly share code, notes, and snippets.

@danielpclark
Last active November 14, 2017 21:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielpclark/b6f290c7addaed13883432c529c2066b to your computer and use it in GitHub Desktop.
Save danielpclark/b6f290c7addaed13883432c529c2066b to your computer and use it in GitHub Desktop.
use std::fmt;
use std::error::Error as StdError;
use std::fs::File;
use std::io::{Read,BufReader};
#[derive(Debug)]
pub enum Error {
ConfigLoadFail,
ConfigParseFail,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::ConfigLoadFail => f.write_str("ConfigLoadFail"),
Error::ConfigParseFail => f.write_str("ConfigParseFail"),
}
}
}
impl StdError for Error {
fn description(&self) -> &str {
match *self {
Error::ConfigLoadFail => "The configuration file failed to load.",
Error::ConfigParseFail => "The configuration file failed to parse.",
}
}
}
#[derive(Debug,PartialEq)]
struct Config {
data: Vec<u8>
}
#[allow(dead_code)]
// Wrong
fn read_config1() -> Result<Config, Error> {
let file = File::open("program.cfg");
if let Ok(f) = file {
let mut buf_reader = BufReader::new(f);
let mut contents = String::new();
if buf_reader.read_to_string(&mut contents).is_ok() {
let mut data: Vec<u8> = vec![];
for item in contents.
split("\n").
map(|s| s.to_string()).
filter(|s| !s.is_empty()).
collect::<Vec<String>>() {
let num = item.parse::<u8>();
if let Ok(conf) = num {
data.push(conf);
} else {
return Err(Error::ConfigParseFail);
}
}
Ok( Config { data: data } )
} else {
Err(Error::ConfigLoadFail)
}
} else {
Err(Error::ConfigLoadFail)
}
}
#[test]
fn read_1() {
let result = read_config1().unwrap();
assert_eq!(result, Config { data: vec![1,2,3] });
}
#[allow(dead_code)]
// Wrong
fn read_config2() -> Result<Config, Error> {
let file = File::open("program.cfg");
match file {
Ok(f) => {
let mut buf_reader = BufReader::new(f);
let mut contents = String::new();
match buf_reader.read_to_string(&mut contents) {
Ok(_) => {
let mut data: Vec<u8> = vec![];
for item in contents.
split("\n").
map(|s| s.to_string()).
filter(|s| !s.is_empty()).
collect::<Vec<String>>() {
let num = item.parse::<u8>();
match num {
Ok(conf) => data.push(conf),
_ => { return Err(Error::ConfigParseFail); },
}
}
Ok( Config { data: data } )
},
_ => { Err(Error::ConfigLoadFail) }
}
},
_ => { Err(Error::ConfigLoadFail) }
}
}
#[test]
fn read_2() {
let result = read_config2().unwrap();
assert_eq!(result, Config { data: vec![1,2,3] });
}
#[allow(dead_code)]
// Wrong
fn read_config3() -> Result<Config, Error> {
let file = File::open("program.cfg");
if let Ok(f) = file {
let mut buf_reader = BufReader::new(f);
let mut contents = String::new();
if buf_reader.read_to_string(&mut contents).is_ok() {
let mut data: Vec<u8> = vec![];
for item in contents.
split("\n").
map(|s| s.to_string()).
filter(|s| !s.is_empty()).
collect::<Vec<String>>() {
let num = item.parse::<u8>();
if let Ok(conf) = num {
data.push(conf);
} else {
return Err(Error::ConfigParseFail);
}
}
return Ok( Config { data: data } );
}
}
Err(Error::ConfigLoadFail)
}
#[test]
fn read_3() {
let result = read_config3().unwrap();
assert_eq!(result, Config { data: vec![1,2,3] });
}
#[allow(dead_code)]
// Correct
fn read_config4() -> Result<Config, Error> {
let file = File::open("program.cfg");
// Correct use of Guard
if let Err(_) = file { return Err(Error::ConfigLoadFail); }
let f = file.unwrap();
let mut buf_reader = BufReader::new(f);
let mut contents = String::new();
// Correct use of Guard
if let Err(_) = buf_reader.read_to_string(&mut contents) {
return Err(Error::ConfigLoadFail);
}
let mut data: Vec<u8> = vec![];
for item in contents.
split("\n").
map(|s| s.to_string()).
filter(|s| !s.is_empty()).
collect::<Vec<String>>() {
let num = item.parse::<u8>();
match num {
Ok(conf) => data.push(conf),
Err(_) => { return Err(Error::ConfigParseFail); }
}
}
Ok( Config { data: data } )
}
#[test]
fn read_4() {
let result = read_config4().unwrap();
assert_eq!(result, Config { data: vec![1,2,3] });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment