Skip to main content

reifydb_value/config/
f64.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 ReifyDB
3
4use super::Config;
5
6impl Config {
7	pub fn f64(&self, key: &str) -> Option<f64> {
8		self.opt_coerce(key)
9	}
10
11	pub fn require_f64(&self, key: &str) -> f64 {
12		self.opt_coerce(key).unwrap_or_else(|| self.missing(key, "a number"))
13	}
14
15	pub fn f64_or(&self, key: &str, default: f64) -> f64 {
16		self.opt_coerce(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_both_float_widths() {
27		let cfg = config(vec![("f8", Value::float8(0.70)), ("f4", Value::float4(0.5f32))]);
28		assert_eq!(cfg.f64("f8"), Some(0.70));
29		assert_eq!(cfg.f64("f4"), Some(0.5), "Float4 widens to f64");
30	}
31
32	#[test]
33	fn casts_every_unsigned_width() {
34		let cfg = config(vec![
35			("a", Value::Uint1(1)),
36			("b", Value::Uint2(2)),
37			("c", Value::Uint4(3)),
38			("d", Value::Uint8(4)),
39			("e", Value::Uint16(5)),
40		]);
41		assert_eq!(cfg.f64("a"), Some(1.0));
42		assert_eq!(cfg.f64("b"), Some(2.0));
43		assert_eq!(cfg.f64("c"), Some(3.0));
44		assert_eq!(cfg.f64("d"), Some(4.0));
45		assert_eq!(cfg.f64("e"), Some(5.0), "Uint16 coerces to f64");
46	}
47
48	#[test]
49	fn casts_every_signed_width() {
50		let cfg = config(vec![
51			("a", Value::Int1(-1)),
52			("b", Value::Int2(-2)),
53			("c", Value::Int4(-3)),
54			("d", Value::Int8(-4)),
55			("e", Value::Int16(-5)),
56		]);
57		assert_eq!(cfg.f64("a"), Some(-1.0));
58		assert_eq!(cfg.f64("b"), Some(-2.0));
59		assert_eq!(cfg.f64("c"), Some(-3.0));
60		assert_eq!(cfg.f64("d"), Some(-4.0));
61		assert_eq!(cfg.f64("e"), Some(-5.0), "Int16 coerces to f64");
62	}
63
64	#[test]
65	fn rejects_non_numeric_values() {
66		let cfg = config(vec![("s", Value::utf8("1.5")), ("b", Value::Boolean(true))]);
67		assert_eq!(cfg.f64("s"), None, "strings are not numbers");
68		assert_eq!(cfg.f64("b"), None, "booleans are not numbers");
69	}
70
71	#[test]
72	fn or_and_require_behavior() {
73		let cfg = config(vec![("present", Value::float8(0.70))]);
74		assert_eq!(cfg.f64_or("present", 1.0), 0.70);
75		assert_eq!(cfg.f64_or("absent", 0.70), 0.70);
76		assert_eq!(cfg.require_f64("present"), 0.70);
77	}
78
79	#[test]
80	#[should_panic(expected = "is missing or not a number")]
81	fn require_panics_when_missing() {
82		let cfg = config(vec![]);
83		cfg.require_f64("k");
84	}
85}