Skip to main content

reifydb_core/key/
policy.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2025 ReifyDB
3
4use super::{EncodableKey, KeyKind};
5use crate::{
6	encoded::key::{EncodedKey, EncodedKeyRange},
7	interface::catalog::policy::PolicyId,
8	util::encoding::keycode::{deserializer::KeyDeserializer, serializer::KeySerializer},
9};
10
11#[derive(Debug, Clone, PartialEq)]
12pub struct PolicyKey {
13	pub policy: PolicyId,
14}
15
16impl PolicyKey {
17	pub fn new(policy: PolicyId) -> Self {
18		Self {
19			policy,
20		}
21	}
22
23	pub fn encoded(policy: PolicyId) -> EncodedKey {
24		Self::new(policy).encode()
25	}
26
27	pub fn full_scan() -> EncodedKeyRange {
28		let mut start = KeySerializer::with_capacity(1);
29		start.extend_u8(Self::KIND as u8);
30		let mut end = KeySerializer::with_capacity(1);
31		end.extend_u8(Self::KIND as u8 - 1);
32		EncodedKeyRange::start_end(Some(start.to_encoded_key()), Some(end.to_encoded_key()))
33	}
34}
35
36impl EncodableKey for PolicyKey {
37	const KIND: KeyKind = KeyKind::Policy;
38
39	fn encode(&self) -> EncodedKey {
40		let mut serializer = KeySerializer::with_capacity(9);
41		serializer.extend_u8(Self::KIND as u8).extend_u64(self.policy);
42		serializer.to_encoded_key()
43	}
44
45	fn decode(key: &EncodedKey) -> Option<Self> {
46		let mut de = KeyDeserializer::from_bytes(key.as_slice());
47		let kind: KeyKind = de.read_u8().ok()?.try_into().ok()?;
48		if kind != Self::KIND {
49			return None;
50		}
51		let policy = de.read_u64().ok()?;
52		Some(Self {
53			policy,
54		})
55	}
56}