2022-07-26 18:14:26 +03:00
|
|
|
use crate::core::{EString, ParseFragment};
|
|
|
|
use crate::error::{Error, Reason};
|
2022-07-23 22:36:22 +03:00
|
|
|
|
2022-07-26 18:14:26 +03:00
|
|
|
impl ParseFragment for bool {
|
2022-07-23 22:36:22 +03:00
|
|
|
#[inline]
|
2022-07-26 18:14:26 +03:00
|
|
|
fn parse_frag(s: EString) -> crate::Result<Self> {
|
2022-07-23 22:36:22 +03:00
|
|
|
match s.to_lowercase().as_str() {
|
|
|
|
"true" | "t" | "yes" | "y" | "on" | "1" => Ok(true),
|
|
|
|
"false" | "f" | "no" | "n" | "off" | "0" | "" => Ok(false),
|
2022-07-26 18:14:26 +03:00
|
|
|
_ => Err(Error(s, Reason::Parse)),
|
2022-07-23 22:36:22 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn should_parse_bool_variable() {
|
|
|
|
let test_cases = [
|
|
|
|
("1", true),
|
|
|
|
("0", false),
|
|
|
|
("y", true),
|
|
|
|
("f", false),
|
|
|
|
("yes", true),
|
|
|
|
("true", true),
|
|
|
|
("false", false),
|
|
|
|
("t", true),
|
|
|
|
("f", false),
|
|
|
|
("on", true),
|
|
|
|
("off", false),
|
|
|
|
];
|
|
|
|
|
|
|
|
for (val, expected) in test_cases {
|
|
|
|
let estr = EString::from(val);
|
|
|
|
match estr.parse::<bool>() {
|
|
|
|
Ok(res) => assert_eq!(res, expected),
|
|
|
|
_ => unreachable!(),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn should_throw_parse_error() {
|
|
|
|
let estr = EString::from("something");
|
|
|
|
match estr.parse::<bool>() {
|
2022-07-26 18:14:26 +03:00
|
|
|
Err(crate::Error(orig, reason)) => {
|
|
|
|
assert_eq!(orig, EString::from("something"));
|
|
|
|
assert_eq!(reason, crate::Reason::Parse);
|
2022-07-23 22:36:22 +03:00
|
|
|
}
|
|
|
|
_ => unreachable!(),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|