vecdb/traits/
collectable.rs

1use crate::IterableVec;
2
3use super::{VecIndex, VecValue};
4
5/// Trait for vectors that can be collected into standard Rust collections with range support.
6pub trait CollectableVec<I, T>: IterableVec<I, T>
7where
8    Self: Clone,
9    I: VecIndex,
10    T: VecValue,
11{
12    /// Returns an iterator over the specified range.
13    fn iter_range(&self, from: Option<usize>, to: Option<usize>) -> impl Iterator<Item = T> {
14        let len = self.len();
15        let from = from.unwrap_or_default();
16        let to = to.map_or(len, |to| to.min(len));
17        let mut iter = self.iter();
18        iter.set_end_to(to);
19        iter.skip(from).take(to.saturating_sub(from))
20    }
21
22    /// Returns an iterator over the specified range using signed indices (supports negative indexing).
23    fn iter_signed_range(&self, from: Option<i64>, to: Option<i64>) -> impl Iterator<Item = T> {
24        let from = from.map(|i| self.i64_to_usize(i));
25        let to = to.map(|i| self.i64_to_usize(i));
26        self.iter_range(from, to)
27    }
28
29    /// Collects all values into a Vec.
30    fn collect(&self) -> Vec<T> {
31        self.collect_range(None, None)
32    }
33
34    /// Collects values in the specified range into a Vec.
35    fn collect_range(&self, from: Option<usize>, to: Option<usize>) -> Vec<T> {
36        self.iter_range(from, to).collect::<Vec<_>>()
37    }
38
39    /// Collects values in the specified range into a Vec using signed indices.
40    fn collect_signed_range(&self, from: Option<i64>, to: Option<i64>) -> Vec<T> {
41        let from = from.map(|i| self.i64_to_usize(i));
42        let to = to.map(|i| self.i64_to_usize(i));
43        self.collect_range(from, to)
44    }
45}
46
47impl<I, T, V> CollectableVec<I, T> for V
48where
49    V: IterableVec<I, T> + Clone,
50    I: VecIndex,
51    T: VecValue,
52{
53}