Skip to main content

reifydb_core/key/
config.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2025 ReifyDB
3
4use std::str::FromStr;
5
6use super::{EncodableKey, KeyKind};
7use crate::{
8	encoded::key::{EncodedKey, EncodedKeyRange},
9	interface::catalog::config::ConfigKey,
10	util::encoding::keycode::{deserializer::KeyDeserializer, serializer::KeySerializer},
11};
12
13const VERSION: u8 = 1;
14
15#[derive(Debug, Clone, PartialEq)]
16pub struct ConfigStorageKey {
17	pub key: ConfigKey,
18}
19
20impl ConfigStorageKey {
21	pub fn new(key: ConfigKey) -> Self {
22		Self {
23			key,
24		}
25	}
26
27	pub fn for_key(key: ConfigKey) -> EncodedKey {
28		Self::new(key).encode()
29	}
30
31	pub fn full_scan() -> EncodedKeyRange {
32		let mut start = KeySerializer::with_capacity(2);
33		start.extend_u8(VERSION).extend_u8(Self::KIND as u8);
34		let mut end = KeySerializer::with_capacity(2);
35		end.extend_u8(VERSION).extend_u8(Self::KIND as u8 - 1);
36		EncodedKeyRange::start_end(Some(start.to_encoded_key()), Some(end.to_encoded_key()))
37	}
38}
39
40impl EncodableKey for ConfigStorageKey {
41	const KIND: KeyKind = KeyKind::ConfigStorage;
42
43	fn encode(&self) -> EncodedKey {
44		let mut serializer = KeySerializer::with_capacity(32);
45		serializer.extend_u8(VERSION).extend_u8(Self::KIND as u8).extend_str(self.key.to_string());
46		serializer.to_encoded_key()
47	}
48
49	fn decode(key: &EncodedKey) -> Option<Self> {
50		let mut de = KeyDeserializer::from_bytes(key.as_slice());
51
52		let version = de.read_u8().ok()?;
53		if version != VERSION {
54			return None;
55		}
56
57		let kind: KeyKind = de.read_u8().ok()?.try_into().ok()?;
58		if kind != Self::KIND {
59			return None;
60		}
61
62		let config_key_str = de.read_str().ok()?;
63		let key = ConfigKey::from_str(&config_key_str)
64			.expect("failed to decode ConfigKey from storage, unknown key");
65
66		Some(Self {
67			key,
68		})
69	}
70}