1use std::collections::BTreeMap;
2use std::hash::Hash;
3use std::ops::{Index, IndexMut};
4
5use crate::{Entity, IdentifiableEntity, Record, Value, VersionedEntity};
6
7#[derive(Debug, Clone, PartialEq)]
8pub struct SmartList<T> {
9 pub data: Vec<T>,
10 pub total_count: Option<u64>,
11 pub aggregations: Record,
12 pub summary: Record,
13 pub facets: BTreeMap<String, SmartList<Record>>,
14}
15
16impl<T> SmartList<T> {
17 pub fn empty() -> Self {
18 Self::new(Vec::new())
19 }
20
21 pub fn new(data: Vec<T>) -> Self {
22 Self {
23 data,
24 total_count: None,
25 aggregations: Record::new(),
26 summary: Record::new(),
27 facets: BTreeMap::new(),
28 }
29 }
30
31 pub fn with_total_count(mut self, total_count: u64) -> Self {
32 self.total_count = Some(total_count);
33 self
34 }
35
36 pub fn with_aggregation(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
37 self.aggregations.insert(key.into(), value.into());
38 self
39 }
40
41 pub fn with_summary(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
42 self.summary.insert(key.into(), value.into());
43 self
44 }
45
46 pub fn with_facet(mut self, key: impl Into<String>, facet: SmartList<Record>) -> Self {
47 self.facets.insert(key.into(), facet);
48 self
49 }
50
51 pub fn add_facet(&mut self, key: impl Into<String>, facet: SmartList<Record>) {
52 self.facets.insert(key.into(), facet);
53 }
54
55 pub fn facets(&self) -> &BTreeMap<String, SmartList<Record>> {
56 &self.facets
57 }
58
59 pub fn facets_mut(&mut self) -> &mut BTreeMap<String, SmartList<Record>> {
60 &mut self.facets
61 }
62
63 pub fn facet(&self, key: &str) -> Option<&SmartList<Record>> {
64 self.facets.get(key)
65 }
66
67 pub fn facet_mut(&mut self, key: &str) -> Option<&mut SmartList<Record>> {
68 self.facets.get_mut(key)
69 }
70
71 pub fn remove_facet(&mut self, key: &str) -> Option<SmartList<Record>> {
72 self.facets.remove(key)
73 }
74
75 pub fn take_facets(&mut self) -> BTreeMap<String, SmartList<Record>> {
76 std::mem::take(&mut self.facets)
77 }
78
79 pub fn push(&mut self, value: T) {
80 self.data.push(value);
81 }
82
83 pub fn extend(&mut self, values: impl IntoIterator<Item = T>) {
84 self.data.extend(values);
85 }
86
87 pub fn set(&mut self, index: usize, value: T) -> Option<T> {
88 if index >= self.data.len() {
89 return None;
90 }
91 Some(std::mem::replace(&mut self.data[index], value))
92 }
93
94 pub fn get(&self, index: usize) -> Option<&T> {
95 self.data.get(index)
96 }
97
98 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
99 self.data.get_mut(index)
100 }
101
102 pub fn last(&self) -> Option<&T> {
103 self.data.last()
104 }
105
106 pub fn len(&self) -> usize {
107 self.data.len()
108 }
109
110 pub fn is_empty(&self) -> bool {
111 self.data.is_empty()
112 }
113
114 pub fn first(&self) -> Option<&T> {
115 self.data.first()
116 }
117
118 pub fn iter(&self) -> std::slice::Iter<'_, T> {
119 self.data.iter()
120 }
121
122 pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, T> {
123 self.data.iter_mut()
124 }
125
126 pub fn as_slice(&self) -> &[T] {
127 &self.data
128 }
129
130 pub fn as_mut_slice(&mut self) -> &mut [T] {
131 &mut self.data
132 }
133
134 pub fn retain(&mut self, filter: impl FnMut(&T) -> bool) {
135 self.data.retain(filter);
136 }
137
138 pub fn total_count_or_len(&self) -> u64 {
139 self.total_count.unwrap_or(self.data.len() as u64)
140 }
141
142 pub fn aggregation(&self, key: &str) -> Option<&Value> {
143 self.aggregations.get(key)
144 }
145
146 pub fn summary(&self, key: &str) -> Option<&Value> {
147 self.summary.get(key)
148 }
149
150 pub fn aggregation_json(&self) -> serde_json::Value {
151 crate::record_to_json_value(&self.aggregations)
152 }
153
154 pub fn summary_json(&self) -> serde_json::Value {
155 crate::record_to_json_value(&self.summary)
156 }
157
158 pub fn into_vec(self) -> Vec<T> {
159 self.data
160 }
161
162 pub fn map<U>(self, mapper: impl FnMut(T) -> U) -> SmartList<U> {
163 SmartList {
164 data: self.data.into_iter().map(mapper).collect(),
165 total_count: self.total_count,
166 aggregations: self.aggregations,
167 summary: self.summary,
168 facets: self.facets,
169 }
170 }
171
172 pub fn to_list<U>(&self, mapper: impl FnMut(&T) -> U) -> Vec<U> {
173 self.data.iter().map(mapper).collect()
174 }
175
176 pub fn to_set<U>(&self, mapper: impl FnMut(&T) -> U) -> std::collections::BTreeSet<U>
177 where
178 U: Ord,
179 {
180 self.data.iter().map(mapper).collect()
181 }
182
183 pub fn identity_map<K>(&self, mut key: impl FnMut(&T) -> K) -> BTreeMap<K, T>
184 where
185 K: Ord,
186 T: Clone,
187 {
188 self.data
189 .iter()
190 .map(|item| (key(item), item.clone()))
191 .collect()
192 }
193
194 pub fn group_by<K>(&self, mut key: impl FnMut(&T) -> K) -> BTreeMap<K, Vec<T>>
195 where
196 K: Ord,
197 T: Clone,
198 {
199 let mut groups = BTreeMap::new();
200 for item in &self.data {
201 groups
202 .entry(key(item))
203 .or_insert_with(Vec::new)
204 .push(item.clone());
205 }
206 groups
207 }
208
209 pub fn merge_by<K>(
210 &mut self,
211 incoming: impl IntoIterator<Item = T>,
212 mut key: impl FnMut(&T) -> K,
213 ) where
214 K: Eq + Hash,
215 {
216 let mut positions = self
217 .data
218 .iter()
219 .enumerate()
220 .map(|(index, item)| (key(item), index))
221 .collect::<std::collections::HashMap<_, _>>();
222 for item in incoming {
223 let item_key = key(&item);
224 if let Some(index) = positions.get(&item_key).copied() {
225 self.data[index] = item;
226 } else {
227 positions.insert(item_key, self.data.len());
228 self.data.push(item);
229 }
230 }
231 }
232
233 pub fn into_records(self) -> SmartList<Record>
234 where
235 T: Entity,
236 {
237 SmartList {
238 data: self.data.into_iter().map(Entity::into_record).collect(),
239 total_count: self.total_count,
240 aggregations: self.aggregations,
241 summary: self.summary,
242 facets: self.facets,
243 }
244 }
245}
246
247impl<T> SmartList<T>
248where
249 T: IdentifiableEntity,
250{
251 pub fn ids(&self) -> Vec<Value> {
252 self.data.iter().map(IdentifiableEntity::id_value).collect()
253 }
254
255 pub fn map_by_id(&self) -> BTreeMap<String, T>
256 where
257 T: Clone,
258 {
259 self.data
260 .iter()
261 .map(|item| (id_key(&item.id_value()), item.clone()))
262 .collect()
263 }
264}
265
266impl<T> SmartList<T>
267where
268 T: VersionedEntity,
269{
270 pub fn versions(&self) -> Vec<i64> {
271 self.data.iter().map(VersionedEntity::version).collect()
272 }
273}
274
275impl<T> From<Vec<T>> for SmartList<T> {
276 fn from(data: Vec<T>) -> Self {
277 Self::new(data)
278 }
279}
280
281impl<T> Default for SmartList<T> {
282 fn default() -> Self {
283 Self::new(Vec::new())
284 }
285}
286
287impl<T> IntoIterator for SmartList<T> {
288 type Item = T;
289 type IntoIter = std::vec::IntoIter<T>;
290
291 fn into_iter(self) -> Self::IntoIter {
292 self.data.into_iter()
293 }
294}
295
296impl<'a, T> IntoIterator for &'a SmartList<T> {
297 type Item = &'a T;
298 type IntoIter = std::slice::Iter<'a, T>;
299
300 fn into_iter(self) -> Self::IntoIter {
301 self.data.iter()
302 }
303}
304
305impl<'a, T> IntoIterator for &'a mut SmartList<T> {
306 type Item = &'a mut T;
307 type IntoIter = std::slice::IterMut<'a, T>;
308
309 fn into_iter(self) -> Self::IntoIter {
310 self.data.iter_mut()
311 }
312}
313
314impl<T> FromIterator<T> for SmartList<T> {
315 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
316 Self::new(iter.into_iter().collect())
317 }
318}
319
320impl<T> Extend<T> for SmartList<T> {
321 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
322 self.data.extend(iter);
323 }
324}
325
326impl<T> Index<usize> for SmartList<T> {
327 type Output = T;
328
329 fn index(&self, index: usize) -> &Self::Output {
330 &self.data[index]
331 }
332}
333
334impl<T> IndexMut<usize> for SmartList<T> {
335 fn index_mut(&mut self, index: usize) -> &mut Self::Output {
336 &mut self.data[index]
337 }
338}
339
340fn id_key(value: &Value) -> String {
341 match value {
342 Value::Null => "null".to_owned(),
343 Value::Bool(value) => format!("b:{value}"),
344 Value::I64(value) => format!("i:{value}"),
345 Value::U64(value) => format!("u:{value}"),
346 Value::F64(value) => format!("f:{value}"),
347 Value::Decimal(value) => format!("d:{value}"),
348 Value::Text(value) => format!("t:{value}"),
349 Value::Json(value) => format!("j:{value}"),
350 Value::Date(value) => format!("d:{value}"),
351 Value::Timestamp(value) => format!("ts:{}", value.to_rfc3339()),
352 Value::Object(_) => "object".to_owned(),
353 Value::List(_) => "list".to_owned(),
354 }
355}