Skip to main content

reifydb_core/key/
policy_op.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 PolicyOpKey {
13	pub policy: PolicyId,
14	pub op_index: u64,
15}
16
17impl PolicyOpKey {
18	pub fn new(policy: PolicyId, op_index: u64) -> Self {
19		Self {
20			policy,
21			op_index,
22		}
23	}
24
25	pub fn encoded(policy: PolicyId, op_index: u64) -> EncodedKey {
26		Self::new(policy, op_index).encode()
27	}
28
29	pub fn full_scan() -> EncodedKeyRange {
30		let mut start = KeySerializer::with_capacity(1);
31		start.extend_u8(Self::KIND as u8);
32		let mut end = KeySerializer::with_capacity(1);
33		end.extend_u8(Self::KIND as u8 - 1);
34		EncodedKeyRange::start_end(Some(start.to_encoded_key()), Some(end.to_encoded_key()))
35	}
36
37	pub fn policy_scan(policy: PolicyId) -> EncodedKeyRange {
38		let mut start = KeySerializer::with_capacity(9);
39		start.extend_u8(Self::KIND as u8).extend_u64(policy);
40		let mut end = KeySerializer::with_capacity(17);
41		end.extend_u8(Self::KIND as u8).extend_u64(policy);
42		let start_key = start.to_encoded_key();
43		let mut end_bytes = end.to_encoded_key().to_vec();
44
45		end_bytes.extend_from_slice(&[0xFF; 8]);
46		EncodedKeyRange::start_end(Some(start_key), Some(EncodedKey::new(end_bytes)))
47	}
48}
49
50impl EncodableKey for PolicyOpKey {
51	const KIND: KeyKind = KeyKind::PolicyOp;
52
53	fn encode(&self) -> EncodedKey {
54		let mut serializer = KeySerializer::with_capacity(17);
55		serializer.extend_u8(Self::KIND as u8).extend_u64(self.policy).extend_u64(self.op_index);
56		serializer.to_encoded_key()
57	}
58
59	fn decode(key: &EncodedKey) -> Option<Self> {
60		let mut de = KeyDeserializer::from_bytes(key.as_slice());
61		let kind: KeyKind = de.read_u8().ok()?.try_into().ok()?;
62		if kind != Self::KIND {
63			return None;
64		}
65		let policy = de.read_u64().ok()?;
66		let op_index = de.read_u64().ok()?;
67		Some(Self {
68			policy,
69			op_index,
70		})
71	}
72}