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 bincode::serialize(&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 = bincode::deserialize(&data)
181 .or_else(|_| serde_json::from_slice(&data))
182 .map_err(|e| MenteError::Serialization(e.to_string()))?;
183
184 let mut tag_bitmaps = HashMap::default();
185 for (tag, bytes) in snapshot.tag_bitmaps {
186 let bm = RoaringBitmap::deserialize_from(&mut Cursor::new(bytes))
187 .map_err(|e| MenteError::Serialization(e.to_string()))?;
188 tag_bitmaps.insert(tag, bm);
189 }
190
191 let mut id_to_offset = HashMap::default();
192 for (id, offset) in snapshot.id_to_offset {
193 id_to_offset.insert(id, offset);
194 }
195
196 Ok(Self {
197 inner: RwLock::new(BitmapInner {
198 tag_bitmaps,
199 id_to_offset,
200 offset_to_id: snapshot.offset_to_id,
201 }),
202 })
203 }
204}
205
206impl Default for BitmapIndex {
207 fn default() -> Self {
208 Self::new()
209 }
210}
211
212#[cfg(test)]
213mod tests {
214 use super::*;
215
216 #[test]
217 fn test_add_and_query_tag() {
218 let idx = BitmapIndex::new();
219 let id = MemoryId::new();
220 idx.add_tag(id, "important");
221
222 let results = idx.query_tag("important");
223 assert_eq!(results, vec![id]);
224 }
225
226 #[test]
227 fn test_query_empty_tag() {
228 let idx = BitmapIndex::new();
229 assert!(idx.query_tag("nonexistent").is_empty());
230 }
231
232 #[test]
233 fn test_remove_tag() {
234 let idx = BitmapIndex::new();
235 let id = MemoryId::new();
236 idx.add_tag(id, "foo");
237 idx.remove_tag(id, "foo");
238
239 assert!(idx.query_tag("foo").is_empty());
240 }
241
242 #[test]
243 fn test_tags_and() {
244 let idx = BitmapIndex::new();
245 let a = MemoryId::new();
246 let b = MemoryId::new();
247
248 idx.add_tag(a, "x");
249 idx.add_tag(a, "y");
250 idx.add_tag(b, "x");
251
252 let both = idx.query_tags_and(&["x", "y"]);
253 assert_eq!(both, vec![a]);
254 }
255
256 #[test]
257 fn test_tags_or() {
258 let idx = BitmapIndex::new();
259 let a = MemoryId::new();
260 let b = MemoryId::new();
261
262 idx.add_tag(a, "x");
263 idx.add_tag(b, "y");
264
265 let either = idx.query_tags_or(&["x", "y"]);
266 assert_eq!(either.len(), 2);
267 }
268
269 #[test]
270 fn test_remove_all() {
271 let idx = BitmapIndex::new();
272 let id = MemoryId::new();
273 idx.add_tag(id, "a");
274 idx.add_tag(id, "b");
275 idx.remove_all(id);
276
277 assert!(idx.query_tag("a").is_empty());
278 assert!(idx.query_tag("b").is_empty());
279 }
280}