Skip to main content

reifydb_value/config/
bool.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 ReifyDB
3
4use super::Config;
5
6impl Config {
7	pub fn bool(&self, key: &str) -> Option<bool> {
8		self.opt(key)
9	}
10
11	pub fn require_bool(&self, key: &str) -> bool {
12		self.opt(key).unwrap_or_else(|| self.missing(key, "a boolean"))
13	}
14
15	pub fn bool_or(&self, key: &str, default: bool) -> bool {
16		self.opt(key).unwrap_or(default)
17	}
18}
19
20#[cfg(test)]
21mod tests {
22	use super::super::testutil::config;
23	use crate::value::Value;
24
25	#[test]
26	fn casts_boolean_values() {
27		let cfg = config(vec![("t", Value::Boolean(true)), ("f", Value::Boolean(false))]);
28		assert_eq!(cfg.bool("t"), Some(true));
29		assert_eq!(cfg.bool("f"), Some(false));
30	}
31
32	#[test]
33	fn rejects_non_boolean_values() {
34		let cfg = config(vec![
35			("n", Value::Uint4(1)),
36			("z", Value::Uint4(0)),
37			("f", Value::float8(1.0)),
38			("s", Value::utf8("true")),
39		]);
40		assert_eq!(cfg.bool("n"), None, "integers do not coerce to bool");
41		assert_eq!(cfg.bool("z"), None, "zero does not coerce to false");
42		assert_eq!(cfg.bool("f"), None, "floats do not coerce to bool");
43		assert_eq!(cfg.bool("s"), None, "the string \"true\" is not a boolean");
44	}
45
46	#[test]
47	fn or_and_require_behavior() {
48		let cfg = config(vec![("present", Value::Boolean(true))]);
49		assert!(cfg.bool_or("present", false), "present value wins over default");
50		assert!(cfg.bool_or("absent", true), "default returned when absent");
51		assert!(cfg.require_bool("present"));
52	}
53
54	#[test]
55	#[should_panic(expected = "is missing or not a boolean")]
56	fn require_panics_when_missing() {
57		let cfg = config(vec![]);
58		cfg.require_bool("k");
59	}
60}