Skip to main content

reifydb_value/value/container/
uuid.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::{Value, is::IsUuid},
16};
17
18pub struct UuidContainer<T>
19where
20	T: IsUuid,
21{
22	data: Vec<T>,
23}
24
25impl<T: IsUuid> Clone for UuidContainer<T> {
26	fn clone(&self) -> Self {
27		Self {
28			data: self.data.clone(),
29		}
30	}
31}
32
33impl<T: IsUuid + Debug> Debug for UuidContainer<T> {
34	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35		f.debug_struct("UuidContainer").field("data", &self.data).finish()
36	}
37}
38
39impl<T: IsUuid> PartialEq for UuidContainer<T> {
40	fn eq(&self, other: &Self) -> bool {
41		self.data == other.data
42	}
43}
44
45impl<T: IsUuid + Serialize> Serialize for UuidContainer<T> {
46	fn serialize<Ser: Serializer>(&self, serializer: Ser) -> StdResult<Ser::Ok, Ser::Error> {
47		#[derive(Serialize)]
48		struct Helper<'a, T: Clone + PartialEq + Serialize> {
49			data: &'a Vec<T>,
50		}
51		Helper {
52			data: &self.data,
53		}
54		.serialize(serializer)
55	}
56}
57
58impl<'de, T: IsUuid + Deserialize<'de>> Deserialize<'de> for UuidContainer<T> {
59	fn deserialize<D: Deserializer<'de>>(deserializer: D) -> StdResult<Self, D::Error> {
60		#[derive(Deserialize)]
61		struct Helper<T: Clone + PartialEq> {
62			data: Vec<T>,
63		}
64		let h = Helper::deserialize(deserializer)?;
65		Ok(UuidContainer {
66			data: h.data,
67		})
68	}
69}
70
71impl<T: IsUuid> Deref for UuidContainer<T> {
72	type Target = [T];
73
74	fn deref(&self) -> &Self::Target {
75		self.data.as_slice()
76	}
77}
78
79impl<T> UuidContainer<T>
80where
81	T: IsUuid + Clone + Debug + Default,
82{
83	pub fn new(data: Vec<T>) -> Self {
84		Self {
85			data,
86		}
87	}
88
89	pub fn with_capacity(capacity: usize) -> Self {
90		Self {
91			data: Vec::with_capacity(capacity),
92		}
93	}
94
95	pub fn from_vec(data: Vec<T>) -> Self {
96		Self {
97			data,
98		}
99	}
100}
101
102impl<T> UuidContainer<T>
103where
104	T: IsUuid + Clone + Debug + Default,
105{
106	pub fn from_parts(data: Vec<T>) -> Self {
107		Self {
108			data,
109		}
110	}
111
112	pub fn len(&self) -> usize {
113		self.data.len()
114	}
115
116	pub fn capacity(&self) -> usize {
117		self.data.capacity()
118	}
119
120	pub fn heap_size(&self) -> usize {
121		self.capacity() * size_of::<T>()
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: T) {
133		self.data.push(value);
134	}
135
136	pub fn push_default(&mut self) {
137		self.data.push(T::default());
138	}
139
140	pub fn get(&self, index: usize) -> Option<&T> {
141		if index < self.len() {
142			self.data.get(index)
143		} else {
144			None
145		}
146	}
147
148	pub fn is_defined(&self, idx: usize) -> bool {
149		idx < self.len()
150	}
151
152	pub fn data(&self) -> &Vec<T> {
153		&self.data
154	}
155
156	pub fn data_mut(&mut self) -> &mut Vec<T> {
157		&mut self.data
158	}
159
160	pub fn as_string(&self, index: usize) -> String {
161		if index < self.len() {
162			self.data[index].to_string()
163		} else {
164			"none".to_string()
165		}
166	}
167
168	pub fn get_value(&self, index: usize) -> Value {
169		if index < self.len() {
170			self.data[index].to_value()
171		} else {
172			Value::none()
173		}
174	}
175
176	pub fn extend(&mut self, other: &Self) -> Result<()> {
177		self.data.extend(other.data.iter().cloned());
178		Ok(())
179	}
180
181	pub fn iter(&self) -> impl Iterator<Item = Option<T>> + '_
182	where
183		T: Copy,
184	{
185		self.data.iter().map(|&v| Some(v))
186	}
187
188	pub fn slice(&self, start: usize, end: usize) -> Self {
189		let count = (end - start).min(self.len().saturating_sub(start));
190		let mut new_data = Vec::with_capacity(count);
191		for i in start..(start + count) {
192			new_data.push(self.data[i].clone());
193		}
194		Self {
195			data: new_data,
196		}
197	}
198
199	pub fn filter(&mut self, mask: &BitVec) {
200		let mut new_data = Vec::with_capacity(mask.count_ones());
201
202		for (i, keep) in mask.iter().enumerate() {
203			if keep && i < self.len() {
204				new_data.push(self.data[i].clone());
205			}
206		}
207
208		self.data = new_data;
209	}
210
211	pub fn reorder(&mut self, indices: &[usize]) {
212		let mut new_data = Vec::with_capacity(indices.len());
213
214		for &idx in indices {
215			if idx < self.len() {
216				new_data.push(self.data[idx].clone());
217			} else {
218				new_data.push(T::default());
219			}
220		}
221
222		self.data = new_data;
223	}
224
225	pub fn take(&self, num: usize) -> Self {
226		Self {
227			data: self.data[..num.min(self.data.len())].to_vec(),
228		}
229	}
230}
231
232impl<T> Default for UuidContainer<T>
233where
234	T: IsUuid + Clone + Debug + Default,
235{
236	fn default() -> Self {
237		Self::with_capacity(0)
238	}
239}
240
241#[cfg(test)]
242pub mod tests {
243	use super::*;
244	use crate::{
245		clock::testing::{TestClock, TestRng},
246		value::uuid::{Uuid4, Uuid7},
247	};
248
249	fn test_clock_and_rng() -> (TestClock, TestClock, TestRng) {
250		let clock = TestClock::from_millis(1000);
251		(clock.clone(), clock, TestRng)
252	}
253
254	#[test]
255	fn test_uuid4_container() {
256		let uuid1 = Uuid4::generate();
257		let uuid2 = Uuid4::generate();
258		let uuids = vec![uuid1, uuid2];
259		let container = UuidContainer::from_vec(uuids.clone());
260
261		assert_eq!(container.len(), 2);
262		assert_eq!(container.get(0), Some(&uuids[0]));
263		assert_eq!(container.get(1), Some(&uuids[1]));
264
265		for i in 0..2 {
266			assert!(container.is_defined(i));
267		}
268	}
269
270	#[test]
271	fn test_uuid7_container() {
272		let (mock, clock, rng) = test_clock_and_rng();
273		let uuid1 = Uuid7::generate(&clock, &rng);
274		mock.advance_millis(1);
275		let uuid2 = Uuid7::generate(&clock, &rng);
276		let uuids = vec![uuid1, uuid2];
277		let container = UuidContainer::from_vec(uuids.clone());
278
279		assert_eq!(container.len(), 2);
280		assert_eq!(container.get(0), Some(&uuids[0]));
281		assert_eq!(container.get(1), Some(&uuids[1]));
282	}
283
284	#[test]
285	fn test_with_capacity() {
286		let container: UuidContainer<Uuid4> = UuidContainer::with_capacity(10);
287		assert_eq!(container.len(), 0);
288		assert!(container.is_empty());
289		assert!(container.capacity() >= 10);
290	}
291
292	#[test]
293	fn test_push_with_default() {
294		let mut container: UuidContainer<Uuid4> = UuidContainer::with_capacity(3);
295		let uuid1 = Uuid4::generate();
296		let uuid2 = Uuid4::generate();
297
298		container.push(uuid1);
299		container.push_default();
300		container.push(uuid2);
301
302		assert_eq!(container.len(), 3);
303		assert_eq!(container.get(0), Some(&uuid1));
304		assert_eq!(container.get(1), Some(&Uuid4::default())); // default
305		assert_eq!(container.get(2), Some(&uuid2));
306
307		assert!(container.is_defined(0));
308		assert!(container.is_defined(1));
309		assert!(container.is_defined(2));
310	}
311
312	#[test]
313	fn testault() {
314		let container: UuidContainer<Uuid4> = UuidContainer::default();
315		assert_eq!(container.len(), 0);
316		assert!(container.is_empty());
317	}
318}