#[must_use]
pub fn present(raw: Option<&str>) -> Option<&str> {
raw.map(str::trim).filter(|value| !value.is_empty())
}
pub const TRUE_SPELLINGS: [&str; 4] = ["true", "1", "yes", "on"];
pub const FALSE_SPELLINGS: [&str; 4] = ["false", "0", "no", "off"];
#[must_use]
pub fn parse_bool(raw: Option<&str>) -> Option<bool> {
let value = present(raw)?.to_ascii_lowercase();
if TRUE_SPELLINGS.contains(&value.as_str()) {
Some(true)
} else if FALSE_SPELLINGS.contains(&value.as_str()) {
Some(false)
} else {
None
}
}
#[must_use]
pub fn parse_bool_lenient(raw: Option<&str>) -> Option<bool> {
present(raw).map(|value| !FALSE_SPELLINGS.contains(&value.to_ascii_lowercase().as_str()))
}
#[must_use]
pub fn parse_csv(raw: Option<&str>) -> Vec<String> {
parse_separated(raw, ',')
}
#[must_use]
pub fn parse_separated(raw: Option<&str>, separator: char) -> Vec<String> {
present(raw)
.map(|value| {
value
.split(separator)
.map(str::trim)
.filter(|element| !element.is_empty())
.map(str::to_string)
.collect()
})
.unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn blank_is_the_same_as_absent() {
assert_eq!(present(Some("")), None);
assert_eq!(present(Some(" \t\n")), None);
assert_eq!(present(None), None);
}
#[test]
fn values_are_trimmed() {
assert_eq!(present(Some("\t orders \n")), Some("orders"));
}
#[test]
fn the_strict_reader_accepts_four_spellings_each_way() {
for text in ["true", "TRUE", "True", "1", "yes", "YES", "on", "ON"] {
assert_eq!(parse_bool(Some(text)), Some(true), "{text}");
}
for text in ["false", "FALSE", "False", "0", "no", "NO", "off", "OFF"] {
assert_eq!(parse_bool(Some(text)), Some(false), "{text}");
}
}
#[test]
fn the_strict_reader_refuses_to_guess() {
for text in ["disabled", "enabled", "nope", "flase", "y", "n", "2"] {
assert_eq!(parse_bool(Some(text)), None, "{text}");
}
}
#[test]
fn the_lenient_reader_is_lopsided_on_purpose() {
for text in ["false", "FALSE", "0", "no", "off"] {
assert_eq!(parse_bool_lenient(Some(text)), Some(false), "{text}");
}
for text in ["true", "1", "yes", "on", "disabled", "nope", "flase"] {
assert_eq!(parse_bool_lenient(Some(text)), Some(true), "{text}");
}
}
#[test]
fn a_blank_boolean_has_no_opinion_either_way() {
assert_eq!(parse_bool(Some(" ")), None);
assert_eq!(parse_bool(None), None);
assert_eq!(parse_bool_lenient(Some(" ")), None);
assert_eq!(parse_bool_lenient(None), None);
}
#[test]
fn a_list_drops_empty_elements() {
assert_eq!(parse_csv(Some("ADT_A05, ,ADT_A39,")), ["ADT_A05", "ADT_A39"]);
}
#[test]
fn a_list_of_nothing_is_empty_not_one_empty_element() {
assert!(parse_csv(Some("")).is_empty());
assert!(parse_csv(Some(",")).is_empty());
assert!(parse_csv(None).is_empty());
}
#[test]
fn a_list_can_use_another_separator() {
assert_eq!(parse_separated(Some("/usr/bin:/bin:"), ':'), ["/usr/bin", "/bin"]);
}
}