Skip to main content

reifydb_value/config/
duration.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 ReifyDB
3
4use super::Config;
5use crate::value::duration::Duration;
6
7impl Config {
8	pub fn duration(&self, key: &str) -> Option<Duration> {
9		self.opt(key)
10	}
11
12	pub fn require_duration(&self, key: &str) -> Duration {
13		self.opt(key).unwrap_or_else(|| self.missing(key, "a duration"))
14	}
15
16	pub fn duration_or(&self, key: &str, default: Duration) -> Duration {
17		self.opt(key).unwrap_or(default)
18	}
19}
20
21#[cfg(test)]
22mod tests {
23	use super::super::testutil::config;
24	use crate::value::{Value, duration::Duration, time::Time};
25
26	#[test]
27	fn casts_duration_values() {
28		let d = Duration::from_seconds(60).unwrap();
29		let cfg = config(vec![("d", Value::Duration(d))]);
30		assert_eq!(cfg.duration("d"), Some(d));
31	}
32
33	#[test]
34	fn rejects_other_temporal_and_numeric() {
35		let cfg = config(vec![("t", Value::Time(Time::midnight())), ("n", Value::Uint8(60))]);
36		assert_eq!(cfg.duration("t"), None, "a time does not coerce to a duration");
37		assert_eq!(cfg.duration("n"), None, "a raw integer does not coerce to a duration");
38	}
39
40	#[test]
41	fn rejects_duration_literal_string() {
42		let cfg = config(vec![("d", Value::utf8("1m")), ("sub", Value::utf8("1s"))]);
43		assert_eq!(cfg.duration("d"), None, "a duration literal string is not a duration");
44		assert_eq!(cfg.duration("sub"), None, "a sub-minute duration literal string is not a duration either");
45		assert_eq!(
46			cfg.duration_or("sub", Duration::from_seconds(1).unwrap()),
47			Duration::from_seconds(1).unwrap(),
48			"a string falls through to the default rather than parsing sub-minute"
49		);
50	}
51
52	#[test]
53	#[should_panic(expected = "is missing or not a duration")]
54	fn require_panics_on_duration_literal_string() {
55		let cfg = config(vec![("d", Value::utf8("1m"))]);
56		cfg.require_duration("d");
57	}
58
59	#[test]
60	fn accepts_sub_minute_duration_value() {
61		let sub = Duration::from_seconds(1).unwrap();
62		let cfg = config(vec![("sub", Value::Duration(sub))]);
63		assert_eq!(
64			cfg.require_duration("sub"),
65			sub,
66			"a sub-minute duration must stay sub-minute, not round up"
67		);
68	}
69
70	#[test]
71	fn or_and_require_behavior() {
72		let d = Duration::from_seconds(60).unwrap();
73		let default = Duration::zero();
74		let cfg = config(vec![("present", Value::Duration(d))]);
75		assert_eq!(cfg.duration_or("present", default), d);
76		assert_eq!(cfg.duration_or("absent", default), default);
77		assert_eq!(cfg.require_duration("present"), d);
78	}
79
80	#[test]
81	#[should_panic(expected = "is missing or not a duration")]
82	fn require_panics_when_missing() {
83		let cfg = config(vec![]);
84		cfg.require_duration("k");
85	}
86}