Skip to main content

reifydb_core/key/
policy_op.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 ReifyDB
3
4use reifydb_codec::key::{
5	deserializer::KeyDeserializer,
6	encoded::{EncodedKey, EncodedKeyRange},
7	serializer::KeySerializer,
8};
9
10use super::{EncodableKey, KeyKind};
11use crate::interface::catalog::policy::PolicyId;
12
13#[derive(Debug, Clone, PartialEq)]
14pub struct PolicyOpKey {
15	pub policy: PolicyId,
16	pub op_index: u64,
17}
18
19impl PolicyOpKey {
20	pub fn new(policy: PolicyId, op_index: u64) -> Self {
21		Self {
22			policy,
23			op_index,
24		}
25	}
26
27	pub fn encoded(policy: PolicyId, op_index: u64) -> EncodedKey {
28		Self::new(policy, op_index).encode()
29	}
30
31	pub fn full_scan() -> EncodedKeyRange {
32		let mut start = KeySerializer::with_capacity(1);
33		start.extend_u8(Self::KIND as u8);
34		let mut end = KeySerializer::with_capacity(1);
35		end.extend_u8(Self::KIND as u8 - 1);
36		EncodedKeyRange::start_end(Some(start.to_encoded_key()), Some(end.to_encoded_key()))
37	}
38
39	pub fn policy_scan(policy: PolicyId) -> EncodedKeyRange {
40		let mut start = KeySerializer::with_capacity(9);
41		start.extend_u8(Self::KIND as u8).extend_u64(policy);
42		let mut end = KeySerializer::with_capacity(17);
43		end.extend_u8(Self::KIND as u8).extend_u64(policy);
44		let start_key = start.to_encoded_key();
45		let mut end_bytes = end.to_encoded_key().to_vec();
46
47		end_bytes.extend_from_slice(&[0xFF; 8]);
48		EncodedKeyRange::start_end(Some(start_key), Some(EncodedKey::new(end_bytes)))
49	}
50}
51
52impl EncodableKey for PolicyOpKey {
53	const KIND: KeyKind = KeyKind::PolicyOp;
54
55	fn encode(&self) -> EncodedKey {
56		let mut serializer = KeySerializer::with_capacity(17);
57		serializer.extend_u8(Self::KIND as u8).extend_u64(self.policy).extend_u64(self.op_index);
58		serializer.to_encoded_key()
59	}
60
61	fn decode(key: &EncodedKey) -> Option<Self> {
62		let mut de = KeyDeserializer::from_bytes(key.as_slice());
63		let kind: KeyKind = de.read_u8().ok()?.try_into().ok()?;
64		if kind != Self::KIND {
65			return None;
66		}
67		let policy = de.read_u64().ok()?;
68		let op_index = de.read_u64().ok()?;
69		Some(Self {
70			policy,
71			op_index,
72		})
73	}
74}