Skip to main content

reifydb_type/
storage.rs

1// SPDX-License-Identifier: MIT
2// Copyright (c) 2025 ReifyDB
3
4use std::ops::Deref;
5
6use crate::util::{bitvec::BitVec, cowvec::CowVec};
7
8/// Trait for vector-like storage of column values.
9pub trait DataVec<T: Clone>: Deref<Target = [T]> + Clone {
10	/// Create a new empty vec with given capacity, using the same allocator.
11	fn spawn(&self, capacity: usize) -> Self;
12	fn push(&mut self, value: T);
13	fn clear(&mut self);
14	fn len(&self) -> usize;
15	fn is_empty(&self) -> bool {
16		self.len() == 0
17	}
18	fn as_slice(&self) -> &[T];
19	fn get(&self, idx: usize) -> Option<&T>;
20	fn extend_from_slice(&mut self, other: &[T]);
21	fn extend_iter(&mut self, iter: impl Iterator<Item = T>);
22	fn capacity(&self) -> usize;
23	fn take(&self, n: usize) -> Self {
24		let len = n.min(self.len());
25		let mut new = self.spawn(len);
26		new.extend_from_slice(&self.as_slice()[..len]);
27		new
28	}
29}
30
31/// Trait for bitvec-like storage (null masks and boolean data).
32pub trait DataBitVec: Clone {
33	fn spawn(&self, capacity: usize) -> Self;
34	fn push(&mut self, bit: bool);
35	fn get(&self, idx: usize) -> bool;
36	fn set(&mut self, idx: usize, value: bool);
37	fn len(&self) -> usize;
38	fn is_empty(&self) -> bool {
39		self.len() == 0
40	}
41	fn clear(&mut self);
42	fn extend_from(&mut self, other: &Self);
43	fn count_ones(&self) -> usize;
44	fn count_zeros(&self) -> usize {
45		self.len() - self.count_ones()
46	}
47	fn iter(&self) -> impl Iterator<Item = bool> + '_;
48	fn capacity(&self) -> usize;
49	fn take(&self, n: usize) -> Self {
50		let len = n.min(self.len());
51		let mut new = self.spawn(len);
52		for i in 0..len {
53			new.push(self.get(i));
54		}
55		new
56	}
57}
58
59/// Trait abstracting over storage backends.
60pub trait Storage: Clone {
61	type Vec<T: Clone + PartialEq + 'static>: DataVec<T> + PartialEq;
62	type BitVec: DataBitVec + PartialEq;
63}
64
65/// Default storage backend using Arc-backed copy-on-write.
66#[derive(Clone, Debug)]
67pub struct Cow;
68
69impl Storage for Cow {
70	type Vec<T: Clone + PartialEq + 'static> = CowVec<T>;
71	type BitVec = BitVec;
72}