redb_extras/roaring/
mod.rs

1//! Roaring bitmap handling module.
2//!
3//! This module provides roaring-specific value handling including encoding,
4//! decoding, and operations that require bitmap knowledge.
5
6use crate::Result;
7use roaring::RoaringTreemap;
8use std::fmt;
9
10/// Errors specific to the roaring layer.
11/// These are concerned with bitmap operations and value-specific semantics.
12#[derive(Debug)]
13pub enum RoaringError {
14    /// Failed to serialize/deserialize RoaringTreemap
15    SerializationFailed(String),
16
17    /// Compaction operation failed
18    CompactionFailed(String),
19
20    /// Invalid roaring bitmap data
21    InvalidBitmap(String),
22
23    /// Size query failed
24    SizeQueryFailed(String),
25}
26
27impl fmt::Display for RoaringError {
28    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29        match self {
30            RoaringError::SerializationFailed(msg) => {
31                write!(f, "Roaring serialization failed: {}", msg)
32            }
33            RoaringError::CompactionFailed(msg) => {
34                write!(f, "Compaction failed: {}", msg)
35            }
36            RoaringError::InvalidBitmap(msg) => {
37                write!(f, "Invalid roaring bitmap: {}", msg)
38            }
39            RoaringError::SizeQueryFailed(msg) => {
40                write!(f, "Size query failed: {}", msg)
41            }
42        }
43    }
44}
45
46impl std::error::Error for RoaringError {
47    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
48        None
49    }
50}
51
52pub trait RoaringValueReadOnlyTable<'txn, K> {
53    /// Gets complete roaring bitmap for the given key.
54    ///
55    /// # Arguments
56    /// * `key` - The key to retrieve (any type that implements redb::Key)
57    ///
58    /// # Returns
59    /// The complete RoaringTreemap or empty if not found
60    fn get_bitmap(&self, key: K) -> Result<RoaringTreemap>;
61
62    /// Checks if a member exists in the bitmap for the given key.
63    ///
64    /// # Arguments
65    /// * `key` - The key to check
66    /// * `member` - The member to check for
67    ///
68    /// # Returns
69    /// True if the member exists, false otherwise
70    fn contains_member(&self, key: K, member: u64) -> Result<bool> {
71        let bitmap = self.get_bitmap(key)?;
72        Ok(bitmap.contains(member))
73    }
74
75    /// Gets the number of members in the bitmap for the given key.
76    ///
77    /// # Arguments
78    /// * `key` - The key to query
79    ///
80    /// # Returns
81    /// The number of members in the bitmap
82    fn get_member_count(&self, key: K) -> Result<u64> {
83        let bitmap = self.get_bitmap(key)?;
84        Ok(bitmap.len())
85    }
86
87    fn iter_members(&self, key: K) -> Result<impl Iterator<Item = u64> + '_> {
88        // Get complete bitmap and return iterator
89        let bitmap = self.get_bitmap(key)?;
90        Ok(bitmap.into_iter())
91    }
92}
93
94pub trait RoaringValueTable<'txn, K>: RoaringValueReadOnlyTable<'txn, K> {
95    /// Inserts a single member ID into the bitmap for the given key.
96    ///
97    /// This method handles shard selection, head segment discovery, segment rolling,
98    /// and bitmap serialization automatically.
99    ///
100    /// # Arguments
101    /// * `key` - The key to modify (any type that implements redb::Key)
102    /// * `member` - The member to insert
103    ///
104    /// # Returns
105    /// Result indicating success or failure
106    fn insert_member(&mut self, key: K, member: u64) -> Result<()>;
107
108    /// Removes a single member ID from the bitmap for the given key.
109    ///
110    /// This method handles shard selection, head segment discovery, segment rolling,
111    /// and bitmap serialization automatically.
112    ///
113    /// # Arguments
114    /// * `key` - The key to modify (any type that implements redb::Key)
115    /// * `member` - The member to remove
116    ///
117    /// # Returns
118    /// Result indicating success or failure
119    fn remove_member(&mut self, key: K, member: u64) -> Result<()>;
120
121    /// Inserts multiple members into the bitmap for the given key.
122    ///
123    /// This is a batch operation that is more efficient than individual inserts
124    /// for large numbers of members.
125    ///
126    /// # Arguments
127    /// * `key` - The key to modify
128    /// * `members` - Iterator of members to insert
129    ///
130    /// # Returns
131    /// Result indicating success or failure
132    fn insert_members<I>(&mut self, key: K, members: I) -> Result<()>
133    where
134        K: Clone,
135        I: IntoIterator<Item = u64>,
136    {
137        let mut current_bitmap = self.get_bitmap(key.clone())?;
138        current_bitmap.extend(members);
139        self.replace_bitmap(key, current_bitmap)
140    }
141
142    /// Removes multiple members from the bitmap for the given key.
143    ///
144    /// This is a batch operation that is more efficient than individual removals
145    /// for large numbers of members.
146    ///
147    /// # Arguments
148    /// * `key` - The key to modify
149    /// * `members` - Iterator of members to remove
150    ///
151    /// # Returns
152    /// Result indicating success or failure
153    fn remove_members<I>(&mut self, key: K, members: I) -> Result<()>
154    where
155        K: Clone,
156        I: IntoIterator<Item = u64>,
157    {
158        let mut current_bitmap = self.get_bitmap(key.clone())?;
159        for member in members {
160            current_bitmap.remove(member);
161        }
162        self.replace_bitmap(key, current_bitmap)
163    }
164
165    /// Clears all members from the bitmap for the given key.
166    ///
167    /// # Arguments
168    /// * `key` - The key to clear
169    ///
170    /// # Returns
171    /// Result indicating success or failure
172    fn clear_bitmap(&mut self, key: K) -> Result<()> {
173        self.remove_key(key)
174    }
175
176    // Helper methods for internal implementation
177    fn replace_bitmap(&mut self, key: K, bitmap: RoaringTreemap) -> Result<()>;
178    fn remove_key(&mut self, key: K) -> Result<()>;
179}
180
181mod facade;
182mod value;
183
184// Re-export main types for public API
185pub use value::RoaringValue;