nmbrs_workload/
boolean.rs1use serde_json::Value as JVal;
14
15pub fn parse_bool(key: &str, raw: &str) -> Result<bool, String> {
20 match raw {
21 "true" => Ok(true),
22 "false" => Ok(false),
23 other => Err(not_a_boolean(key, other)),
24 }
25}
26
27pub fn json_bool(key: &str, value: &JVal) -> Result<bool, String> {
31 match value {
32 JVal::Bool(b) => Ok(*b),
33 JVal::String(s) => parse_bool(key, s),
34 other => Err(not_a_boolean(key, &other.to_string())),
35 }
36}
37
38pub fn env_flag(name: &str) -> Result<bool, String> {
41 match std::env::var(name) {
42 Ok(v) => parse_bool(name, &v),
43 Err(std::env::VarError::NotPresent) => Ok(false),
44 Err(std::env::VarError::NotUnicode(_)) => Err(not_a_boolean(name, "<non-UTF-8>")),
45 }
46}
47
48pub fn is_bool_word(raw: &str) -> bool {
50 matches!(raw, "true" | "false")
51}
52
53fn not_a_boolean(key: &str, raw: &str) -> String {
54 format!("{key}={raw}: not a boolean; write {key}=true or {key}=false")
55}
56
57#[cfg(test)]
58mod tests {
59 use super::*;
60 use serde_json::json;
61
62 #[test]
63 fn only_true_and_false_are_booleans() {
64 assert_eq!(parse_bool("k", "true"), Ok(true));
65 assert_eq!(parse_bool("k", "false"), Ok(false));
66 for other in ["on", "off", "yes", "no", "1", "0", "", "True", "FALSE"] {
67 let err = parse_bool("k", other).expect_err(other);
68 assert!(err.contains("write k=true or k=false"), "{err}");
69 }
70 }
71
72 #[test]
73 fn json_bool_takes_bools_and_canonical_strings_only() {
74 assert_eq!(json_bool("k", &json!(true)), Ok(true));
75 assert_eq!(json_bool("k", &json!("false")), Ok(false));
76 assert!(json_bool("k", &json!("on")).is_err());
77 assert!(json_bool("k", &json!(1)).is_err());
78 assert!(json_bool("k", &json!(null)).is_err());
79 }
80}