Skip to main content

reifydb_value/value/container/
dictionary.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 ReifyDB
3
4use std::{
5	fmt::{self, Debug},
6	ops::Deref,
7	result::Result as StdResult,
8};
9
10use serde::{Deserialize, Deserializer, Serialize, Serializer};
11
12use crate::{
13	Result,
14	util::bitvec::BitVec,
15	value::{
16		Value,
17		dictionary::{DictionaryEntryId, DictionaryId},
18		value_type::ValueType,
19	},
20};
21
22pub struct DictionaryContainer {
23	data: Vec<DictionaryEntryId>,
24	dictionary_id: Option<DictionaryId>,
25}
26
27impl Clone for DictionaryContainer {
28	fn clone(&self) -> Self {
29		Self {
30			data: self.data.clone(),
31			dictionary_id: self.dictionary_id,
32		}
33	}
34}
35
36impl Debug for DictionaryContainer {
37	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38		f.debug_struct("DictionaryContainer")
39			.field("data", &self.data)
40			.field("dictionary_id", &self.dictionary_id)
41			.finish()
42	}
43}
44
45impl PartialEq for DictionaryContainer {
46	fn eq(&self, other: &Self) -> bool {
47		self.data == other.data && self.dictionary_id == other.dictionary_id
48	}
49}
50
51impl Serialize for DictionaryContainer {
52	fn serialize<Ser: Serializer>(&self, serializer: Ser) -> StdResult<Ser::Ok, Ser::Error> {
53		#[derive(Serialize)]
54		struct Helper<'a> {
55			data: &'a Vec<DictionaryEntryId>,
56			dictionary_id: Option<DictionaryId>,
57		}
58		Helper {
59			data: &self.data,
60			dictionary_id: self.dictionary_id,
61		}
62		.serialize(serializer)
63	}
64}
65
66impl<'de> Deserialize<'de> for DictionaryContainer {
67	fn deserialize<D: Deserializer<'de>>(deserializer: D) -> StdResult<Self, D::Error> {
68		#[derive(Deserialize)]
69		struct Helper {
70			data: Vec<DictionaryEntryId>,
71			dictionary_id: Option<DictionaryId>,
72		}
73		let h = Helper::deserialize(deserializer)?;
74		Ok(DictionaryContainer {
75			data: h.data,
76			dictionary_id: h.dictionary_id,
77		})
78	}
79}
80
81impl Deref for DictionaryContainer {
82	type Target = [DictionaryEntryId];
83
84	fn deref(&self) -> &Self::Target {
85		self.data.as_slice()
86	}
87}
88
89impl DictionaryContainer {
90	pub fn new(data: Vec<DictionaryEntryId>) -> Self {
91		Self {
92			data,
93			dictionary_id: None,
94		}
95	}
96
97	pub fn from_vec(data: Vec<DictionaryEntryId>) -> Self {
98		Self {
99			data,
100			dictionary_id: None,
101		}
102	}
103
104	pub fn with_capacity(capacity: usize) -> Self {
105		Self {
106			data: Vec::with_capacity(capacity),
107			dictionary_id: None,
108		}
109	}
110}
111
112impl DictionaryContainer {
113	pub fn from_parts(data: Vec<DictionaryEntryId>, dictionary_id: Option<DictionaryId>) -> Self {
114		Self {
115			data,
116			dictionary_id,
117		}
118	}
119
120	pub fn len(&self) -> usize {
121		self.data.len()
122	}
123
124	pub fn is_empty(&self) -> bool {
125		self.data.is_empty()
126	}
127
128	pub fn clear(&mut self) {
129		self.data.clear();
130	}
131
132	pub fn push(&mut self, value: impl Into<Option<DictionaryEntryId>>) {
133		let value = value.into();
134		match value {
135			Some(id) => {
136				self.data.push(id);
137			}
138			None => {
139				self.data.push(DictionaryEntryId::default());
140			}
141		}
142	}
143
144	pub fn push_default(&mut self) {
145		self.push(None);
146	}
147
148	pub fn get(&self, index: usize) -> Option<DictionaryEntryId> {
149		if index < self.len() {
150			Some(self.data[index])
151		} else {
152			None
153		}
154	}
155
156	pub fn iter(&self) -> impl Iterator<Item = Option<DictionaryEntryId>> + '_ {
157		self.data.iter().map(|&id| Some(id))
158	}
159
160	pub fn data(&self) -> &Vec<DictionaryEntryId> {
161		&self.data
162	}
163
164	pub fn data_mut(&mut self) -> &mut Vec<DictionaryEntryId> {
165		&mut self.data
166	}
167
168	pub fn dictionary_id(&self) -> Option<DictionaryId> {
169		self.dictionary_id
170	}
171
172	pub fn set_dictionary_id(&mut self, id: DictionaryId) {
173		self.dictionary_id = Some(id);
174	}
175
176	pub fn is_defined(&self, idx: usize) -> bool {
177		idx < self.len()
178	}
179
180	pub fn extend(&mut self, other: &Self) -> Result<()> {
181		self.data.extend_from_slice(other.data.as_slice());
182		Ok(())
183	}
184
185	pub fn get_value(&self, index: usize) -> Value {
186		self.get(index).map(Value::DictionaryId).unwrap_or(Value::none_of(ValueType::DictionaryId))
187	}
188
189	pub fn filter(&mut self, mask: &BitVec) {
190		let mut new_data = Vec::with_capacity(mask.count_ones());
191
192		for (i, keep) in mask.iter().enumerate() {
193			if keep && i < self.data.len() {
194				new_data.push(self.data[i]);
195			}
196		}
197
198		self.data = new_data;
199	}
200
201	pub fn reorder(&mut self, indices: &[usize]) {
202		let mut new_data = Vec::with_capacity(indices.len());
203
204		for &index in indices {
205			if index < self.data.len() {
206				new_data.push(self.data[index]);
207			} else {
208				new_data.push(DictionaryEntryId::default());
209			}
210		}
211
212		self.data = new_data;
213	}
214
215	pub fn take(&self, num: usize) -> Self {
216		Self {
217			data: self.data[..num.min(self.data.len())].to_vec(),
218			dictionary_id: self.dictionary_id,
219		}
220	}
221
222	pub fn slice(&self, start: usize, end: usize) -> Self {
223		let count = (end - start).min(self.len().saturating_sub(start));
224		let mut new_data = Vec::with_capacity(count);
225		for i in start..(start + count) {
226			new_data.push(self.data[i]);
227		}
228		Self {
229			data: new_data,
230			dictionary_id: self.dictionary_id,
231		}
232	}
233
234	pub fn as_string(&self, index: usize) -> String {
235		self.get(index).map(|id| id.to_string()).unwrap_or_else(|| "none".to_string())
236	}
237
238	pub fn capacity(&self) -> usize {
239		self.data.capacity()
240	}
241
242	pub fn heap_size(&self) -> usize {
243		self.capacity() * size_of::<DictionaryEntryId>()
244	}
245}
246
247impl From<Vec<DictionaryEntryId>> for DictionaryContainer {
248	fn from(data: Vec<DictionaryEntryId>) -> Self {
249		Self::from_vec(data)
250	}
251}
252
253impl FromIterator<Option<DictionaryEntryId>> for DictionaryContainer {
254	fn from_iter<T: IntoIterator<Item = Option<DictionaryEntryId>>>(iter: T) -> Self {
255		let mut container = Self::with_capacity(0);
256		for item in iter {
257			container.push(item);
258		}
259		container
260	}
261}