reifydb_value/config/
i64.rs1use super::Config;
5
6impl Config {
7 pub fn i64(&self, key: &str) -> Option<i64> {
8 self.opt_coerce(key)
9 }
10
11 pub fn require_i64(&self, key: &str) -> i64 {
12 self.opt_coerce(key).unwrap_or_else(|| self.missing(key, "an integer"))
13 }
14
15 pub fn i64_or(&self, key: &str, default: i64) -> i64 {
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_every_signed_width() {
27 let cfg = config(vec![
28 ("a", Value::Int1(-1)),
29 ("b", Value::Int2(-2)),
30 ("c", Value::Int4(-3)),
31 ("d", Value::Int8(-4)),
32 ("e", Value::Int16(-5)),
33 ]);
34 assert_eq!(cfg.i64("a"), Some(-1));
35 assert_eq!(cfg.i64("b"), Some(-2));
36 assert_eq!(cfg.i64("c"), Some(-3));
37 assert_eq!(cfg.i64("d"), Some(-4));
38 assert_eq!(cfg.i64("e"), Some(-5), "negative Int16 within range coerces to i64");
39 }
40
41 #[test]
42 fn casts_unsigned_widths_within_range() {
43 let cfg = config(vec![
44 ("a", Value::Uint1(1)),
45 ("b", Value::Uint2(2)),
46 ("c", Value::Uint4(3)),
47 ("d", Value::Uint8(4)),
48 ("e", Value::Uint16(5)),
49 ]);
50 assert_eq!(cfg.i64("a"), Some(1));
51 assert_eq!(cfg.i64("b"), Some(2));
52 assert_eq!(cfg.i64("c"), Some(3));
53 assert_eq!(cfg.i64("d"), Some(4));
54 assert_eq!(cfg.i64("e"), Some(5), "unsigned that fits coerces to i64");
55 }
56
57 #[test]
58 fn rejects_unsigned_above_i64_max() {
59 let cfg = config(vec![("u8", Value::Uint8(u64::MAX)), ("u16", Value::Uint16(i64::MAX as u128 + 1))]);
60 assert_eq!(cfg.i64("u8"), None, "Uint8 above i64::MAX is range-checked and rejected");
61 assert_eq!(cfg.i64("u16"), None, "Uint16 above i64::MAX is range-checked and rejected");
62 }
63
64 #[test]
65 fn rejects_non_integer_values() {
66 let cfg = config(vec![("f", Value::float8(2.0)), ("s", Value::utf8("1"))]);
67 assert_eq!(cfg.i64("f"), None, "floats do not coerce to i64");
68 assert_eq!(cfg.i64("s"), None, "strings are not integers");
69 }
70
71 #[test]
72 fn or_and_require_behavior() {
73 let cfg = config(vec![("present", Value::Int4(-9))]);
74 assert_eq!(cfg.i64_or("present", 1), -9);
75 assert_eq!(cfg.i64_or("absent", 1), 1);
76 assert_eq!(cfg.require_i64("present"), -9);
77 }
78
79 #[test]
80 #[should_panic(expected = "is missing or not an integer")]
81 fn require_panics_when_missing() {
82 let cfg = config(vec![]);
83 cfg.require_i64("k");
84 }
85}