Skip to main content

nmbrs_workload/
boolean.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! The one boolean spelling: `true` / `false`.
5//!
6//! Every boolean-valued input — a CLI `key=value` param, a workload
7//! field given as a string, an `NMBRS_*` env flag — goes through
8//! this module. Nothing else counts as a boolean. Spellings that
9//! other tools accept (`on`/`off`, `yes`/`no`, `1`/`0`) are errors
10//! that name the canonical word, so a typo never quietly becomes
11//! `false`.
12
13use serde_json::Value as JVal;
14
15/// Parse `raw` as the value of the boolean `key`.
16///
17/// Accepts exactly `true` or `false`. Anything else is an error
18/// naming `key` and the two accepted words.
19pub 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
27/// Read the boolean `key` from a workload value: a YAML/JSON bool,
28/// or a string spelled `true` / `false` (the form a `{param}`
29/// substitution or a CLI override produces).
30pub 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
38/// Read the boolean env flag `name`. Unset is `false`; a set value
39/// must be `true` or `false`.
40pub 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
48/// True when `raw` is a canonical boolean word.
49pub 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}