Skip to main content

reifydb_core/key/
index.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 ReifyDB
3
4use std::collections::Bound;
5
6use reifydb_codec::key::{
7	deserializer::KeyDeserializer,
8	encoded::{EncodedKey, EncodedKeyRange},
9	serializer::KeySerializer,
10};
11
12use super::{EncodableKey, EncodableKeyRange, KeyKind};
13use crate::{
14	interface::catalog::{
15		id::{IndexId, PrimaryKeyId},
16		shape::ShapeId,
17	},
18	key::catalog::{KeyDeserializerCatalogExt, KeySerializerCatalogExt},
19};
20
21#[derive(Debug, Clone, PartialEq)]
22pub struct IndexKey {
23	pub shape: ShapeId,
24	pub index: IndexId,
25}
26
27impl EncodableKey for IndexKey {
28	const KIND: KeyKind = KeyKind::Index;
29
30	fn encode(&self) -> EncodedKey {
31		let mut serializer = KeySerializer::with_capacity(18);
32		serializer.extend_u8(Self::KIND as u8).extend_shape_id(self.shape).extend_u64(self.index);
33		serializer.to_encoded_key()
34	}
35
36	fn decode(key: &EncodedKey) -> Option<Self> {
37		let mut de = KeyDeserializer::from_bytes(key.as_slice());
38
39		let kind: KeyKind = de.read_u8().ok()?.try_into().ok()?;
40		if kind != Self::KIND {
41			return None;
42		}
43
44		let shape = de.read_shape_id().ok()?;
45		let index_value = de.read_u64().ok()?;
46
47		Some(Self {
48			shape,
49			index: IndexId::Primary(PrimaryKeyId(index_value)),
50		})
51	}
52}
53
54#[derive(Debug, Clone, PartialEq)]
55pub struct ShapeIndexKeyRange {
56	pub shape: ShapeId,
57}
58
59impl ShapeIndexKeyRange {
60	fn decode_key(key: &EncodedKey) -> Option<Self> {
61		let mut de = KeyDeserializer::from_bytes(key.as_slice());
62
63		let kind: KeyKind = de.read_u8().ok()?.try_into().ok()?;
64		if kind != Self::KIND {
65			return None;
66		}
67
68		let shape = de.read_shape_id().ok()?;
69
70		Some(ShapeIndexKeyRange {
71			shape,
72		})
73	}
74}
75
76impl EncodableKeyRange for ShapeIndexKeyRange {
77	const KIND: KeyKind = KeyKind::Index;
78
79	fn start(&self) -> Option<EncodedKey> {
80		let mut serializer = KeySerializer::with_capacity(10);
81		serializer.extend_u8(Self::KIND as u8).extend_shape_id(self.shape);
82		Some(serializer.to_encoded_key())
83	}
84
85	fn end(&self) -> Option<EncodedKey> {
86		let mut serializer = KeySerializer::with_capacity(10);
87		serializer.extend_u8(Self::KIND as u8).extend_shape_id(self.shape.prev());
88		Some(serializer.to_encoded_key())
89	}
90
91	fn decode(range: &EncodedKeyRange) -> (Option<Self>, Option<Self>)
92	where
93		Self: Sized,
94	{
95		let start_key = match &range.start {
96			Bound::Included(key) | Bound::Excluded(key) => Self::decode_key(key),
97			Bound::Unbounded => None,
98		};
99
100		let end_key = match &range.end {
101			Bound::Included(key) | Bound::Excluded(key) => Self::decode_key(key),
102			Bound::Unbounded => None,
103		};
104
105		(start_key, end_key)
106	}
107}
108
109impl IndexKey {
110	pub fn encoded(shape: impl Into<ShapeId>, index: impl Into<IndexId>) -> EncodedKey {
111		Self {
112			shape: shape.into(),
113			index: index.into(),
114		}
115		.encode()
116	}
117
118	pub fn full_scan(shape: impl Into<ShapeId>) -> EncodedKeyRange {
119		let shape = shape.into();
120		EncodedKeyRange::start_end(Some(Self::shape_start(shape)), Some(Self::shape_end(shape)))
121	}
122
123	pub fn shape_start(shape: impl Into<ShapeId>) -> EncodedKey {
124		let shape = shape.into();
125		let mut serializer = KeySerializer::with_capacity(10);
126		serializer.extend_u8(Self::KIND as u8).extend_shape_id(shape);
127		serializer.to_encoded_key()
128	}
129
130	pub fn shape_end(shape: impl Into<ShapeId>) -> EncodedKey {
131		let shape = shape.into();
132		let mut serializer = KeySerializer::with_capacity(10);
133		serializer.extend_u8(Self::KIND as u8).extend_shape_id(shape.prev());
134		serializer.to_encoded_key()
135	}
136}
137
138#[cfg(test)]
139pub mod tests {
140	use super::{EncodableKey, IndexKey};
141	use crate::interface::catalog::{id::IndexId, shape::ShapeId};
142
143	#[test]
144	fn test_encode_decode() {
145		let key = IndexKey {
146			shape: ShapeId::table(0xABCD),
147			index: IndexId::primary(0x123456789ABCDEF0u64),
148		};
149		let encoded = key.encode();
150
151		let expected: Vec<u8> =
152			vec![0xF3, 0x01, 0x3F, 0x54, 0x32, 0x00, 0xED, 0xCB, 0xA9, 0x87, 0x65, 0x43, 0x21, 0x0F];
153
154		assert_eq!(encoded.as_slice(), expected);
155
156		let key = IndexKey::decode(&encoded).unwrap();
157		assert_eq!(key.shape, 0xABCD);
158		assert_eq!(key.index, 0x123456789ABCDEF0);
159	}
160
161	#[test]
162	fn test_order_preserving() {
163		let key1 = IndexKey {
164			shape: ShapeId::table(1),
165			index: IndexId::primary(100),
166		};
167		let key2 = IndexKey {
168			shape: ShapeId::table(1),
169			index: IndexId::primary(200),
170		};
171		let key3 = IndexKey {
172			shape: ShapeId::table(2),
173			index: IndexId::primary(50),
174		};
175
176		let encoded1 = key1.encode();
177		let encoded2 = key2.encode();
178		let encoded3 = key3.encode();
179
180		assert!(encoded3 < encoded2, "ordering not preserved");
181		assert!(encoded2 < encoded1, "ordering not preserved");
182	}
183}