reifydb_core/key/
namespace_dictionary.rs1use reifydb_type::value::dictionary::DictionaryId;
5
6use super::{EncodableKey, KeyKind};
7use crate::{
8 encoded::key::{EncodedKey, EncodedKeyRange},
9 interface::catalog::id::NamespaceId,
10 util::encoding::keycode::{deserializer::KeyDeserializer, serializer::KeySerializer},
11};
12
13#[derive(Debug, Clone, PartialEq)]
14pub struct NamespaceDictionaryKey {
15 pub namespace: NamespaceId,
16 pub dictionary: DictionaryId,
17}
18
19impl NamespaceDictionaryKey {
20 pub fn new(namespace: NamespaceId, dictionary: DictionaryId) -> Self {
21 Self {
22 namespace,
23 dictionary,
24 }
25 }
26
27 pub fn encoded(namespace: impl Into<NamespaceId>, dictionary: impl Into<DictionaryId>) -> EncodedKey {
28 Self::new(namespace.into(), dictionary.into()).encode()
29 }
30
31 pub fn full_scan(namespace: NamespaceId) -> EncodedKeyRange {
32 EncodedKeyRange::start_end(Some(Self::link_start(namespace)), Some(Self::link_end(namespace)))
33 }
34
35 fn link_start(namespace: NamespaceId) -> EncodedKey {
36 let mut serializer = KeySerializer::with_capacity(9);
37 serializer.extend_u8(Self::KIND as u8).extend_u64(namespace);
38 serializer.to_encoded_key()
39 }
40
41 fn link_end(namespace: NamespaceId) -> EncodedKey {
42 let mut serializer = KeySerializer::with_capacity(9);
43 serializer.extend_u8(Self::KIND as u8).extend_u64(*namespace - 1);
44 serializer.to_encoded_key()
45 }
46}
47
48impl EncodableKey for NamespaceDictionaryKey {
49 const KIND: KeyKind = KeyKind::NamespaceDictionary;
50
51 fn encode(&self) -> EncodedKey {
52 let mut serializer = KeySerializer::with_capacity(17);
53 serializer.extend_u8(Self::KIND as u8).extend_u64(self.namespace).extend_u64(self.dictionary);
54 serializer.to_encoded_key()
55 }
56
57 fn decode(key: &EncodedKey) -> Option<Self> {
58 let mut de = KeyDeserializer::from_bytes(key.as_slice());
59
60 let kind: KeyKind = de.read_u8().ok()?.try_into().ok()?;
61 if kind != Self::KIND {
62 return None;
63 }
64
65 let namespace = de.read_u64().ok()?;
66 let dictionary = de.read_u64().ok()?;
67
68 Some(Self {
69 namespace: NamespaceId(namespace),
70 dictionary: DictionaryId(dictionary),
71 })
72 }
73}
74
75#[cfg(test)]
76pub mod tests {
77 use std::ops::Bound;
78
79 use super::*;
80
81 #[test]
82 fn test_namespace_dictionary_key_encode_decode() {
83 let key = NamespaceDictionaryKey {
84 namespace: NamespaceId(1025),
85 dictionary: DictionaryId(2048),
86 };
87 let encoded = key.encode();
88 let decoded = NamespaceDictionaryKey::decode(&encoded).unwrap();
89 assert_eq!(decoded.namespace, key.namespace);
90 assert_eq!(decoded.dictionary, key.dictionary);
91 }
92
93 #[test]
94 fn test_namespace_dictionary_key_full_scan() {
95 let range = NamespaceDictionaryKey::full_scan(NamespaceId(1025));
96 assert!(matches!(range.start, Bound::Included(_) | Bound::Excluded(_)));
97 assert!(matches!(range.end, Bound::Included(_) | Bound::Excluded(_)));
98 }
99}