### Initialize RangeInclusiveMap with macro Source: https://docs.rs/rangemap/1.7.1/rangemap/macro.range_inclusive_map.html Example usage of the range_inclusive_map macro to create a map with inclusive ranges. ```rust let map = range_inclusive_map!{ 0..=100 => "abc", 100..=200 => "def", 200..=300 => "ghi" }; ``` -------------------------------- ### RangeInclusiveStartWrapper Implementation Source: https://docs.rs/rangemap/1.7.1/src/rangemap/range_wrapper.rs.html Wraps an inclusive range to allow ordering by the start value. ```rust #[derive(Eq, Debug, Clone)] pub struct RangeInclusiveStartWrapper { pub end_wrapper: RangeInclusiveEndWrapper, } impl RangeInclusiveStartWrapper { pub fn new(range: RangeInclusive) -> RangeInclusiveStartWrapper { RangeInclusiveStartWrapper { end_wrapper: RangeInclusiveEndWrapper::new(range), } } } impl PartialEq for RangeInclusiveStartWrapper where T: PartialEq, { fn eq(&self, other: &RangeInclusiveStartWrapper) -> bool { self.start() == other.start() } } impl Ord for RangeInclusiveStartWrapper where T: Ord, { fn cmp(&self, other: &RangeInclusiveStartWrapper) -> Ordering { self.start().cmp(other.start()) } } ``` -------------------------------- ### Example Usage of range_map Macro Source: https://docs.rs/rangemap/1.7.1/rangemap/macro.range_map.html Demonstrates how to use the `range_map` macro to create a `RangeMap` with several key-value pairs. Each key is a range and each value is a string. ```rust let map = range_map!{ 0..100 => "abc", 100..200 => "def", 200..300 => "ghi" }; ``` -------------------------------- ### Initialize RangeInclusiveSet Source: https://docs.rs/rangemap/1.7.1/rangemap/macro.range_inclusive_set.html Example usage of the range_inclusive_set macro to create a set with multiple inclusive ranges. ```rust let set = range_inclusive_set![0..=100, 200..=300, 400..=500]; ``` -------------------------------- ### RangeStartWrapper Implementation Source: https://docs.rs/rangemap/1.7.1/src/rangemap/range_wrapper.rs.html Wraps a range to allow ordering by the start value. Implements Borrow and Deref to facilitate access to the inner RangeEndWrapper. ```rust use core::cmp::Ordering; use core::ops::{Deref, Range, RangeInclusive}; #[derive(Debug, Clone)] pub struct RangeStartWrapper { pub end_wrapper: RangeEndWrapper, } impl RangeStartWrapper { pub fn new(range: Range) -> RangeStartWrapper { RangeStartWrapper { end_wrapper: RangeEndWrapper::new(range), } } } impl PartialEq for RangeStartWrapper where T: PartialEq, { fn eq(&self, other: &RangeStartWrapper) -> bool { self.start == other.start } } impl Eq for RangeStartWrapper where T: Eq {} impl Ord for RangeStartWrapper where T: Ord, { fn cmp(&self, other: &RangeStartWrapper) -> Ordering { self.start.cmp(&other.start) } } impl PartialOrd for RangeStartWrapper where T: PartialOrd, { fn partial_cmp(&self, other: &RangeStartWrapper) -> Option { self.start.partial_cmp(&other.start) } } impl core::borrow::Borrow> for RangeStartWrapper { fn borrow(&self) -> &RangeEndWrapper { &self.end_wrapper } } impl Deref for RangeStartWrapper { type Target = RangeEndWrapper; fn deref(&self) -> &Self::Target { &self.end_wrapper } } ``` -------------------------------- ### Test item starting at start of outer range Source: https://docs.rs/rangemap/1.7.1/src/rangemap/map.rs.html Verifies that gaps are correctly identified when an item starts exactly at the beginning of the outer range. ```rust #[test] fn item_starting_at_start_of_outer_range() { let mut range_map: RangeMap = RangeMap::new(); // 0 1 2 3 4 5 6 7 8 9 // ◌ ◌ ◌ ◌ ◌ ●-◌ ◌ ◌ ◌ range_map.insert(5..6, ()); // 0 1 2 3 4 5 6 7 8 9 // ◌ ◌ ◌ ◌ ◌ ◆-----◇ ◌ let outer_range = 5..8; let mut gaps = range_map.gaps(&outer_range); // Should yield from the item onwards. assert_eq!(gaps.next(), Some(6..8)); assert_eq!(gaps.next(), None); // Gaps iterator should be fused. assert_eq!(gaps.next(), None); assert_eq!(gaps.next(), None); } ``` -------------------------------- ### Proptest: Test RangeSet first() Source: https://docs.rs/rangemap/1.7.1/src/rangemap/set.rs.html Tests the `first()` method of RangeSet against the result of iterating and finding the minimum by start key. ```rust #[proptest] fn test_first(set: RangeSet) { assert_eq!(set.first(), set.iter().min_by_key(|range| range.start)); } ``` -------------------------------- ### PartialOrd for RangeInclusiveStartWrapper Source: https://docs.rs/rangemap/1.7.1/src/rangemap/range_wrapper.rs.html Implements partial comparison for RangeInclusiveStartWrapper based on its start value. Requires the inner type T to implement PartialOrd. ```rust impl PartialOrd for RangeInclusiveStartWrapper where T: PartialOrd, { fn partial_cmp(&self, other: &RangeInclusiveStartWrapper) -> Option { self.start().partial_cmp(other.start()) } } ``` -------------------------------- ### RangeMap Gaps: No Empty Gaps Between Adjacent Items Source: https://docs.rs/rangemap/1.7.1/src/rangemap/map.rs.html This example shows that `range_map.gaps` correctly identifies gaps at the start and end of the `outer_range` but does not create a gap between two adjacent items that are mapped. The iterator is fused. ```rust let mut range_map: RangeMap = RangeMap::new(); range_map.insert(4..5, true); range_map.insert(3..4, false); let outer_range = 1..8; let mut gaps = range_map.gaps(&outer_range); assert_eq!(gaps.next(), Some(1..3)); assert_eq!(gaps.next(), Some(5..8)); assert_eq!(gaps.next(), None); assert_eq!(gaps.next(), None); assert_eq!(gaps.next(), None); ``` -------------------------------- ### RangeSet Initialization and Basic Operations Source: https://docs.rs/rangemap/1.7.1/src/rangemap/set.rs.html Provides documentation for creating and managing RangeSet instances, including checking for emptiness and clearing the set. ```APIDOC ## RangeSet Initialization and Basic Operations ### Description This section covers the creation of new `RangeSet` instances and fundamental operations like checking if the set is empty and clearing all elements. ### Methods #### `new()` - **Description**: Creates a new, empty `RangeSet`. - **Usage**: `RangeSet::new()` #### `clear()` - **Description**: Removes all ranges from the `RangeSet`, making it empty. - **Usage**: `rangeset.clear()` #### `len()` - **Description**: Returns the number of disjoint ranges currently stored in the `RangeSet`. - **Usage**: `rangeset.len()` #### `is_empty()` - **Description**: Returns `true` if the `RangeSet` contains no ranges, and `false` otherwise. - **Usage**: `rangeset.is_empty()` ### Request Example ```rust let mut rs: RangeSet = RangeSet::new(); println!("Is empty: {}", rs.is_empty()); // Output: Is empty: true rs.insert(1..5); println!("Is empty: {}", rs.is_empty()); // Output: Is empty: false println!("Length: {}", rs.len()); // Output: Length: 1 rs.clear(); println!("Is empty: {}", rs.is_empty()); // Output: Is empty: true ``` ### Response - **`new()`**: Returns a new `RangeSet`. - **`clear()`**: Modifies the `RangeSet` in place. - **`len()`**: Returns `usize`. - **`is_empty()`**: Returns `bool`. ``` -------------------------------- ### Get Key-Value Pair by Key in RangeInclusiveMap Source: https://docs.rs/rangemap/1.7.1/src/rangemap/inclusive_map.rs.html Returns the range and value corresponding to a given key, if the key is covered by any range in the map. It searches for the last stored range whose start is less than or equal to the key. ```rust pub fn get_key_value(&self, key: &K) -> Option<(&RangeInclusive, &V)> { use core::ops::Bound; // The only stored range that could contain the given key is the // last stored range whose start is less than or equal to this key. let key_as_start = RangeInclusiveStartWrapper::new(key.clone()..=key.clone()); self.btm .range((Bound::Unbounded, Bound::Included(key_as_start))) .next_back() .filter(|(range_start_wrapper, _value)| { // Does the only candidate range contain // the requested key? range_start_wrapper.contains(key) }) .map(|(range_start_wrapper, value)| (&range_start_wrapper.range, value)) ``` -------------------------------- ### Initialize and Populate RangeMap with Chrono Source: https://docs.rs/rangemap/1.7.1/src/rangemap/lib.rs.html Demonstrates initializing a RangeMap and populating it with time-based ranges using the Chrono crate. Useful for scheduling or time-based assignments. ```rust use chrono::offset::TimeZone; use chrono::{Duration, Utc}; use rangemap::RangeMap; let people = ["Alice", "Bob", "Carol"]; let mut roster = RangeMap::new(); // Set up initial roster. let start_of_roster = Utc.ymd(2019, 1, 7); let mut week_start = start_of_roster; for _ in 0..3 { for person in &people { let next_week = week_start + Duration::weeks(1); roster.insert(week_start..next_week, person); week_start = next_week; } } // Bob is covering Alice's second shift (the fourth shift overall). let fourth_shift_start = start_of_roster + Duration::weeks(3); let fourth_shift_end = fourth_shift_start + Duration::weeks(1); roster.insert(fourth_shift_start..fourth_shift_end, &"Bob"); for (range, person) in roster.iter() { println!("{} ({}) {}", range.start, range.end - range.start, person); } ``` -------------------------------- ### Test Map Initialization Source: https://docs.rs/rangemap/1.7.1/src/rangemap/inclusive_map.rs.html Demonstrates creating a map from an array and using the range_inclusive_map macro. ```rust #[test] fn test_from_array() { let mut map = RangeInclusiveMap::new(); map.insert(0..=100, "hello"); map.insert(200..=300, "world"); assert_eq!( map, RangeInclusiveMap::from([(0..=100, "hello"), (200..=300, "world")]) ); } #[test] fn test_macro() { assert_eq!( range_inclusive_map![], RangeInclusiveMap::::default() ); assert_eq!( range_inclusive_map!(0..=100 => "abc", 100..=200 => "def", 200..=300 => "ghi"), [(0..=100, "abc"), (100..=200, "def"), (200..=300, "ghi")] .iter() .cloned() .collect(), ); } ``` -------------------------------- ### Range Map Gaps Test: Item Starting at Start of Outer Range Source: https://docs.rs/rangemap/1.7.1/src/rangemap/inclusive_map.rs.html Tests the `gaps` method when an entry starts exactly at the beginning of the outer range. The gap should start immediately after the end of this entry, and the iterator should be fused. ```rust let mut range_map: RangeInclusiveMap = RangeInclusiveMap::new(); range_map.insert(5..=6, ()); let outer_range = 5..=8; let mut gaps = range_map.gaps(&outer_range); assert_eq!(gaps.next(), Some(7..=8)); assert_eq!(gaps.next(), None); assert_eq!(gaps.next(), None); ``` -------------------------------- ### Range Map Gaps Test: Item Overlapping Start of Outer Range Source: https://docs.rs/rangemap/1.7.1/src/rangemap/inclusive_map.rs.html Tests the `gaps` method when an entry overlaps the start of the outer range. The gap should start immediately after the end of the overlapping entry, and the iterator should be fused. ```rust let mut range_map: RangeInclusiveMap = RangeInclusiveMap::new(); range_map.insert(1..=5, ()); let outer_range = 5..=8; let mut gaps = range_map.gaps(&outer_range); assert_eq!(gaps.next(), Some(6..=8)); assert_eq!(gaps.next(), None); assert_eq!(gaps.next(), None); assert_eq!(gaps.next(), None); ``` -------------------------------- ### Test RangeMap Initialization Source: https://docs.rs/rangemap/1.7.1/src/rangemap/map.rs.html Demonstrates creating a RangeMap from an array and using the range_map! macro. ```rust #[test] fn test_from_array() { let mut map = RangeMap::new(); map.insert(0..100, "hello"); map.insert(200..300, "world"); assert_eq!( map, RangeMap::from([(0..100, "hello"), (200..300, "world")]) ); } #[test] fn test_macro() { assert_eq!(range_map![], RangeMap::::default()); assert_eq!( range_map!(0..100 => "abc", 100..200 => "def", 200..300 => "ghi"), [(0..100, "abc"), (100..200, "def"), (200..300, "ghi")] .iter() .cloned() .collect(), ); } ``` -------------------------------- ### clone_to_uninit Source: https://docs.rs/rangemap/1.7.1/rangemap/inclusive_set/struct.RangeInclusiveSet.html This is a nightly-only experimental API. It performs copy-assignment from self to dest. ```APIDOC ## unsafe fn clone_to_uninit(&self, dest: *mut u8) ### Description Performs copy-assignment from `self` to `dest`. ### Method `unsafe fn` ### Endpoint N/A (Method implementation) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response None ### Error Handling None ``` -------------------------------- ### Test overlapping start of outer range Source: https://docs.rs/rangemap/1.7.1/src/rangemap/map.rs.html Verifies that gaps are correctly identified when an item overlaps the start of the outer range. ```rust #[test] fn item_overlapping_start_of_outer_range() { let mut range_map: RangeMap = RangeMap::new(); // 0 1 2 3 4 5 6 7 8 9 // ◌ ●---------◌ ◌ ◌ ◌ range_map.insert(1..6, ()); // 0 1 2 3 4 5 6 7 8 9 // ◌ ◌ ◌ ◌ ◌ ◆-----◇ ◌ let outer_range = 5..8; let mut gaps = range_map.gaps(&outer_range); // Should yield from the end of the stored item // to the end of the outer range. assert_eq!(gaps.next(), Some(6..8)); assert_eq!(gaps.next(), None); // Gaps iterator should be fused. assert_eq!(gaps.next(), None); assert_eq!(gaps.next(), None); } ``` -------------------------------- ### Initialize RangeSet with macro Source: https://docs.rs/rangemap/1.7.1/rangemap/macro.range_set.html Create a new RangeSet instance using the range_set macro with multiple range inputs. ```rust let set = range_set![0..100, 200..300, 400..500]; ``` -------------------------------- ### Test Range Map Get Operation Source: https://docs.rs/rangemap/1.7.1/src/rangemap/inclusive_map.rs.html Verifies the 'get' method for retrieving a value associated with a specific key within the map. Checks for existing and non-existing keys. ```rust fn get() { let mut range_map: RangeInclusiveMap = RangeInclusiveMap::new(); range_map.insert(0..=50, false); assert_eq!(range_map.get(&50), Some(&false)); assert_eq!(range_map.get(&51), None); } ``` -------------------------------- ### Manage schedules with RangeMap and Chrono Source: https://docs.rs/rangemap/1.7.1/rangemap/index.html Demonstrates using RangeMap to manage time-based shifts, showing how overlapping or contiguous ranges are coalesced. ```rust use chrono::offset::TimeZone; use chrono::{Duration, Utc}; use rangemap::RangeMap; let people = ["Alice", "Bob", "Carol"]; let mut roster = RangeMap::new(); // Set up initial roster. let start_of_roster = Utc.ymd(2019, 1, 7); let mut week_start = start_of_roster; for _ in 0..3 { for person in &people { let next_week = week_start + Duration::weeks(1); roster.insert(week_start..next_week, person); week_start = next_week; } } // Bob is covering Alice's second shift (the fourth shift overall). let fourth_shift_start = start_of_roster + Duration::weeks(3); let fourth_shift_end = fourth_shift_start + Duration::weeks(1); roster.insert(fourth_shift_start..fourth_shift_end, &"Bob"); for (range, person) in roster.iter() { println!("{} ({}): {}", range.start, range.end - range.start, person); } // Output: // 2019-01-07UTC (P7D): Alice // 2019-01-14UTC (P7D): Bob // 2019-01-21UTC (P7D): Carol // 2019-01-28UTC (P14D): Bob // 2019-02-11UTC (P7D): Carol // 2019-02-18UTC (P7D): Alice // 2019-02-25UTC (P7D): Bob // 2019-03-04UTC (P7D): Carol ``` -------------------------------- ### Range Map Gaps Test: Item Touching Start of Outer Range Source: https://docs.rs/rangemap/1.7.1/src/rangemap/inclusive_map.rs.html Tests the `gaps` method when an entry in the map touches the start of the outer range. The entire outer range should be reported as a gap, and the iterator should be fused. ```rust let mut range_map: RangeInclusiveMap = RangeInclusiveMap::new(); range_map.insert(1..=4, ()); let outer_range = 5..=8; let mut gaps = range_map.gaps(&outer_range); assert_eq!(gaps.next(), Some(5..=8)); assert_eq!(gaps.next(), None); assert_eq!(gaps.next(), None); assert_eq!(gaps.next(), None); ``` -------------------------------- ### Macros Source: https://docs.rs/rangemap/1.7.1/rangemap/index.html Macros for initializing range-based data structures. ```APIDOC ## Macros ### range_inclusive_map Create a `RangeInclusiveMap` from key-value pairs. ### range_inclusive_set Create a `RangeInclusiveSet` from a list of ranges. ### range_map Create a `RangeMap` from key-value pairs. ### range_set Create a `RangeSet` from a list of ranges. ``` -------------------------------- ### Handle Overlapping or Following Stored Ranges Source: https://docs.rs/rangemap/1.7.1/src/rangemap/inclusive_map.rs.html Iterates through stored ranges that start after the new range's start and potentially overlap or immediately follow its end. Includes logic to break early if ranges are irrelevant or do not merge. ```rust let second_last_possible_start = new_range_start_wrapper.end().clone(); let second_last_possible_start = RangeInclusiveStartWrapper::new( second_last_possible_start.clone()..=second_last_possible_start, ); while let Some((stored_range_start_wrapper, stored_value)) = self .btm .range::, ( Bound<&RangeInclusiveStartWrapper>, Bound<&RangeInclusiveStartWrapper>, )>(( Bound::Included(&new_range_start_wrapper), // We would use something like `Bound::Included(&last_possible_start)`, // but making `last_possible_start` might cause arithmetic overflow; // instead decide inside the loop whether we've gone too far and break. Bound::Unbounded, )) .next() { // A couple of extra exceptions are needed at the // end of the subset of stored ranges we want to consider, // in part because we use `Bound::Unbounded` above. // (See comments up there, and in the individual cases below.) let stored_start = stored_range_start_wrapper.start(); if *stored_start > *second_last_possible_start.start() { let latest_possible_start = StepFnsT::add_one(second_last_possible_start.start()); if *stored_start > latest_possible_start { // We're beyond the last stored range that could be relevant. // Avoid wasting time on irrelevant ranges, or even worse, looping forever. // (`adjust_touching_ranges_for_insert` below assumes that the given range // is relevant, and behaves very poorly if it is handed a range that it // shouldn't be touching.) break; } if *stored_start == latest_possible_start && *stored_value != new_value { // We are looking at the last stored range that could be relevant, // but it has a different value, so we don't want to merge with it. // We must explicitly break here as well, because `adjust_touching_ranges_for_insert` // below assumes that the given range is relevant, and behaves very poorly if it // is handed a range that it shouldn't be touching. break; } } let stored_range_start_wrapper = stored_range_start_wrapper.clone(); } ``` -------------------------------- ### Min/Max and Aggregation Methods Source: https://docs.rs/rangemap/1.7.1/rangemap/inclusive_map/struct.Iter.html Methods for finding extreme values or calculating sums and products. ```APIDOC ## fn max(self) -> Option ### Description Returns the maximum element of an iterator. ## fn min(self) -> Option ### Description Returns the minimum element of an iterator. ## fn sum(self) -> S ### Description Sums the elements of an iterator. ## fn product

