gistools/data_store/vector/
mod.rs1use super::U64;
2use alloc::{vec, vec::Vec};
6use s2json::Properties;
7use serde::{Serialize, de::DeserializeOwned};
8
9pub trait VectorStore<K: U64 = u64, V: Serialize + DeserializeOwned + Clone = Properties>:
11 Clone
12{
13 fn new(name: Option<&str>) -> Self;
15 fn len(&self) -> u64;
17 fn is_empty(&self) -> bool;
19 fn push(&mut self, id: K, value: V);
21 fn has(&self, key: K) -> bool;
23 fn get(&self, key: K) -> Option<&(K, V)>;
25 fn get_mut(&mut self, key: K) -> Option<&mut (K, V)>;
27 fn get_index(&self, index: u64) -> Option<&(K, V)>;
29 fn get_index_mut(&mut self, index: u64) -> Option<&mut (K, V)>;
31 fn sort(&mut self);
33 fn iter<'a>(&'a self) -> impl Iterator<Item = &'a (K, V)>
35 where
36 K: 'a,
37 V: 'a;
38 fn iter_mut<'a>(&'a mut self) -> impl Iterator<Item = &'a mut (K, V)>
40 where
41 K: 'a,
42 V: 'a;
43 fn cleanup(&mut self) {}
45}
46
47#[derive(Debug, Clone)]
49pub struct Vector<K: U64 = u64, V: Serialize + DeserializeOwned + Clone = Properties> {
50 store: Vec<(K, V)>,
51 sorted: bool,
52}
53impl<K: U64, V: Serialize + DeserializeOwned + Clone> VectorStore<K, V> for Vector<K, V> {
54 fn new(_name: Option<&str>) -> Self {
55 Self { store: vec![], sorted: false }
56 }
57 fn len(&self) -> u64 {
58 self.store.len() as u64
59 }
60 fn is_empty(&self) -> bool {
61 self.store.is_empty()
62 }
63 fn push(&mut self, id: K, value: V) {
64 self.store.push((id, value));
65 }
66 fn has(&self, key: K) -> bool {
67 assert!(self.sorted);
68 self.store.binary_search_by_key(&key, |(id, _)| *id).is_ok()
69 }
70 fn get(&self, key: K) -> Option<&(K, V)> {
71 assert!(self.sorted);
72 self.store.get(self.store.binary_search_by_key(&key, |(id, _)| *id).ok()?)
73 }
74 fn get_mut(&mut self, key: K) -> Option<&mut (K, V)> {
75 assert!(self.sorted);
76 let index = self.store.binary_search_by_key(&key, |(id, _)| *id).ok()?;
77 self.store.get_mut(index)
78 }
79 fn get_index(&self, index: u64) -> Option<&(K, V)> {
80 assert!(self.sorted);
81 self.store.get(index as usize)
82 }
83 fn get_index_mut(&mut self, index: u64) -> Option<&mut (K, V)> {
84 assert!(self.sorted);
85 self.store.get_mut(index as usize)
86 }
87 fn sort(&mut self) {
88 if self.sorted {
89 return;
90 }
91 self.sorted = true;
92 self.store.sort_by_key(|(id, _)| *id);
93 }
94 fn iter<'a>(&'a self) -> impl Iterator<Item = &'a (K, V)>
95 where
96 K: 'a,
97 V: 'a,
98 {
99 assert!(self.sorted);
100 self.store.iter()
101 }
102 fn iter_mut<'a>(&'a mut self) -> impl Iterator<Item = &'a mut (K, V)>
103 where
104 K: 'a,
105 V: 'a,
106 {
107 assert!(self.sorted);
108 self.store.iter_mut()
109 }
110 fn cleanup(&mut self) {
111 self.store.clear();
112 }
113}