reifydb_core/key/
namespace_dictionary.rs1use super::{EncodableKey, KeyKind};
5use crate::{
6 EncodedKey, EncodedKeyRange,
7 interface::{DictionaryId, NamespaceId},
8 util::encoding::keycode::{KeyDeserializer, KeySerializer},
9};
10
11const VERSION: u8 = 1;
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 full_scan(namespace: NamespaceId) -> EncodedKeyRange {
28 EncodedKeyRange::start_end(Some(Self::link_start(namespace)), Some(Self::link_end(namespace)))
29 }
30
31 fn link_start(namespace: NamespaceId) -> EncodedKey {
32 let mut serializer = KeySerializer::with_capacity(10);
33 serializer.extend_u8(VERSION).extend_u8(Self::KIND as u8).extend_u64(namespace);
34 serializer.to_encoded_key()
35 }
36
37 fn link_end(namespace: NamespaceId) -> EncodedKey {
38 let mut serializer = KeySerializer::with_capacity(10);
39 serializer.extend_u8(VERSION).extend_u8(Self::KIND as u8).extend_u64(*namespace - 1);
40 serializer.to_encoded_key()
41 }
42}
43
44impl EncodableKey for NamespaceDictionaryKey {
45 const KIND: KeyKind = KeyKind::NamespaceDictionary;
46
47 fn encode(&self) -> EncodedKey {
48 let mut serializer = KeySerializer::with_capacity(18);
49 serializer
50 .extend_u8(VERSION)
51 .extend_u8(Self::KIND as u8)
52 .extend_u64(self.namespace)
53 .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 version = de.read_u8().ok()?;
61 if version != VERSION {
62 return None;
63 }
64
65 let kind: KeyKind = de.read_u8().ok()?.try_into().ok()?;
66 if kind != Self::KIND {
67 return None;
68 }
69
70 let namespace = de.read_u64().ok()?;
71 let dictionary = de.read_u64().ok()?;
72
73 Some(Self {
74 namespace: NamespaceId(namespace),
75 dictionary: DictionaryId(dictionary),
76 })
77 }
78}
79
80#[cfg(test)]
81mod tests {
82 use super::*;
83
84 #[test]
85 fn test_namespace_dictionary_key_encode_decode() {
86 let key = NamespaceDictionaryKey {
87 namespace: NamespaceId(1025),
88 dictionary: DictionaryId(2048),
89 };
90 let encoded = key.encode();
91 let decoded = NamespaceDictionaryKey::decode(&encoded).unwrap();
92 assert_eq!(decoded.namespace, key.namespace);
93 assert_eq!(decoded.dictionary, key.dictionary);
94 }
95
96 #[test]
97 fn test_namespace_dictionary_key_full_scan() {
98 use std::ops::Bound;
99 let range = NamespaceDictionaryKey::full_scan(NamespaceId(1025));
100 assert!(matches!(range.start, Bound::Included(_) | Bound::Excluded(_)));
101 assert!(matches!(range.end, Bound::Included(_) | Bound::Excluded(_)));
102 }
103}