1use std::io::Cursor;
4
5use ahash::HashMap;
6use parking_lot::RwLock;
7use roaring::RoaringBitmap;
8use serde::{Deserialize, Serialize};
9
10use mentedb_core::error::{MenteError, MenteResult};
11use mentedb_core::types::MemoryId;
12
13pub struct BitmapIndex {
18 inner: RwLock<BitmapInner>,
19}
20
21struct BitmapInner {
22 tag_bitmaps: HashMap<String, RoaringBitmap>,
24 id_to_offset: HashMap<MemoryId, u32>,
26 offset_to_id: Vec<MemoryId>,
28}
29
30impl BitmapIndex {
31 pub fn new() -> Self {
33 Self {
34 inner: RwLock::new(BitmapInner {
35 tag_bitmaps: HashMap::default(),
36 id_to_offset: HashMap::default(),
37 offset_to_id: Vec::new(),
38 }),
39 }
40 }
41
42 fn ensure_offset(inner: &mut BitmapInner, id: MemoryId) -> u32 {
44 if let Some(&offset) = inner.id_to_offset.get(&id) {
45 return offset;
46 }
47 let offset = inner.offset_to_id.len() as u32;
48 inner.id_to_offset.insert(id, offset);
49 inner.offset_to_id.push(id);
50 offset
51 }
52
53 pub fn add_tag(&self, id: MemoryId, tag: &str) {
55 let mut inner = self.inner.write();
56 let offset = Self::ensure_offset(&mut inner, id);
57 inner
58 .tag_bitmaps
59 .entry(tag.to_string())
60 .or_default()
61 .insert(offset);
62 }
63
64 pub fn remove_tag(&self, id: MemoryId, tag: &str) {
66 let mut inner = self.inner.write();
67 if let Some(&offset) = inner.id_to_offset.get(&id)
68 && let Some(bm) = inner.tag_bitmaps.get_mut(tag)
69 {
70 bm.remove(offset);
71 }
72 }
73
74 pub fn query_tag(&self, tag: &str) -> Vec<MemoryId> {
76 let inner = self.inner.read();
77 match inner.tag_bitmaps.get(tag) {
78 Some(bm) => bm
79 .iter()
80 .filter_map(|offset| inner.offset_to_id.get(offset as usize).copied())
81 .collect(),
82 None => Vec::new(),
83 }
84 }
85
86 pub fn query_tags_and(&self, tags: &[&str]) -> Vec<MemoryId> {
88 let inner = self.inner.read();
89 if tags.is_empty() {
90 return Vec::new();
91 }
92
93 let mut result: Option<RoaringBitmap> = None;
94 for tag in tags {
95 match inner.tag_bitmaps.get(*tag) {
96 Some(bm) => {
97 result = Some(match result {
98 Some(r) => r & bm,
99 None => bm.clone(),
100 });
101 }
102 None => return Vec::new(),
103 }
104 }
105
106 match result {
107 Some(bm) => bm
108 .iter()
109 .filter_map(|offset| inner.offset_to_id.get(offset as usize).copied())
110 .collect(),
111 None => Vec::new(),
112 }
113 }
114
115 pub fn query_tags_or(&self, tags: &[&str]) -> Vec<MemoryId> {
117 let inner = self.inner.read();
118 if tags.is_empty() {
119 return Vec::new();
120 }
121
122 let mut result = RoaringBitmap::new();
123 for tag in tags {
124 if let Some(bm) = inner.tag_bitmaps.get(*tag) {
125 result |= bm;
126 }
127 }
128
129 result
130 .iter()
131 .filter_map(|offset| inner.offset_to_id.get(offset as usize).copied())
132 .collect()
133 }
134
135 pub fn remove_all(&self, id: MemoryId) {
137 let mut inner = self.inner.write();
138 if let Some(&offset) = inner.id_to_offset.get(&id) {
139 for bm in inner.tag_bitmaps.values_mut() {
140 bm.remove(offset);
141 }
142 }
143 }
144}
145
146#[derive(Serialize, Deserialize)]
148struct BitmapSnapshot {
149 tag_bitmaps: Vec<(String, Vec<u8>)>,
151 id_to_offset: Vec<(MemoryId, u32)>,
152 offset_to_id: Vec<MemoryId>,
153}
154
155impl BitmapIndex {
156 pub fn save(&self, path: &std::path::Path) -> MenteResult<()> {
158 let inner = self.inner.read();
159 let mut tag_bitmaps = Vec::new();
160 for (tag, bm) in &inner.tag_bitmaps {
161 let mut buf = Vec::new();
162 bm.serialize_into(&mut buf)
163 .map_err(|e| MenteError::Serialization(e.to_string()))?;
164 tag_bitmaps.push((tag.clone(), buf));
165 }
166 let snapshot = BitmapSnapshot {
167 tag_bitmaps,
168 id_to_offset: inner.id_to_offset.iter().map(|(&k, &v)| (k, v)).collect(),
169 offset_to_id: inner.offset_to_id.clone(),
170 };
171 let data =
172 serde_json::to_vec(&snapshot).map_err(|e| MenteError::Serialization(e.to_string()))?;
173 std::fs::write(path, data)?;
174 Ok(())
175 }
176
177 pub fn load(path: &std::path::Path) -> MenteResult<Self> {
179 let data = std::fs::read(path)?;
180 let snapshot: BitmapSnapshot =
181 serde_json::from_slice(&data).map_err(|e| MenteError::Serialization(e.to_string()))?;
182
183 let mut tag_bitmaps = HashMap::default();
184 for (tag, bytes) in snapshot.tag_bitmaps {
185 let bm = RoaringBitmap::deserialize_from(&mut Cursor::new(bytes))
186 .map_err(|e| MenteError::Serialization(e.to_string()))?;
187 tag_bitmaps.insert(tag, bm);
188 }
189
190 let mut id_to_offset = HashMap::default();
191 for (id, offset) in snapshot.id_to_offset {
192 id_to_offset.insert(id, offset);
193 }
194
195 Ok(Self {
196 inner: RwLock::new(BitmapInner {
197 tag_bitmaps,
198 id_to_offset,
199 offset_to_id: snapshot.offset_to_id,
200 }),
201 })
202 }
203}
204
205impl Default for BitmapIndex {
206 fn default() -> Self {
207 Self::new()
208 }
209}
210
211#[cfg(test)]
212mod tests {
213 use super::*;
214
215 #[test]
216 fn test_add_and_query_tag() {
217 let idx = BitmapIndex::new();
218 let id = MemoryId::new();
219 idx.add_tag(id, "important");
220
221 let results = idx.query_tag("important");
222 assert_eq!(results, vec![id]);
223 }
224
225 #[test]
226 fn test_query_empty_tag() {
227 let idx = BitmapIndex::new();
228 assert!(idx.query_tag("nonexistent").is_empty());
229 }
230
231 #[test]
232 fn test_remove_tag() {
233 let idx = BitmapIndex::new();
234 let id = MemoryId::new();
235 idx.add_tag(id, "foo");
236 idx.remove_tag(id, "foo");
237
238 assert!(idx.query_tag("foo").is_empty());
239 }
240
241 #[test]
242 fn test_tags_and() {
243 let idx = BitmapIndex::new();
244 let a = MemoryId::new();
245 let b = MemoryId::new();
246
247 idx.add_tag(a, "x");
248 idx.add_tag(a, "y");
249 idx.add_tag(b, "x");
250
251 let both = idx.query_tags_and(&["x", "y"]);
252 assert_eq!(both, vec![a]);
253 }
254
255 #[test]
256 fn test_tags_or() {
257 let idx = BitmapIndex::new();
258 let a = MemoryId::new();
259 let b = MemoryId::new();
260
261 idx.add_tag(a, "x");
262 idx.add_tag(b, "y");
263
264 let either = idx.query_tags_or(&["x", "y"]);
265 assert_eq!(either.len(), 2);
266 }
267
268 #[test]
269 fn test_remove_all() {
270 let idx = BitmapIndex::new();
271 let id = MemoryId::new();
272 idx.add_tag(id, "a");
273 idx.add_tag(id, "b");
274 idx.remove_all(id);
275
276 assert!(idx.query_tag("a").is_empty());
277 assert!(idx.query_tag("b").is_empty());
278 }
279}