vecdb/traits/
collectable.rs1use crate::{AnyIterableVec, i64_to_usize};
2
3use super::{AnyVec, StoredIndex, StoredRaw};
4
5pub trait CollectableVec<I, T>: AnyIterableVec<I, T>
6where
7 Self: Clone,
8 I: StoredIndex,
9 T: StoredRaw,
10{
11 fn iter_range(&self, from: Option<usize>, to: Option<usize>) -> impl Iterator<Item = T> {
12 let len = self.len();
13 let from = from.unwrap_or_default();
14 let to = to.map_or(len, |to| to.min(len));
15 let mut iter = self.iter();
16 iter.set_end_to(to);
17 iter.skip(from).take(to - from)
18 }
19
20 fn iter_signed_range(&self, from: Option<i64>, to: Option<i64>) -> impl Iterator<Item = T> {
21 let from = from.map(|i| self.i64_to_usize(i));
22 let to = to.map(|i| self.i64_to_usize(i));
23 self.iter_range(from, to)
24 }
25
26 fn collect(&self) -> Vec<T> {
27 self.collect_range(None, None)
28 }
29
30 fn collect_range(&self, from: Option<usize>, to: Option<usize>) -> Vec<T> {
31 self.iter_range(from, to).collect::<Vec<_>>()
32 }
33
34 fn collect_signed_range(&self, from: Option<i64>, to: Option<i64>) -> Vec<T> {
35 let from = from.map(|i| self.i64_to_usize(i));
36 let to = to.map(|i| self.i64_to_usize(i));
37 self.collect_range(from, to)
38 }
39
40 #[inline]
41 fn collect_range_json_bytes(&self, from: Option<usize>, to: Option<usize>) -> Vec<u8> {
42 let vec = self.iter_range(from, to).collect::<Vec<_>>();
43 let mut bytes = Vec::with_capacity(self.len() * 21);
44 sonic_rs::to_writer(&mut bytes, &vec).unwrap();
45 bytes
46 }
47
48 #[inline]
49 fn collect_range_string(&self, from: Option<usize>, to: Option<usize>) -> Vec<String> {
50 self.iter_range(from, to).map(|v| v.to_string()).collect()
51 }
52
53 #[inline]
54 fn i64_to_usize_(i: i64, len: usize) -> usize {
55 if i >= 0 {
56 (i as usize).min(len)
57 } else {
58 let v = len as i64 + i;
59 if v < 0 { 0 } else { v as usize }
60 }
61 }
62}
63
64impl<I, T, V> CollectableVec<I, T> for V
65where
66 V: AnyVec + AnyIterableVec<I, T> + Clone,
67 I: StoredIndex,
68 T: StoredRaw + 'static,
69{
70}
71
72pub trait AnyCollectableVec: AnyVec {
73 fn collect_range_json_bytes(&self, from: Option<usize>, to: Option<usize>) -> Vec<u8>;
74 fn collect_range_string(&self, from: Option<usize>, to: Option<usize>) -> Vec<String>;
75
76 fn range_count(&self, from: Option<i64>, to: Option<i64>) -> usize {
77 let len = self.len();
78 let from = from.map(|i| i64_to_usize(i, len));
79 let to = to.map(|i| i64_to_usize(i, len));
80 (from.unwrap_or_default()..to.unwrap_or(len)).count()
81 }
82
83 fn range_weight(&self, from: Option<i64>, to: Option<i64>) -> usize {
84 self.range_count(from, to) * self.value_type_to_size_of()
85 }
86}