Skip to main content

reinhardt_query/value/
values.rs

1//! Values wrapper struct.
2
3use super::Value;
4
5/// Wrapper struct for collected query parameters.
6///
7/// This struct holds the values collected during SQL generation,
8/// which will be used as bind parameters when executing the query.
9///
10/// # Example
11///
12/// ```rust
13/// use reinhardt_query::{Value, Values};
14///
15/// let values = Values(vec![
16///     Value::Int(Some(42)),
17///     Value::String(Some(Box::new("hello".to_string()))),
18/// ]);
19///
20/// assert_eq!(values.len(), 2);
21/// ```
22#[derive(Clone, Debug, Default, PartialEq)]
23pub struct Values(pub Vec<Value>);
24
25impl Values {
26	/// Creates a new empty `Values` collection.
27	#[must_use]
28	pub fn new() -> Self {
29		Self(Vec::new())
30	}
31
32	/// Creates a `Values` collection with the specified capacity.
33	#[must_use]
34	pub fn with_capacity(capacity: usize) -> Self {
35		Self(Vec::with_capacity(capacity))
36	}
37
38	/// Returns the number of values in this collection.
39	#[must_use]
40	pub fn len(&self) -> usize {
41		self.0.len()
42	}
43
44	/// Returns `true` if this collection is empty.
45	#[must_use]
46	pub fn is_empty(&self) -> bool {
47		self.0.is_empty()
48	}
49
50	/// Adds a value to this collection and returns its 1-based index.
51	///
52	/// This is useful for generating placeholder indices like `$1`, `$2`, etc.
53	///
54	/// # Example
55	///
56	/// ```rust
57	/// use reinhardt_query::{Value, Values};
58	///
59	/// let mut values = Values::new();
60	/// let idx1 = values.push(Value::Int(Some(1)));
61	/// let idx2 = values.push(Value::Int(Some(2)));
62	///
63	/// assert_eq!(idx1, 1);
64	/// assert_eq!(idx2, 2);
65	/// ```
66	pub fn push(&mut self, value: Value) -> usize {
67		self.0.push(value);
68		self.0.len()
69	}
70
71	/// Returns an iterator over references to the values.
72	pub fn iter(&self) -> impl Iterator<Item = &Value> {
73		self.0.iter()
74	}
75
76	/// Consumes this collection and returns the underlying vector.
77	#[must_use]
78	pub fn into_inner(self) -> Vec<Value> {
79		self.0
80	}
81}
82
83impl IntoIterator for Values {
84	type Item = Value;
85	type IntoIter = std::vec::IntoIter<Value>;
86
87	fn into_iter(self) -> Self::IntoIter {
88		self.0.into_iter()
89	}
90}
91
92impl<'a> IntoIterator for &'a Values {
93	type Item = &'a Value;
94	type IntoIter = std::slice::Iter<'a, Value>;
95
96	fn into_iter(self) -> Self::IntoIter {
97		self.0.iter()
98	}
99}
100
101impl From<Vec<Value>> for Values {
102	fn from(values: Vec<Value>) -> Self {
103		Self(values)
104	}
105}
106
107impl From<Values> for Vec<Value> {
108	fn from(values: Values) -> Self {
109		values.0
110	}
111}
112
113impl std::ops::Deref for Values {
114	type Target = [Value];
115
116	fn deref(&self) -> &Self::Target {
117		&self.0
118	}
119}
120
121impl std::ops::Index<usize> for Values {
122	type Output = Value;
123
124	fn index(&self, index: usize) -> &Self::Output {
125		&self.0[index]
126	}
127}