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 prefix = KeySerializer::with_capacity(9);
41		prefix.extend_u8(Self::KIND as u8).extend_u64(policy);
42		EncodedKeyRange::prefix(prefix.to_encoded_key().as_slice())
43	}
44}
45
46impl EncodableKey for PolicyOpKey {
47	const KIND: KeyKind = KeyKind::PolicyOp;
48
49	fn encode(&self) -> EncodedKey {
50		let mut serializer = KeySerializer::with_capacity(17);
51		serializer.extend_u8(Self::KIND as u8).extend_u64(self.policy).extend_u64(self.op_index);
52		serializer.to_encoded_key()
53	}
54
55	fn decode(key: &EncodedKey) -> Option<Self> {
56		let mut de = KeyDeserializer::from_bytes(key.as_slice());
57		let kind: KeyKind = de.read_u8().ok()?.try_into().ok()?;
58		if kind != Self::KIND {
59			return None;
60		}
61		let policy = de.read_u64().ok()?;
62		let op_index = de.read_u64().ok()?;
63		Some(Self {
64			policy,
65			op_index,
66		})
67	}
68}
69
70#[cfg(test)]
71mod tests {
72	use std::ops::RangeBounds;
73
74	use super::*;
75
76	#[test]
77	fn policy_scan_holds_every_op_index_of_that_policy() {
78		// A fixed 0xFF-padded end bound only covers suffixes of exactly its own width.
79		let range = PolicyOpKey::policy_scan(7);
80
81		for op_index in [0u64, 1, 2, u64::MAX] {
82			let key = PolicyOpKey::encoded(7, op_index);
83			assert!(range.contains(&key), "op index {op_index} must fall inside the policy scan");
84		}
85	}
86
87	#[test]
88	fn policy_scan_excludes_a_neighbouring_policy() {
89		// The scan must not widen into the next policy when the bound is carry-incremented.
90		let range = PolicyOpKey::policy_scan(7);
91
92		assert!(!range.contains(&PolicyOpKey::encoded(6, 1)));
93		assert!(!range.contains(&PolicyOpKey::encoded(8, 1)));
94	}
95}