(self) -> P ### Description Iterates over the entire iterator, multiplying all the elements. ``` -------------------------------- ### Deserialize RangeSet Source: https://docs.rs/rangemap/1.7.1/src/rangemap/set.rs.html Implements deserialization for RangeSet from a sequence of start and end pairs. ```rust impl<'de, T> Deserialize<'de> for RangeSet where T: Ord + Clone + Deserialize<'de>, { type Value = RangeSet; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("RangeSet") } fn visit_seq(self, mut access: A) -> Result where A: SeqAccess<'de>, { let mut range_set = RangeSet::new(); while let Some((start, end)) = access.next_element()? { range_set.insert(start..end); } Ok(range_set) } } ``` -------------------------------- ### In-place Partitioning and Checking Source: https://docs.rs/rangemap/1.7.1/rangemap/inclusive_set/struct.Iter.html Methods for in-place reordering and checking the partitioned state of an iterator. ```APIDOC ## Iterator Adapters: In-place Partitioning ### Description These methods operate on iterators that yield mutable references, allowing for in-place reordering and checking of partitioned elements. ### Methods - `partition_in_place<'a, T, P>(predicate)` - `is_partitioned

(predicate)` ### Endpoint N/A (Methods on Iterator trait) ### Parameters - `predicate`: A closure that takes a reference to an item and returns a boolean. ### Request Example N/A ### Response #### Success Response (200) - `partition_in_place`: The number of elements satisfying the predicate (`usize`). - `is_partitioned`: A boolean indicating if the iterator is partitioned. #### Response Example N/A ``` -------------------------------- ### Get Set Size Source: https://docs.rs/rangemap/1.7.1/src/rangemap/inclusive_set.rs.html Returns the number of distinct ranges currently stored in the set. ```rust impl RangeInclusiveSet where T: Ord + Clone, StepFnsT: StepFns, { /// Returns the number of elements in the set. pub fn len(&self) -> usize { self.rm.len() } } ``` -------------------------------- ### DoubleEndedIterator::rfold Implementation Source: https://docs.rs/rangemap/1.7.1/rangemap/inclusive_map/struct.Iter.html Reduces the iterator's elements to a single value, starting from the back. ```rust fn rfold(self, init: B, f: F) -> B ``` -------------------------------- ### Use Rangemap with Chrono for Scheduling Source: https://docs.rs/rangemap/1.7.1/index.html Demonstrates using RangeMap with Chrono to manage a weekly roster, including setting initial shifts and reassigning a shift. Requires the 'chrono' crate. ```rust use chrono::offset::TimeZone; use chrono::{Duration, Utc}; use rangemap::RangeMap; let people = ["Alice", "Bob", "Carol"]; let mut roster = RangeMap::new(); // Set up initial roster. let start_of_roster = Utc.ymd(2019, 1, 7); let mut week_start = start_of_roster; for _ in 0..3 { for person in &people { let next_week = week_start + Duration::weeks(1); roster.insert(week_start..next_week, person); week_start = next_week; } } // Bob is covering Alice's second shift (the fourth shift overall). let fourth_shift_start = start_of_roster + Duration::weeks(3); let fourth_shift_end = fourth_shift_start + Duration::weeks(1); roster.insert(fourth_shift_start..fourth_shift_end, &"Bob"); for (range, person) in roster.iter() { println!("{} ({}): {}", range.start, range.end - range.start, person); } // Output: // 2019-01-07UTC (P7D): Alice // 2019-01-14UTC (P7D): Bob // 2019-01-21UTC (P7D): Carol // 2019-01-28UTC (P14D): Bob // 2019-02-11UTC (P7D): Carol // 2019-02-18UTC (P7D): Alice // 2019-02-25UTC (P7D): Bob // 2019-03-04UTC (P7D): Carol ``` -------------------------------- ### Test RangeSet Initialization Source: https://docs.rs/rangemap/1.7.1/src/rangemap/set.rs.html Tests creating a RangeSet from arrays or macros. ```rust #[test] fn test_from_array() { let mut set = RangeSet::new(); set.insert(0..100); set.insert(200..300); assert_eq!(set, RangeSet::from([0..100, 200..300])); } ``` ```rust #[test] fn test_macro() { assert_eq!(range_set![], RangeSet::::new()); assert_eq!( range_set![0..100, 200..300, 400..500], [0..100, 200..300, 400..500].iter().cloned().collect(), ); } ``` -------------------------------- ### Implement QuickCheck Arbitrary for Testing Source: https://docs.rs/rangemap/1.7.1/src/rangemap/inclusive_map.rs.html Provides arbitrary generation for property-based testing when the quickcheck feature is enabled. ```rust #[cfg(feature = "quickcheck")] impl quickcheck::Arbitrary for RangeInclusiveMap where K: quickcheck::Arbitrary + Ord + StepLite, V: quickcheck::Arbitrary + PartialEq, { fn arbitrary(g: &mut quickcheck::Gen) -> Self { // REVISIT: allocation could be avoided if Gen::gen_size were public (https://github.com/BurntSushi/quickcheck/issues/326#issue-2653601170) , _)>>::arbitrary(g) .into_iter() .filter(|(range, _)| !range.is_empty()) .collect() } } ``` -------------------------------- ### Iterate Over Ranges Source: https://docs.rs/rangemap/1.7.1/src/rangemap/inclusive_set.rs.html Provides an ordered iterator over all ranges present in the set. The ranges are sorted by their start values. ```rust impl RangeInclusiveSet where T: Ord + Clone, StepFnsT: StepFns, { /// Gets an ordered iterator over all ranges, /// ordered by range. pub fn iter(&self) -> Iter<'_, T> { Iter { inner: self.rm.iter(), } } } ``` -------------------------------- ### Testing Utilities Source: https://docs.rs/rangemap/1.7.1/src/rangemap/set.rs.html Includes implementations for `Arbitrary` and test functions for various `RangeSet` functionalities. ```APIDOC ## Testing Utilities ### Description Provides testing utilities for `RangeSet`, including property-based testing. ### Arbitrary Implementation - `impl Arbitrary for RangeSet` where `T: Ord + Clone + Debug + Arbitrary + 'static` - Generates `Vec>` and filters out empty ranges to create a `RangeSet`. ### Test Functions - `test_first(set: RangeSet)`: Asserts that `set.first()` matches the minimum start of ranges. - `test_len(mut map: RangeSet)`: Asserts `len()` and `is_empty()` behavior, including after `clear()`. - `test_last(set: RangeSet)`: Asserts that `set.last()` matches the maximum end of ranges. - `test_iter_reversible(set: RangeSet)`: Tests the reversibility of the iterator. ``` -------------------------------- ### Get the Last Range Source: https://docs.rs/rangemap/1.7.1/src/rangemap/set.rs.html Retrieves the maximum range present in the `RangeSet`. Returns `None` if the set is empty. ```rust pub fn last(&self) -> Option<&Range> { self.rm.last_range_value().map(|(range, _)| range) } ``` -------------------------------- ### Get the First Range Source: https://docs.rs/rangemap/1.7.1/src/rangemap/set.rs.html Retrieves the minimum range present in the `RangeSet`. Returns `None` if the set is empty. ```rust pub fn first(&self) -> Option<&Range> { self.rm.first_range_value().map(|(range, _)| range) } ``` -------------------------------- ### RangeSet Creation from Iterator Source: https://docs.rs/rangemap/1.7.1/rangemap/set/struct.RangeSet.html Demonstrates how to create a RangeSet from an iterator of Ranges. ```APIDOC ## FromIterator> for RangeSet ### Description Creates a `RangeSet` from an iterator yielding `Range` items. ### Method `from_iter` ### Parameters - `iter` (I: IntoIterator>) - The iterator providing the ranges. ### Request Example ```rust let ranges = vec![0..5, 10..15]; let range_set: RangeSet = ranges.into_iter().collect(); ``` ### Response #### Success Response (200) - `RangeSet` - A new RangeSet containing the elements from the iterator. ``` -------------------------------- ### Get Range Containing Value Source: https://docs.rs/rangemap/1.7.1/src/rangemap/inclusive_set.rs.html Retrieves a reference to the range that includes the specified value, if such a range exists in the set. ```rust impl RangeInclusiveSet where T: Ord + Clone, StepFnsT: StepFns, { /// Returns a reference to the range covering the given key, if any. pub fn get(&self, value: &T) -> Option<&RangeInclusive> { self.rm.get_key_value(value).map(|(range, _)| range) } } ``` -------------------------------- ### Min/Max and Transformation Methods Source: https://docs.rs/rangemap/1.7.1/rangemap/map/struct.Iter.html Methods for finding extrema and transforming iterator contents. ```APIDOC ## max / min ### Description Returns the maximum or minimum element of an iterator. ## max_by / min_by ### Description Returns the element that gives the max/min value based on a comparison function. ## rev ### Description Reverses the iterator direction. ## unzip ### Description Converts an iterator of pairs into a pair of containers. ## copied / cloned ### Description Creates an iterator that copies or clones all elements. ``` -------------------------------- ### Get Type ID of Self Source: https://docs.rs/rangemap/1.7.1/rangemap/inclusive_map/struct.Gaps.html The `type_id` method returns the `TypeId` of the current type. This is part of the `Any` trait implementation. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Initialize RangeInclusiveSet with macro Source: https://docs.rs/rangemap/1.7.1/src/rangemap/inclusive_set.rs.html Uses the range_inclusive_set! macro to initialize sets. ```rust #[test] fn test_macro() { assert_eq!(range_inclusive_set![], RangeInclusiveSet::::default()); assert_eq!( range_inclusive_set![0..=100, 200..=300, 400..=500], [0..=100, 200..=300, 400..=500].iter().cloned().collect(), ); } ``` -------------------------------- ### RangeInclusiveSet - Querying Source: https://docs.rs/rangemap/1.7.1/rangemap/inclusive_set/struct.RangeInclusiveSet.html Methods for querying the set, such as checking for containment, getting specific ranges, and finding overlapping ranges. ```APIDOC ## RangeInclusiveSet - Querying ### `get(value: &T)` Returns a reference to the range that covers the given `value`, if any. **Signature:** ```rust pub fn get(&self, value: &T) -> Option<&RangeInclusive> ``` ### `contains(value: &T)` Returns `true` if any range in the set covers the specified `value`. **Signature:** ```rust pub fn contains(&self, value: &T) -> bool ``` ### `overlaps(range: &RangeInclusive)` Returns `true` if any range in the set completely or partially overlaps the given `range`. **Signature:** ```rust pub fn overlaps(&self, range: &RangeInclusive) -> bool ``` ### `first()` Returns the first (minimum) range in the set, if one exists. **Signature:** ```rust pub fn first(&self) -> Option<&RangeInclusive> ``` ### `last()` Returns the last (maximum) range in the set, if one exists. **Signature:** ```rust pub fn last(&self) -> Option<&RangeInclusive> ``` ``` -------------------------------- ### Test Removing Non-Covered Range After Stored Range Source: https://docs.rs/rangemap/1.7.1/src/rangemap/inclusive_map.rs.html Confirms that removing a range that starts after any stored range does not alter the map. ```rust fn remove_non_covered_range_after_stored() { let mut range_map: RangeInclusiveMap = RangeInclusiveMap::new(); range_map.insert(25..=75, false); range_map.remove(76..=100); assert_eq!(range_map.to_vec(), vec![(25..=75, false)]); } ``` -------------------------------- ### RangeSet Querying Source: https://docs.rs/rangemap/1.7.1/src/rangemap/set.rs.html Documentation for querying the RangeSet, including checking for containment, retrieving specific ranges, and iterating over gaps. ```APIDOC ## RangeSet Querying ### Description This section details how to query a `RangeSet` to check for the presence of values, retrieve covering ranges, and identify gaps. ### Methods #### `get(value: &T) -> Option<&Range>` - **Description**: Returns a reference to the range that covers the given `value`, if such a range exists in the set. - **Parameters**: - **value** (`&T`) - Required - The value to check for. - **Returns**: `Some(&Range)` if a covering range is found, `None` otherwise. #### `contains(value: &T) -> bool` - **Description**: Returns `true` if any range in the set covers the specified `value`, and `false` otherwise. - **Parameters**: - **value** (`&T`) - Required - The value to check for. - **Returns**: `bool` indicating if the value is contained within any range. #### `gaps<'a>(outer_range: &'a Range) -> Gaps<'a, T>` - **Description**: Returns an iterator over all maximally-sized ranges within `outer_range` that are *not* covered by any range in the set. If `outer_range` itself is not covered, it will be yielded as a single gap. - **Parameters**: - **outer_range** (`&'a Range`) - Required - The range within which to find gaps. - **Returns**: An iterator yielding `Range` representing the gaps. ### Request Example ```rust let mut rs: RangeSet = RangeSet::new(); rs.insert(10..20); rs.insert(30..40); println!("Contains 15: {}", rs.contains(&15)); // Output: Contains 15: true println!("Contains 25: {}", rs.contains(&25)); // Output: Contains 25: false if let Some(range) = rs.get(&12) { println!("Range for 12: {:?}", range); // Output: Range for 12: 10..20 } let gaps: Vec<_> = rs.gaps(&(5..45)).collect(); println!("Gaps in 5..45: {:?}", gaps); // Output: Gaps in 5..45: [5..10, 20..30, 40..45] ``` ### Response - **`get()`**: Returns `Option<&Range>`. - **`contains()`**: Returns `bool`. - **`gaps()`**: Returns an iterator `Gaps<'a, T>`. ``` -------------------------------- ### Module inclusive_set Source: https://docs.rs/rangemap/1.7.1/rangemap/inclusive_set/index.html Documentation for the inclusive_set module within the rangemap crate. ```APIDOC ## Module inclusive_set ### Summary This module provides data structures for managing sets of inclusive ranges. ### Structs - **Gaps** An iterator over all ranges not covered by a `RangeInclusiveSet`. - **IntoIter** An owning iterator over the ranges of a `RangeInclusiveSet`. - **Iter** An iterator over the ranges of a `RangeInclusiveSet`. - **Overlapping** An iterator over all stored ranges partially or completely overlapped by a given range. - **RangeInclusiveSet** A set whose items are stored as ranges bounded inclusively below and above `(start..=end)`. ### Type Aliases - **Intersection** Intersection iterator over two `RangeInclusiveSet`. - **Union** Union iterator over two `RangeInclusiveSet`. ``` -------------------------------- ### By Reference Adapter Source: https://docs.rs/rangemap/1.7.1/rangemap/set/struct.Iter.html Creates a "by reference" adapter for an iterator. ```APIDOC ## fn by_ref(&mut self) -> &mut Self ### Description Creates a “by reference” adapter for this instance of `Iterator`. ### Method `by_ref` ### Endpoint N/A (Iterator method) ### Parameters None ### Request Example N/A ### Response N/A (Returns a mutable reference to the iterator) ### Version 1.0.0 ``` -------------------------------- ### DoubleEndedIterator::rfold Implementation Source: https://docs.rs/rangemap/1.7.1/rangemap/inclusive_set/struct.IntoIter.html Reduces the iterator's elements to a single value, starting from the back. Similar to `fold` but in reverse. ```rust fn rfold(self, init: B, f: F) where Self: Sized, F: FnMut(B, Self::Item) -> B ``` -------------------------------- ### DoubleEndedIterator::try_rfold Implementation Source: https://docs.rs/rangemap/1.7.1/rangemap/inclusive_set/struct.IntoIter.html A reverse version of `try_fold`. It takes elements starting from the back and applies a closure, short-circuiting on errors. ```rust fn try_rfold(&mut self, init: B, f: F) where Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try ``` -------------------------------- ### Const fn RangeSet Initialization Source: https://docs.rs/rangemap/1.7.1/src/rangemap/set.rs.html Demonstrates the ability to initialize a RangeSet using a const function. Requires the 'const_fn' feature. ```rust const _SET: RangeSet = RangeSet::new(); ``` -------------------------------- ### Test First Range Value Source: https://docs.rs/rangemap/1.7.1/src/rangemap/map.rs.html Property-based test to verify that `first_range_value()` returns the same result as iterating and finding the minimum by range start. ```rust #[proptest] fn test_first(set: RangeMap) { assert_eq!( set.first_range_value(), set.iter().min_by_key(|(range, _)| range.start) ); } ``` -------------------------------- ### Const fn Initialization Source: https://docs.rs/rangemap/1.7.1/src/rangemap/inclusive_map.rs.html Demonstrates the use of `const fn` for initializing `RangeInclusiveMap`. Shows initialization of an empty map and a map using custom step functions. ```rust const _MAP: RangeInclusiveMap = RangeInclusiveMap::new(); ``` ```rust const _MAP2: RangeInclusiveMap = RangeInclusiveMap::new_with_step_fns(); ``` -------------------------------- ### RangeSet Methods Source: https://docs.rs/rangemap/1.7.1/rangemap/set/struct.RangeSet.html This section covers the core methods available for the RangeSet struct, including creation, querying, modification, and iteration. ```APIDOC ## RangeSet ### Description A set whose items are stored as (half-open) ranges bounded inclusively below and exclusively above `(start..end)`. ### Methods #### `new()` - **Description**: Makes a new empty `RangeSet`. - **Method**: `pub fn new() -> Self` #### `get(value: &T)` - **Description**: Returns a reference to the range covering the given key, if any. - **Method**: `pub fn get(&self, value: &T) -> Option<&Range>` #### `contains(value: &T)` - **Description**: Returns `true` if any range in the set covers the specified value. - **Method**: `pub fn contains(&self, value: &T) -> bool` #### `iter()` - **Description**: Gets an ordered iterator over all ranges, ordered by range. - **Method**: `pub fn iter(&self) -> Iter<'_, T>` #### `clear()` - **Description**: Clears the set, removing all elements. - **Method**: `pub fn clear(&mut self)` #### `len()` - **Description**: Returns the number of elements in the set. - **Method**: `pub fn len(&self) -> usize` #### `is_empty()` - **Description**: Returns true if the set contains no elements. - **Method**: `pub fn is_empty(&self) -> bool` #### `intersection(other: &Self)` - **Description**: Returns an iterator over the intersection of two range sets. - **Method**: `pub fn intersection<'a>(&'a self, other: &'a Self) -> Intersection<'a, T>` #### `union(other: &Self)` - **Description**: Returns an iterator over the union of two range sets. - **Method**: `pub fn union<'a>(&'a self, other: &'a Self) -> Union<'a, T>` #### `insert(range: Range)` - **Description**: Inserts a range into the set. If the inserted range either overlaps or is immediately adjacent any existing range, then the ranges will be coalesced into a single contiguous range. - **Method**: `pub fn insert(&mut self, range: Range)` - **Panics**: Panics if range `start >= end`. #### `remove(range: Range)` - **Description**: Removes a range from the set, if all or any of it was present. If the range to be removed _partially_ overlaps any ranges in the set, then those ranges will be contracted to no longer cover the removed range. - **Method**: `pub fn remove(&mut self, range: Range)` - **Panics**: Panics if range `start >= end`. #### `gaps(outer_range: &Range)` - **Description**: Gets an iterator over all the maximally-sized ranges contained in `outer_range` that are not covered by any range stored in the set. If the start and end of the outer range are the same and it does not overlap any stored range, then a single empty gap will be returned. The iterator element type is `Range`. - **Method**: `pub fn gaps<'a>(&'a self, outer_range: &'a Range) -> Gaps<'a, T>` #### `overlapping(range: R)` - **Description**: Gets an iterator over all the stored ranges that are either partially or completely overlapped by the given range. The iterator element type is `&Range`. - **Method**: `pub fn overlapping>>( &self, range: R, ) -> Overlapping<'_, T, R>` #### `overlaps(range: &Range)` - **Description**: Returns `true` if any range in the set completely or partially overlaps the given range. - **Method**: `pub fn overlaps(&self, range: &Range) -> bool` #### `first()` - **Description**: Returns the first range in the set, if one exists. The range is the minimum range in this set. - **Method**: `pub fn first(&self) -> Option<&Range>` #### `last()` - **Description**: Returns the last range in the set, if one exists. The range is the maximum range in this set. - **Method**: `pub fn last(&self) -> Option<&Range>` ``` -------------------------------- ### Get Length of RangeInclusiveMap Source: https://docs.rs/rangemap/1.7.1/src/rangemap/inclusive_map.rs.html Returns the number of distinct ranges stored in the map. This count reflects the number of entries in the underlying BTreeMap. ```rust pub fn len(&self) -> usize { self.btm.len() } ``` -------------------------------- ### Enable serde1 feature in Cargo.toml Source: https://docs.rs/rangemap/1.7.1/rangemap/index.html Configuration to enable serialization support for rangemap types. ```toml [dependencies] rangemap = { version = "1", features = ["serde1"] } ``` -------------------------------- ### Check for Overlapping Ranges Source: https://docs.rs/rangemap/1.7.1/src/rangemap/set.rs.html Use the `overlapping` method to get an iterator over ranges that overlap with the given range. This is a precursor to checking if any overlap exists. ```rust pub fn overlapping>>(&'_ self, range: R) -> Overlapping<'_, T, R> { Overlapping { inner: self.rm.overlapping(range), } } ``` -------------------------------- ### product Source: https://docs.rs/rangemap/1.7.1/rangemap/set/struct.Gaps.html Iterates over the entire iterator, multiplying all the elements. ```APIDOC ## POST /api/product ### Description Iterates over the entire iterator, multiplying all the elements. ### Method POST ### Endpoint /api/product ### Response #### Success Response (200) - **total_product** (P) - The product of all elements in the iterator. #### Response Example ```json { "total_product": 120 } ``` ```