Skip to main content

reifydb_value/config/
dictionary.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 ReifyDB
3
4use super::Config;
5use crate::value::dictionary::DictionaryEntryId;
6
7impl Config {
8	pub fn dictionary_id(&self, key: &str) -> Option<DictionaryEntryId> {
9		self.get(key).and_then(DictionaryEntryId::from_value)
10	}
11
12	pub fn require_dictionary_id(&self, key: &str) -> DictionaryEntryId {
13		self.dictionary_id(key).unwrap_or_else(|| self.missing(key, "a dictionary id"))
14	}
15
16	pub fn dictionary_id_or(&self, key: &str, default: DictionaryEntryId) -> DictionaryEntryId {
17		self.dictionary_id(key).unwrap_or(default)
18	}
19}
20
21#[cfg(test)]
22mod tests {
23	use super::super::testutil::config;
24	use crate::value::{Value, dictionary::DictionaryEntryId};
25
26	#[test]
27	fn casts_dictionary_id_values() {
28		let id = DictionaryEntryId::U4(42);
29		let cfg = config(vec![("id", Value::DictionaryId(id))]);
30		assert_eq!(cfg.dictionary_id("id"), Some(id));
31	}
32
33	#[test]
34	fn maps_unsigned_integers_by_width() {
35		let cfg = config(vec![("u1", Value::Uint1(7)), ("u4", Value::Uint4(42)), ("u16", Value::Uint16(99))]);
36		assert_eq!(cfg.dictionary_id("u1"), Some(DictionaryEntryId::U1(7)));
37		assert_eq!(cfg.dictionary_id("u4"), Some(DictionaryEntryId::U4(42)));
38		assert_eq!(
39			cfg.dictionary_id("u16"),
40			Some(DictionaryEntryId::U16(99)),
41			"unsigned integers map to a dictionary id by their width"
42		);
43	}
44
45	#[test]
46	fn rejects_signed_and_non_numeric() {
47		let cfg = config(vec![("i", Value::Int4(42)), ("b", Value::Boolean(true)), ("s", Value::utf8("42"))]);
48		assert_eq!(cfg.dictionary_id("i"), None, "a signed integer is not a dictionary id");
49		assert_eq!(cfg.dictionary_id("b"), None, "a boolean is not a dictionary id");
50		assert_eq!(cfg.dictionary_id("s"), None, "a string is not a dictionary id");
51	}
52
53	#[test]
54	fn or_and_require_behavior() {
55		let id = DictionaryEntryId::U4(42);
56		let default = DictionaryEntryId::U1(0);
57		let cfg = config(vec![("present", Value::DictionaryId(id))]);
58		assert_eq!(cfg.dictionary_id_or("present", default), id);
59		assert_eq!(cfg.dictionary_id_or("absent", default), default);
60		assert_eq!(cfg.require_dictionary_id("present"), id);
61	}
62
63	#[test]
64	#[should_panic(expected = "is missing or not a dictionary id")]
65	fn require_panics_when_missing() {
66		let cfg = config(vec![]);
67		cfg.require_dictionary_id("k");
68	}
69}