Skip to main content

reifydb_type/value/container/
dictionary.rs

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