### Retrieving RoaringBitmap Internal Statistics Source: https://context7.com/roaringbitmap/roaring-rs/llms.txt Explains how to use `statistics` to get detailed internal information about a `RoaringBitmap`'s container composition, cardinality, min/max values, and byte usage. This is useful for performance analysis and debugging, especially after operations like `optimize()`. ```rust use roaring::RoaringBitmap; let mut rb: RoaringBitmap = (1..100).collect(); // small: fits in an array container let stats = rb.statistics(); assert_eq!(stats.n_containers, 1); assert_eq!(stats.n_array_containers, 1); assert_eq!(stats.n_run_containers, 0); assert_eq!(stats.n_bitset_containers, 0); assert_eq!(stats.cardinality, 99); assert_eq!(stats.min_value, Some(1)); assert_eq!(stats.max_value, Some(99)); // After optimize(), dense ranges become run containers let mut rb2: RoaringBitmap = (0..=10000).collect(); rb2.optimize(); let stats2 = rb2.statistics(); assert_eq!(stats2.n_run_containers, 1); assert_eq!(stats2.cardinality, 10001); assert_eq!(stats2.n_bytes_run_containers, 6); // very compact ``` -------------------------------- ### RoaringBitmap Rank and Select Operations Source: https://context7.com/roaringbitmap/roaring-rs/llms.txt Use `rank(v)` to count set values less than or equal to `v`. Use `select(n)` to get the nth smallest value (0-indexed). `min()` and `max()` retrieve the smallest and largest values respectively. ```rust use roaring::RoaringBitmap; let rb: RoaringBitmap = [10, 20, 30, 40, 50].into_iter().collect(); // rank: count of elements <= value assert_eq!(rb.rank(9), 0); assert_eq!(rb.rank(10), 1); assert_eq!(rb.rank(25), 2); // 10 and 20 are <= 25 assert_eq!(rb.rank(50), 5); // select: 0-indexed nth element assert_eq!(rb.select(0), Some(10)); assert_eq!(rb.select(2), Some(30)); assert_eq!(rb.select(4), Some(50)); assert_eq!(rb.select(5), None); // out of bounds // min / max assert_eq!(rb.min(), Some(10)); assert_eq!(rb.max(), Some(50)); ``` -------------------------------- ### Run Benchmarks Source: https://github.com/roaringbitmap/roaring-rs/blob/main/README.md Execute benchmarks using the Criterion library. Recommended to run on bare-metal machines for accurate results. ```bash cargo bench ``` -------------------------------- ### Run Tests Source: https://github.com/roaringbitmap/roaring-rs/blob/main/README.md Execute all project tests to verify code correctness. Ensure all tests pass before contributing. ```bash cargo test ``` -------------------------------- ### Optimize and Remove Run Compression for RoaringBitmap Source: https://context7.com/roaringbitmap/roaring-rs/llms.txt Demonstrates how to optimize a RoaringBitmap for space efficiency by converting dense ranges to run containers and how to forcibly remove run-length encoding. Ensure values are preserved through these operations. ```rust use roaring::RoaringBitmap; let mut rb: RoaringBitmap = (0..=10000).collect(); // Before optimize: likely stored as a bitmap container let before = rb.statistics().n_run_containers; // optimize converts dense ranges to run containers let changed = rb.optimize(); assert!(changed); let after = rb.statistics().n_run_containers; assert!(after > before); // remove_run_compression reverses the encoding assert!(rb.remove_run_compression()); let reverted = rb.statistics().n_run_containers; assert_eq!(reverted, 0); // Values are preserved through both operations assert_eq!(rb.len(), 10001); assert!(rb.contains(5000)); ``` -------------------------------- ### Check Code Formatting and Linting Source: https://github.com/roaringbitmap/roaring-rs/blob/main/README.md Run these commands to ensure code adheres to formatting standards and passes linting checks. Requires Clippy and rustfmt components. ```bash cargo fmt -- --check ``` ```bash cargo clippy --all-targets -- -D warnings ``` -------------------------------- ### Constructing RoaringBitmap from LSB0 Bytes Source: https://context7.com/roaringbitmap/roaring-rs/llms.txt Shows how to create a `RoaringBitmap` from a byte slice using `from_lsb0_bytes`, which interprets bits in LSB-first order. An optional bit offset can be provided to shift the imported bits. ```rust use roaring::RoaringBitmap; // Each byte is read LSB-first: // 0b00000101 => bits 0 and 2 are set let bytes = [0b00000101u8, 0b00000010, 0b00000000, 0b10000000]; // bit76543210 bit98 ... bit31 let rb = RoaringBitmap::from_lsb0_bytes(0, &bytes); assert!(rb.contains(0)); // bit 0 of byte 0 assert!(!rb.contains(1)); // bit 1 of byte 0 is 0 assert!(rb.contains(2)); // bit 2 of byte 0 assert!(rb.contains(9)); // bit 1 of byte 1 assert!(rb.contains(31)); // MSB of byte 3 // With a bit offset of 8: shift all bits up by 8 let rb8 = RoaringBitmap::from_lsb0_bytes(8, &bytes); assert!(rb8.contains(8)); // was bit 0, now bit 8 assert!(rb8.contains(10)); // was bit 2, now bit 10 // Non-multiple-of-8 offset is also supported let rb3 = RoaringBitmap::from_lsb0_bytes(3, &bytes); assert!(rb3.contains(3)); // was bit 0, now bit 3 assert!(rb3.contains(5)); // was bit 2, now bit 5 ``` -------------------------------- ### RoaringBitmap::new / RoaringBitmap::full Source: https://context7.com/roaringbitmap/roaring-rs/llms.txt Creates an empty RoaringBitmap or a RoaringBitmap containing all possible u32 values. ```APIDOC ## RoaringBitmap::new / RoaringBitmap::full ### Description Creates an empty or a completely full (`0..=u32::MAX`) `RoaringBitmap`. ### Method Associated functions (constructors) ### Usage ```rust use roaring::RoaringBitmap; let empty = RoaringBitmap::new(); assert!(empty.is_empty()); assert_eq!(empty.len(), 0); let full = RoaringBitmap::full(); assert!(full.is_full()); assert_eq!(full.len(), u32::MAX as u64 + 1); assert!(full.contains(0)); assert!(full.contains(u32::MAX)); ``` ``` -------------------------------- ### Bidirectional Iteration and Seeking with RoaringBitmap Source: https://context7.com/roaringbitmap/roaring-rs/llms.txt Demonstrates using `advance_to` to seek forward, `advance_back_to` to seek backward, and `next_range` to efficiently consume consecutive runs of values. The `range` method allows iterating over a specific slice of the bitmap. ```rust use roaring::RoaringBitmap; let bitmap = RoaringBitmap::from([1, 2, 3, 10, 11, 12, 50]); // advance_to: skip forward to the first value >= n let mut iter = bitmap.iter(); iter.advance_to(10); assert_eq!(iter.next(), Some(10)); assert_eq!(iter.next(), Some(11)); // advance_back_to: trim the back to the first value <= n let mut iter = bitmap.iter(); iter.advance_back_to(12); assert_eq!(iter.next_back(), Some(12)); assert_eq!(iter.next_back(), Some(11)); // next_range: efficiently consume an entire run of consecutive values let bm = RoaringBitmap::from([1, 2, 3, 7, 8, 20]); let mut iter = bm.iter(); assert_eq!(iter.next_range(), Some(1..=3)); assert_eq!(iter.next_range(), Some(7..=8)); assert_eq!(iter.next_range(), Some(20..=20)); assert_eq!(iter.next_range(), None); // range: iterate only a slice of the bitmap let bitmap2 = RoaringBitmap::from([0, 1, 5, 10, 11, 20, u32::MAX]); let slice: Vec = bitmap2.range(5..=11).collect(); assert_eq!(slice, vec![5, 10, 11]); ``` -------------------------------- ### Construction from LSB0 Bytes Source: https://context7.com/roaringbitmap/roaring-rs/llms.txt Explains how to construct a `RoaringBitmap` from a byte slice using little-endian bit ordering (LSB0) with an optional bit offset. ```APIDOC ## `RoaringBitmap::from_lsb0_bytes` Constructs a bitmap from a raw byte slice, interpreting bits in LSB-first order with an optional bit offset. Useful for importing bitfield data from external systems. ### Description This method allows creating a `RoaringBitmap` by reading bits from a byte slice where the least significant bit (LSB) of each byte corresponds to the lowest bit index. An offset can be provided to shift the interpretation of these bits. ### Parameters - `offset` (u32): The bit offset to apply to the data read from the bytes. - `bytes` (&[u8]): The byte slice containing the bit data. ### Request Example ```rust use roaring::RoaringBitmap; // Each byte is read LSB-first: // 0b00000101 => bits 0 and 2 are set let bytes = [0b00000101u8, 0b00000010, 0b00000000, 0b10000000]; // bit76543210 bit98 ... bit31 let rb = RoaringBitmap::from_lsb0_bytes(0, &bytes); assert!(rb.contains(0)); // bit 0 of byte 0 assert!(!rb.contains(1)); // bit 1 of byte 0 is 0 assert!(rb.contains(2)); // bit 2 of byte 0 assert!(rb.contains(9)); // bit 1 of byte 1 assert!(rb.contains(31)); // MSB of byte 3 // With a bit offset of 8: shift all bits up by 8 let rb8 = RoaringBitmap::from_lsb0_bytes(8, &bytes); assert!(rb8.contains(8)); // was bit 0, now bit 8 assert!(rb8.contains(10)); // was bit 2, now bit 10 // Non-multiple-of-8 offset is also supported let rb3 = RoaringBitmap::from_lsb0_bytes(3, &bytes); assert!(rb3.contains(3)); // was bit 0, now bit 3 assert!(rb3.contains(5)); // was bit 2, now bit 5 ``` ``` -------------------------------- ### RoaringBitmap::try_push / RoaringBitmap::append Source: https://context7.com/roaringbitmap/roaring-rs/llms.txt Builds a bitmap from pre-sorted data using `try_push` for single values or `append` for iterators. ```APIDOC ## RoaringBitmap::try_push / RoaringBitmap::append ### Description Efficiently builds a bitmap from pre-sorted data. `try_push` appends a single value that must be greater than the current maximum; `append` extends with a sorted iterator and reports how many values were consumed before any out-of-order value. ### Method - `try_push(value: u32) -> Result<(), IntegerTooSmall>` - `append(iter: impl Iterator) -> Result` - `from_sorted_iter(iter: impl Iterator) -> Result` ### Usage ```rust use roaring::{RoaringBitmap, IntegerTooSmall, NonSortedIntegers}; // try_push: O(1) amortized, requires strictly increasing values let mut rb = RoaringBitmap::new(); assert!(rb.try_push(1).is_ok()); assert!(rb.try_push(5).is_ok()); assert_eq!(rb.try_push(5), Err(IntegerTooSmall)); // not strictly greater assert!(rb.try_push(6).is_ok()); // from_sorted_iter: build from any sorted iterator let rb2 = RoaringBitmap::from_sorted_iter(0..1000).unwrap(); assert_eq!(rb2.len(), 1000); // append: extend an existing bitmap with a sorted iterator let mut rb3 = RoaringBitmap::new(); assert_eq!(rb3.append(0..500), Ok(500)); assert_eq!(rb3.append(1000..1500), Ok(500)); // continues from max let err = rb3.append([100, 200].into_iter()).unwrap_err(); // out of order assert_eq!(err.valid_until(), 0); // zero values appended ``` ``` -------------------------------- ### Create Empty or Full RoaringBitmap Source: https://context7.com/roaringbitmap/roaring-rs/llms.txt Use `RoaringBitmap::new()` to create an empty bitmap or `RoaringBitmap::full()` for a bitmap containing all possible u32 values. Check emptiness with `is_empty()` and fullness with `is_full()`. The length of a full bitmap is `u32::MAX + 1`. ```rust use roaring::RoaringBitmap; let empty = RoaringBitmap::new(); assert!(empty.is_empty()); assert_eq!(empty.len(), 0); let full = RoaringBitmap::full(); assert!(full.is_full()); assert_eq!(full.len(), u32::MAX as u64 + 1); assert!(full.contains(0)); assert!(full.contains(u32::MAX)); ``` -------------------------------- ### Serialization and Deserialization Source: https://context7.com/roaringbitmap/roaring-rs/llms.txt Covers methods for serializing a `RoaringBitmap` to a byte vector or writer and deserializing it back, ensuring compatibility with other Roaring implementations. ```APIDOC ## `RoaringBitmap::serialize_into` / `RoaringBitmap::deserialize_from` Serializes and deserializes a bitmap using the standard cross-language Roaring format, compatible with the official C/C++, Java, and Go implementations. ### Description These methods provide a way to convert a `RoaringBitmap` into a byte sequence for storage or transmission, and to reconstruct a `RoaringBitmap` from such a sequence. They support both checked deserialization (validating data integrity) and an unchecked variant for performance when data is trusted. ### Methods - `serialize_into(&mut self, writer: &mut W)`: Serializes the bitmap into the provided `Write` implementor. - `deserialize_from(reader: &R)`: Deserializes the bitmap from the provided `Read` implementor, performing checks. - `deserialize_unchecked_from(reader: &R)`: Deserializes the bitmap from the provided `Read` implementor without checks (faster). ### Usage Examples ```rust use roaring::RoaringBitmap; use std::io::Cursor; let original: RoaringBitmap = (1..1000).chain([65536, 65537, 131072]).collect(); // Pre-compute size for buffer allocation let size = original.serialized_size(); let mut bytes = Vec::with_capacity(size); // Serialize original.serialize_into(&mut bytes).unwrap(); assert_eq!(bytes.len(), size); // Deserialize (checked – validates internal invariants) let restored = RoaringBitmap::deserialize_from(&bytes[..]).unwrap(); assert_eq!(original, restored); // Unchecked variant for trusted data (slightly faster) let restored2 = RoaringBitmap::deserialize_unchecked_from(&bytes[..]).unwrap(); assert_eq!(original, restored2); // Works with any io::Read / io::Write (files, network sockets, etc.) let mut cursor = Cursor::new(Vec::new()); original.serialize_into(&mut cursor).unwrap(); cursor.set_position(0); let from_cursor = RoaringBitmap::deserialize_from(cursor).unwrap(); assert_eq!(original, from_cursor); ``` ``` -------------------------------- ### Serializing and Deserializing RoaringBitmaps Source: https://context7.com/roaringbitmap/roaring-rs/llms.txt Demonstrates how to serialize a `RoaringBitmap` to a byte vector using `serialize_into` and deserialize it back using `deserialize_from`. The `deserialize_unchecked_from` variant is faster but assumes trusted input. Serialization also works with any `io::Read` and `io::Write`. ```rust use roaring::RoaringBitmap; let original: RoaringBitmap = (1..1000).chain([65536, 65537, 131072]).collect(); // Pre-compute size for buffer allocation let size = original.serialized_size(); let mut bytes = Vec::with_capacity(size); // Serialize original.serialize_into(&mut bytes).unwrap(); assert_eq!(bytes.len(), size); // Deserialize (checked – validates internal invariants) let restored = RoaringBitmap::deserialize_from(&bytes[..]).unwrap(); assert_eq!(original, restored); // Unchecked variant for trusted data (slightly faster) let restored2 = RoaringBitmap::deserialize_unchecked_from(&bytes[..]).unwrap(); assert_eq!(original, restored2); // Works with any io::Read / io::Write (files, network sockets, etc.) use std::io::Cursor; let mut cursor = Cursor::new(Vec::new()); original.serialize_into(&mut cursor).unwrap(); cursor.set_position(0); let from_cursor = RoaringBitmap::deserialize_from(cursor).unwrap(); assert_eq!(original, from_cursor); ``` -------------------------------- ### MultiOps for RoaringTreemap Bulk Operations Source: https://context7.com/roaringbitmap/roaring-rs/llms.txt Shows how to use the `MultiOps` trait with `RoaringTreemap` for efficient bulk set operations like union and difference on multiple 64-bit bitmaps. Prefer `MultiOps` for aggregating more than two bitmaps. ```rust use roaring::{MultiOps, RoaringTreemap}; let maps = [ RoaringTreemap::from_iter(0u64..10), RoaringTreemap::from_iter(5u64..15), RoaringTreemap::from_iter(10u64..20), ]; let union = maps.clone().union(); assert_eq!(union.len(), 20); assert_eq!(union.min(), Some(0)); assert_eq!(union.max(), Some(19)); let diff = maps.difference(); // first minus all others assert_eq!(diff.iter().collect::>(), vec![0, 1, 2, 3, 4]); ``` -------------------------------- ### Iterator Seeking and Range Consumption Source: https://context7.com/roaringbitmap/roaring-rs/llms.txt Demonstrates `advance_to`, `advance_back_to`, and `next_range` for efficient seeking and consuming consecutive values within a Roaring Bitmap iterator. ```APIDOC ## `Iter::advance_to` / `Iter::advance_back_to` / `Iter::next_range` The `Iter` and `IntoIter` types provide bidirectional iteration with efficient seeking and run-detection. ### Description - `advance_to(n)`: Skips forward in the iterator to the first value greater than or equal to `n`. - `advance_back_to(n)`: Trims the iterator from the back to the first value less than or equal to `n`. - `next_range()`: Efficiently consumes and returns an entire run of consecutive values as a range. ### Usage Examples ```rust use roaring::RoaringBitmap; let bitmap = RoaringBitmap::from([1, 2, 3, 10, 11, 12, 50]); // advance_to: skip forward to the first value >= n let mut iter = bitmap.iter(); iter.advance_to(10); assert_eq!(iter.next(), Some(10)); assert_eq!(iter.next(), Some(11)); // advance_back_to: trim the back to the first value <= n let mut iter = bitmap.iter(); iter.advance_back_to(12); assert_eq!(iter.next_back(), Some(12)); assert_eq!(iter.next_back(), Some(11)); // next_range: efficiently consume an entire run of consecutive values let bm = RoaringBitmap::from([1, 2, 3, 7, 8, 20]); let mut iter = bm.iter(); assert_eq!(iter.next_range(), Some(1..=3)); assert_eq!(iter.next_range(), Some(7..=8)); assert_eq!(iter.next_range(), Some(20..=20)); assert_eq!(iter.next_range(), None); ``` ``` -------------------------------- ### RoaringTreemap for 64-bit Integers Source: https://context7.com/roaringbitmap/roaring-rs/llms.txt Illustrates the usage of RoaringTreemap for managing u64 values, including insertion, range operations across the 32-bit boundary, rank/select queries, and serialization/deserialization. Supports the full u64 range. ```rust use roaring::RoaringTreemap; let mut tm = RoaringTreemap::new(); // Supports full u64 range tm.insert(0); tm.insert(u64::MAX); tm.insert(0x1_0000_0000); // crosses the 32-bit boundary assert_eq!(tm.len(), 3); assert!(tm.contains(u64::MAX)); assert_eq!(tm.min(), Some(0)); assert_eq!(tm.max(), Some(u64::MAX)); // insert_range works across the u32 boundary let mut tm2 = RoaringTreemap::new(); tm2.insert_range(0xFFFF_FFFE..=0x1_0000_0001); // 4 values spanning the boundary assert_eq!(tm2.len(), 4); assert!(tm2.contains(0xFFFF_FFFF)); assert!(tm2.contains(0x1_0000_0000)); // rank and select tm2.insert_range(0..10); let combined_len = tm2.len(); assert_eq!(tm2.rank(9), 10); // 0..=9 are the 10 smallest // Serialization (compatible with Java/Go Roaring treemap format) let mut bytes = Vec::new(); tm2.serialize_into(&mut bytes).unwrap(); let restored = RoaringTreemap::deserialize_from(&bytes[..]).unwrap(); assert_eq!(tm2, restored); ``` -------------------------------- ### RoaringBitmap::insert / RoaringBitmap::remove / RoaringBitmap::contains Source: https://context7.com/roaringbitmap/roaring-rs/llms.txt Performs single-value insertion, removal, and membership testing for RoaringBitmaps. ```APIDOC ## RoaringBitmap::insert / RoaringBitmap::remove / RoaringBitmap::contains ### Description Core single-value mutation and membership test operations. `insert` returns `true` when the value was newly added; `remove` returns `true` when the value was present and has been removed. ### Method - `insert(value: u32) -> bool` - `remove(value: u32) -> bool` - `contains(value: u32) -> bool` ### Usage ```rust use roaring::RoaringBitmap; let mut rb = RoaringBitmap::new(); // insert returns true on a new value, false on a duplicate assert_eq!(rb.insert(42), true); assert_eq!(rb.insert(42), false); assert_eq!(rb.insert(100), true); assert_eq!(rb.contains(42), true); assert_eq!(rb.contains(99), false); // remove returns true if the value was present assert_eq!(rb.remove(42), true); assert_eq!(rb.remove(42), false); assert_eq!(rb.contains(42), false); assert_eq!(rb.len(), 1); // 100 remains ``` ``` -------------------------------- ### Insert, Remove, and Check Membership in RoaringBitmap Source: https://context7.com/roaringbitmap/roaring-rs/llms.txt Use `insert` to add a value, `remove` to delete it, and `contains` to check for its presence. `insert` returns `true` if the value was newly added, and `false` if it was already present. `remove` returns `true` if the value was present and removed. ```rust use roaring::RoaringBitmap; let mut rb = RoaringBitmap::new(); // insert returns true on a new value, false on a duplicate assert_eq!(rb.insert(42), true); assert_eq!(rb.insert(42), false); assert_eq!(rb.insert(100), true); assert_eq!(rb.contains(42), true); assert_eq!(rb.contains(99), false); // remove returns true if the value was present assert_eq!(rb.remove(42), true); assert_eq!(rb.remove(42), false); assert_eq!(rb.contains(42), false); assert_eq!(rb.len(), 1); // 100 remains ``` -------------------------------- ### Bitmap Statistics Source: https://context7.com/roaringbitmap/roaring-rs/llms.txt Details the `statistics` method for retrieving internal composition and cardinality information about a `RoaringBitmap` without modification. ```APIDOC ## `RoaringBitmap::statistics` Returns detailed internal statistics about container composition without modifying the bitmap, useful for performance analysis and debugging. ### Description The `statistics` method provides insights into how a `RoaringBitmap` is internally structured, including the number and types of containers (array, run, bitset) it uses, its total cardinality, and its minimum and maximum values. This information is valuable for understanding memory usage and optimizing performance. ### Usage Examples ```rust use roaring::RoaringBitmap; let mut rb: RoaringBitmap = (1..100).collect(); // small: fits in an array container let stats = rb.statistics(); assert_eq!(stats.n_containers, 1); assert_eq!(stats.n_array_containers, 1); assert_eq!(stats.n_run_containers, 0); assert_eq!(stats.n_bitset_containers, 0); assert_eq!(stats.cardinality, 99); assert_eq!(stats.min_value, Some(1)); assert_eq!(stats.max_value, Some(99)); // After optimize(), dense ranges become run containers let mut rb2: RoaringBitmap = (0..=10000).collect(); rb2.optimize(); let stats2 = rb2.statistics(); assert_eq!(stats2.n_run_containers, 1); assert_eq!(stats2.cardinality, 10001); assert_eq!(stats2.n_bytes_run_containers, 6); // very compact ``` ``` -------------------------------- ### RoaringTreemap — 64-bit bitmap Source: https://context7.com/roaringbitmap/roaring-rs/llms.txt RoaringTreemap extends Roaring bitmaps to u64 values by using a BTreeMap for the high 32 bits. Its API mirrors RoaringBitmap and supports the full u64 range, including operations across the 32-bit boundary, rank, select, and serialization. ```APIDOC ## `RoaringTreemap` — 64-bit bitmap `RoaringTreemap` extends the Roaring bitmap concept to `u64` values using a `BTreeMap` for the high 32 bits. The API mirrors `RoaringBitmap`. ```rust use roaring::RoaringTreemap; let mut tm = RoaringTreemap::new(); // Supports full u64 range tm.insert(0); tm.insert(u64::MAX); tm.insert(0x1_0000_0000); // crosses the 32-bit boundary assert_eq!(tm.len(), 3); assert!(tm.contains(u64::MAX)); assert_eq!(tm.min(), Some(0)); assert_eq!(tm.max(), Some(u64::MAX)); // insert_range works across the u32 boundary let mut tm2 = RoaringTreemap::new(); tm2.insert_range(0xFFFF_FFFE..=0x1_0000_0001); // 4 values spanning the boundary assert_eq!(tm2.len(), 4); assert!(tm2.contains(0xFFFF_FFFF)); assert!(tm2.contains(0x1_0000_0000)); // rank and select tm2.insert_range(0..10); let combined_len = tm2.len(); assert_eq!(tm2.rank(9), 10); // 0..=9 are the 10 smallest // Serialization (compatible with Java/Go Roaring treemap format) let mut bytes = Vec::new(); tm2.serialize_into(&mut bytes).unwrap(); let restored = RoaringTreemap::deserialize_from(&bytes[..]).unwrap(); assert_eq!(tm2, restored); ``` ``` -------------------------------- ### Set Operations (Union, Intersection, Difference, Symmetric Difference) Source: https://context7.com/roaringbitmap/roaring-rs/llms.txt Perform standard set algebra operations using overloaded Rust operators for RoaringBitmaps. ```APIDOC ## Set Operations: `|`, `&`, `-`, `^` (and assign variants) Standard set algebra via overloaded Rust operators. All four combinations of owned/reference operands are supported. ### Example Usage ```rust use roaring::RoaringBitmap; let a: RoaringBitmap = (1..5).collect(); // {1,2,3,4} let b: RoaringBitmap = (3..7).collect(); // {3,4,5,6} // Union let union = &a | &b; assert_eq!(union.iter().collect::>(), vec![1, 2, 3, 4, 5, 6]); // Intersection let inter = &a & &b; assert_eq!(inter.iter().collect::>(), vec![3, 4]); // Difference (a minus b) let diff = &a - &b; assert_eq!(diff.iter().collect::>(), vec![1, 2]); // Symmetric difference let sym = &a ^ &b; assert_eq!(sym.iter().collect::>(), vec![1, 2, 5, 6]); // Cardinality shortcuts (no allocation) assert_eq!(a.intersection_len(&b), 2); assert_eq!(a.union_len(&b), 6); assert_eq!(a.difference_len(&b), 2); assert_eq!(a.symmetric_difference_len(&b), 4); // In-place assign variants let mut c: RoaringBitmap = (0..10).collect(); c &= &a; // keep only values in a assert_eq!(c.iter().collect::>(), vec![1, 2, 3, 4]); ``` ``` -------------------------------- ### Rank and Select Operations Source: https://context7.com/roaringbitmap/roaring-rs/llms.txt The `rank(v)` method returns the count of set values less than or equal to `v`. The `select(n)` method returns the `n`th smallest value (0-indexed). ```APIDOC ## `RoaringBitmap::rank` / `RoaringBitmap::select` Order-statistic operations: `rank(v)` returns how many set values are ≤ `v`; `select(n)` returns the `n`th smallest value (0-indexed). ### Example Usage ```rust use roaring::RoaringBitmap; let rb: RoaringBitmap = [10, 20, 30, 40, 50].into_iter().collect(); // rank: count of elements <= value assert_eq!(rb.rank(9), 0); assert_eq!(rb.rank(10), 1); assert_eq!(rb.rank(25), 2); // 10 and 20 are <= 25 assert_eq!(rb.rank(50), 5); // select: 0-indexed nth element assert_eq!(rb.select(0), Some(10)); assert_eq!(rb.select(2), Some(30)); assert_eq!(rb.select(4), Some(50)); assert_eq!(rb.select(5), None); // out of bounds // min / max assert_eq!(rb.min(), Some(10)); assert_eq!(rb.max(), Some(50)); ``` ``` -------------------------------- ### Append Sorted Data to RoaringBitmap Source: https://context7.com/roaringbitmap/roaring-rs/llms.txt Use `try_push` to append a single value that must be strictly greater than the current maximum. Use `append` to extend with a sorted iterator, reporting consumed values before any out-of-order element. `from_sorted_iter` builds a bitmap from any sorted iterator. ```rust use roaring::{RoaringBitmap, IntegerTooSmall, NonSortedIntegers}; // try_push: O(1) amortized, requires strictly increasing values let mut rb = RoaringBitmap::new(); assert!(rb.try_push(1).is_ok()); assert!(rb.try_push(5).is_ok()); assert_eq!(rb.try_push(5), Err(IntegerTooSmall)); // not strictly greater assert!(rb.try_push(6).is_ok()); // from_sorted_iter: build from any sorted iterator let rb2 = RoaringBitmap::from_sorted_iter(0..1000).unwrap(); assert_eq!(rb2.len(), 1000); // append: extend an existing bitmap with a sorted iterator let mut rb3 = RoaringBitmap::new(); assert_eq!(rb3.append(0..500), Ok(500)); assert_eq!(rb3.append(1000..1500), Ok(500)); // continues from max let err = rb3.append([100, 200].into_iter()).unwrap_err(); // out of order assert_eq!(err.valid_until(), 0); // zero values appended ``` -------------------------------- ### RoaringBitmap::optimize / RoaringBitmap::remove_run_compression Source: https://context7.com/roaringbitmap/roaring-rs/llms.txt These methods allow for optimizing the internal representation of a RoaringBitmap for space efficiency or forcibly removing run-length encoding. `optimize` converts containers to their most space-efficient form, while `remove_run_compression` reverses run-length encoding. ```APIDOC ## `RoaringBitmap::optimize` / `RoaringBitmap::remove_run_compression` Converts internal containers to the most space-efficient representation (`optimize`) or forcibly removes run-length encoding (`remove_run_compression`). ```rust use roaring::RoaringBitmap; let mut rb: RoaringBitmap = (0..=10000).collect(); // Before optimize: likely stored as a bitmap container let before = rb.statistics().n_run_containers; // optimize converts dense ranges to run containers let changed = rb.optimize(); assert!(changed); let after = rb.statistics().n_run_containers; assert!(after > before); // remove_run_compression reverses the encoding assert!(rb.remove_run_compression()); let reverted = rb.statistics().n_run_containers; assert_eq!(reverted, 0); // Values are preserved through both operations assert_eq!(rb.len(), 10001); assert!(rb.contains(5000)); ``` ``` -------------------------------- ### RoaringTreemap with MultiOps Source: https://context7.com/roaringbitmap/roaring-rs/llms.txt The `MultiOps` trait is implemented for `RoaringTreemap`, enabling efficient bulk set operations on 64-bit bitmaps. This includes operations like union and difference across multiple treemaps. ```APIDOC ## `RoaringTreemap` with `MultiOps` `MultiOps` is also implemented for `RoaringTreemap`, enabling fast bulk set operations over 64-bit bitmaps. ```rust use roaring::{MultiOps, RoaringTreemap}; let maps = [ RoaringTreemap::from_iter(0u64..10), RoaringTreemap::from_iter(5u64..15), RoaringTreemap::from_iter(10u64..20), ]; let union = maps.clone().union(); assert_eq!(union.len(), 20); assert_eq!(union.min(), Some(0)); assert_eq!(union.max(), Some(19)); let diff = maps.difference(); // first minus all others assert_eq!(diff.iter().collect::>(), vec![0, 1, 2, 3, 4]); ``` ``` -------------------------------- ### RoaringBitmap Set Operations with Operators Source: https://context7.com/roaringbitmap/roaring-rs/llms.txt Perform standard set operations like union (`|`), intersection (`&`), difference (`-`), and symmetric difference (`^`) using overloaded Rust operators. Supports both owned and referenced bitmaps. Also includes cardinality shortcuts like `intersection_len()` for efficient size calculation without allocation. ```rust use roaring::RoaringBitmap; let a: RoaringBitmap = (1..5).collect(); // {1,2,3,4} let b: RoaringBitmap = (3..7).collect(); // {3,4,5,6} // Union let union = &a | &b; assert_eq!(union.iter().collect::>(), vec![1, 2, 3, 4, 5, 6]); // Intersection let inter = &a & &b; assert_eq!(inter.iter().collect::>(), vec![3, 4]); // Difference (a minus b) let diff = &a - &b; assert_eq!(diff.iter().collect::>(), vec![1, 2]); // Symmetric difference let sym = &a ^ &b; assert_eq!(sym.iter().collect::>(), vec![1, 2, 5, 6]); // Cardinality shortcuts (no allocation) assert_eq!(a.intersection_len(&b), 2); assert_eq!(a.union_len(&b), 6); assert_eq!(a.difference_len(&b), 2); assert_eq!(a.symmetric_difference_len(&b), 4); // In-place assign variants let mut c: RoaringBitmap = (0..10).collect(); c &= &a; // keep only values in a assert_eq!(c.iter().collect::>(), vec![1, 2, 3, 4]); ``` -------------------------------- ### Efficiently Remove Smallest/Biggest Elements from RoaringBitmap Source: https://context7.com/roaringbitmap/roaring-rs/llms.txt Use `remove_smallest(n)` or `remove_biggest(n)` to efficiently trim a specified number of elements from the ends of the bitmap in-place. These operations are faster than individual removals and work correctly across internal container boundaries. ```rust use roaring::RoaringBitmap; let mut rb = RoaringBitmap::from_iter([1, 5, 7, 9, 11, 100]); rb.remove_smallest(2); assert_eq!(rb.min(), Some(7)); // 1 and 5 removed assert_eq!(rb.len(), 4); let mut rb2 = RoaringBitmap::from_iter([1, 5, 7, 9, 11, 100]); rb2.remove_biggest(2); assert_eq!(rb2.max(), Some(9)); // 11 and 100 removed assert_eq!(rb2.len(), 4); // Works across internal container boundaries let mut rb3 = RoaringBitmap::new(); rb3.insert_range(0..(1_u32 << 16) + 5); // 65541 values rb3.remove_smallest(65537); assert_eq!(rb3.len(), 4); assert_eq!(rb3.min(), Some(65537)); ``` -------------------------------- ### Insert and Remove Ranges in RoaringBitmap Source: https://context7.com/roaringbitmap/roaring-rs/llms.txt Efficiently insert or remove contiguous ranges of `u32` values using `insert_range` and `remove_range`. These operations can span multiple internal containers and return the count of values actually added or removed. Ranges are exclusive of the end value. ```rust use roaring::RoaringBitmap; let mut rb = RoaringBitmap::new(); let added = rb.insert_range(10..20); assert_eq!(added, 10); assert!(rb.contains(10)); assert!(rb.contains(19)); assert!(!rb.contains(20)); // Range can span multiple internal containers (>= 65536 values) let mut big = RoaringBitmap::new(); let added = big.insert_range(0..(1_u32 << 16) + 5); // 65541 values assert_eq!(added, 65541); // remove_range returns the count of removed values let removed = rb.remove_range(12..15); assert_eq!(removed, 3); assert!(!rb.contains(12)); assert!(rb.contains(10)); // still present ``` -------------------------------- ### MultiOps Trait: Bulk Set Operations Source: https://context7.com/roaringbitmap/roaring-rs/llms.txt Optimized multi-way union, intersection, difference, and symmetric difference operations over iterators of bitmaps. ```APIDOC ## `MultiOps` trait: bulk set operations The `MultiOps` trait provides optimized multi-way union, intersection, difference, and symmetric difference over any iterator of bitmaps. It is significantly faster than chained pairwise operations. ### Example Usage ```rust use roaring::{MultiOps, RoaringBitmap}; let bitmaps = [ RoaringBitmap::from_iter(0..10), RoaringBitmap::from_iter(5..15), RoaringBitmap::from_iter(10..20), ]; // Multi-way union (faster than fold with |) let union = bitmaps.clone().union(); assert_eq!(union.min(), Some(0)); assert_eq!(union.max(), Some(19)); assert_eq!(union.len(), 20); // Multi-way intersection let inter = bitmaps.clone().intersection(); assert!(inter.is_empty()); // no value in all three // Multi-way difference (first minus all others) let diff = bitmaps.clone().difference(); assert_eq!(diff.iter().collect::>(), vec![0, 1, 2, 3, 4]); // Works with references too (avoids cloning) let refs = [&bitmaps[0], &bitmaps[1], &bitmaps[2]]; let union_ref = refs.union(); assert_eq!(union_ref.len(), 20); // Also works with Result iterators (for fallible sources) use core::convert::Infallible; let results = bitmaps.map(Ok::<_, Infallible>); let union_try = results.union().unwrap(); assert_eq!(union_try.len(), 20); ``` ``` -------------------------------- ### Check Range Presence and Cardinality in RoaringBitmap Source: https://context7.com/roaringbitmap/roaring-rs/llms.txt Use `contains_range` to test if all values within a range are present. `range_cardinality` efficiently counts values within an arbitrary range without allocating a new bitmap. An empty range is always considered present. ```rust use roaring::RoaringBitmap; let mut rb = RoaringBitmap::new(); rb.insert_range(100..200); rb.insert(500); rb.insert(501); // contains_range: empty range always returns true assert!(rb.contains_range(7..7)); assert!(rb.contains_range(100..200)); assert!(!rb.contains_range(99..200)); // 99 is missing // range_cardinality: count without allocating a new bitmap assert_eq!(rb.range_cardinality(0..100), 0); assert_eq!(rb.range_cardinality(100..200), 100); assert_eq!(rb.range_cardinality(100..=500), 101); // 100 values + 500 assert_eq!(rb.range_cardinality(490..510), 2); // only 500, 501 ``` -------------------------------- ### Optimized Multi-Way Set Operations with MultiOps Source: https://context7.com/roaringbitmap/roaring-rs/llms.txt The `MultiOps` trait provides optimized multi-way union, intersection, difference, and symmetric difference over iterators of bitmaps. This is significantly faster than chaining pairwise operations. It supports cloning bitmaps, references, and fallible iterators (e.g., `Result`). ```rust use roaring::{MultiOps, RoaringBitmap}; let bitmaps = [ RoaringBitmap::from_iter(0..10), RoaringBitmap::from_iter(5..15), RoaringBitmap::from_iter(10..20), ]; // Multi-way union (faster than fold with |) let union = bitmaps.clone().union(); assert_eq!(union.min(), Some(0)); assert_eq!(union.max(), Some(19)); assert_eq!(union.len(), 20); // Multi-way intersection let inter = bitmaps.clone().intersection(); assert!(inter.is_empty()); // no value in all three // Multi-way difference (first minus all others) let diff = bitmaps.clone().difference(); assert_eq!(diff.iter().collect::>(), vec![0, 1, 2, 3, 4]); // Works with references too (avoids cloning) let refs = [&bitmaps[0], &bitmaps[1], &bitmaps[2]]; let union_ref = refs.union(); assert_eq!(union_ref.len(), 20); // Also works with Result iterators (for fallible sources) use core::convert::Infallible; let results = bitmaps.map(Ok::<_, Infallible>); let union_try = results.union().unwrap(); assert_eq!(union_try.len(), 20); ``` -------------------------------- ### RoaringBitmap::insert_range / RoaringBitmap::remove_range Source: https://context7.com/roaringbitmap/roaring-rs/llms.txt Efficiently inserts or removes a contiguous range of u32 values, handling container boundaries. ```APIDOC ## RoaringBitmap::insert_range / RoaringBitmap::remove_range ### Description Efficiently inserts or removes a contiguous range of `u32` values, crossing container boundaries as needed. Returns the count of values actually added or removed. ### Method - `insert_range(range: impl RangeBounds) -> u64` - `remove_range(range: impl RangeBounds) -> u64` ### Usage ```rust use roaring::RoaringBitmap; let mut rb = RoaringBitmap::new(); let added = rb.insert_range(10..20); assert_eq!(added, 10); assert!(rb.contains(10)); assert!(rb.contains(19)); assert!(!rb.contains(20)); // Range can span multiple internal containers (>= 65536 values) let mut big = RoaringBitmap::new(); let added = big.insert_range(0..(1_u32 << 16) + 5); // 65541 values assert_eq!(added, 65541); // remove_range returns the count of removed values let removed = rb.remove_range(12..15); assert_eq!(removed, 3); assert!(!rb.contains(12)); assert!(rb.contains(10)); // still present ``` ``` -------------------------------- ### RoaringBitmap::contains_range / RoaringBitmap::range_cardinality Source: https://context7.com/roaringbitmap/roaring-rs/llms.txt Checks if all values in a range are present and counts values within a specified range. ```APIDOC ## RoaringBitmap::contains_range / RoaringBitmap::range_cardinality ### Description Tests whether every value in a range is present, and counts values within an arbitrary range without materializing the result. ### Method - `contains_range(range: impl RangeBounds) -> bool` - `range_cardinality(range: impl RangeBounds) -> u64` ### Usage ```rust use roaring::RoaringBitmap; let mut rb = RoaringBitmap::new(); rb.insert_range(100..200); rb.insert(500); rb.insert(501); // contains_range: empty range always returns true assert!(rb.contains_range(7..7)); assert!(rb.contains_range(100..200)); assert!(!rb.contains_range(99..200)); // 99 is missing // range_cardinality: count without allocating a new bitmap assert_eq!(rb.range_cardinality(0..100), 0); assert_eq!(rb.range_cardinality(100..200), 100); assert_eq!(rb.range_cardinality(100..=500), 101); // 100 values + 500 assert_eq!(rb.range_cardinality(490..510), 2); // only 500, 501 ``` ```