Skip to content

Commit 7e023eb

Browse files
committed
config: properly handle decoding errors
Signed-off-by: Paul Osborne <[email protected]>
1 parent 4d6e2a9 commit 7e023eb

File tree

1 file changed

+33
-2
lines changed

1 file changed

+33
-2
lines changed

src/config.rs

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ pub struct GpioConfig {
2828
pub enum Error {
2929
IoError(io::Error),
3030
ParserErrors(Vec<toml::ParserError>),
31+
DecodingError(toml::DecodeError),
3132
NoConfigFound,
3233
}
3334

@@ -53,6 +54,12 @@ impl From<Vec<toml::ParserError>> for Error {
5354
}
5455
}
5556

57+
impl From<toml::DecodeError> for Error {
58+
fn from(e: toml::DecodeError) -> Self {
59+
Error::DecodingError(e)
60+
}
61+
}
62+
5663
impl GpioConfig {
5764

5865
/// Load a GPIO Config from the system
@@ -82,7 +89,7 @@ impl GpioConfig {
8289

8390
// /etc/gpio.d/*.toml
8491
for fragment in glob("/etc/gpio.d/*.toml").unwrap().filter_map(Result::ok) {
85-
config_instances.push(try!(Self::from_file("/etc/gpio.toml")));
92+
config_instances.push(try!(Self::from_file(fragment)));
8693
}
8794

8895
// additional from command-line
@@ -104,7 +111,10 @@ impl GpioConfig {
104111
let mut parser = toml::Parser::new(config);
105112
let root = try!(parser.parse().ok_or(parser.errors));
106113
let mut d = toml::Decoder::new(toml::Value::Table(root));
107-
Ok(Decodable::decode(&mut d).unwrap())
114+
match Decodable::decode(&mut d) {
115+
Ok(cfg) => Ok(cfg),
116+
Err(e) => Err(Error::from(e)),
117+
}
108118
}
109119

110120
/// Load a GPIO config from the specified path
@@ -165,6 +175,27 @@ error_led = { num = 11, direction = "in", export = false}
165175
assert_eq!(status_led.export, None);
166176
}
167177

178+
#[test]
179+
fn test_parser_empty_toml() {
180+
let configstr = "";
181+
match GpioConfig::from_str(configstr) {
182+
Err(Error::DecodingError(_)) => {},
183+
_ => panic!("Expected a decoding error"),
184+
}
185+
}
186+
187+
#[test]
188+
fn test_parser_missing_pinnum() {
189+
let configstr = r#"
190+
[pins.reset_button]
191+
export = true
192+
"#;
193+
match GpioConfig::from_str(configstr) {
194+
Err(Error::DecodingError(_)) => {},
195+
_ => panic!("Expected a decoding error"),
196+
}
197+
}
198+
168199
#[test]
169200
fn test_parse_error_bad_toml() {
170201
// basically, just garbage data

0 commit comments

Comments
 (0)