Skip to main content

reifydb_value/config/
u16.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 ReifyDB
3
4use super::Config;
5
6impl Config {
7	pub fn u16(&self, key: &str) -> Option<u16> {
8		self.opt_coerce(key)
9	}
10
11	pub fn require_u16(&self, key: &str) -> u16 {
12		self.opt_coerce(key).unwrap_or_else(|| self.missing(key, "an unsigned integer"))
13	}
14
15	pub fn u16_or(&self, key: &str, default: u16) -> u16 {
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_widths_that_fit() {
27		let cfg = config(vec![("a", Value::Uint2(65535)), ("b", Value::Uint8(1000)), ("c", Value::Int4(7))]);
28		assert_eq!(cfg.u16("a"), Some(65535));
29		assert_eq!(cfg.u16("b"), Some(1000));
30		assert_eq!(cfg.u16("c"), Some(7), "non-negative signed coerces to u16");
31	}
32
33	#[test]
34	fn rejects_out_of_range_and_negative() {
35		let cfg = config(vec![("hi", Value::Uint4(65536)), ("neg", Value::Int2(-1))]);
36		assert_eq!(cfg.u16("hi"), None, "65536 exceeds u16::MAX");
37		assert_eq!(cfg.u16("neg"), None, "negative does not coerce to unsigned");
38	}
39
40	#[test]
41	fn rejects_non_integer() {
42		let cfg = config(vec![("f", Value::float8(1.0)), ("b", Value::Boolean(false))]);
43		assert_eq!(cfg.u16("f"), None);
44		assert_eq!(cfg.u16("b"), None);
45	}
46
47	#[test]
48	fn or_and_require_behavior() {
49		let cfg = config(vec![("present", Value::Uint2(9))]);
50		assert_eq!(cfg.u16_or("present", 1), 9);
51		assert_eq!(cfg.u16_or("absent", 1), 1);
52		assert_eq!(cfg.require_u16("present"), 9);
53	}
54
55	#[test]
56	#[should_panic(expected = "is missing or not an unsigned integer")]
57	fn require_panics_when_missing() {
58		let cfg = config(vec![]);
59		cfg.require_u16("k");
60	}
61}