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