Struct SegmentMap

Source
pub struct SegmentMap<K, V> { /* private fields */ }
Expand description

§SegmentMap

A map of non-overlapping ranges to values. Inserted ranges will be merged with adjacent ranges if they have the same value.

Internally, SegmentMap is represented by a BTreeMap in which the keys are represented by a concrete [Range] type, sorted by their start values.

§Examples

TODO

§Entry API

TODO

Implementations§

Source§

impl<K, V> SegmentMap<K, V>

Source

pub fn len(&self) -> usize

Returns the number of ranges in the map.

§Examples

Basic usage:

use std::collections::BTreeMap;

let mut a = BTreeMap::new();
assert_eq!(a.len(), 0);
a.insert(1, "a");
assert_eq!(a.len(), 1);
Source

pub fn is_empty(&self) -> bool

Returns true if the map contains no ranges.

§Examples

Basic usage:

use std::collections::BTreeMap;

let mut a = BTreeMap::new();
assert!(a.is_empty());
a.insert(1, "a");
assert!(!a.is_empty());
Source

pub fn into_vec(self) -> Vec<(Segment<K>, V)>

Converts the map into a Vec by chaining [into_iter] and [collect]

Source

pub fn iter(&self) -> Iter<'_, K, V>

Gets an iterator over the sorted ranges in the map.

§Examples

Basic usage:

let mut map = SegmentMap::new();
map.insert(0..1, "a");
map.insert(1..2, "b");
map.insert(2..3, "c");

let (first_range, first_value) = map.iter().next().unwrap();
assert_eq!((*first_range, *first_value), (Segment::from(0..1), "a"));
Source

pub fn iter_in<R>(&self, range: R) -> IterIn<'_, K, V>
where R: RangeBounds<K>, K: Clone + Ord,

Gets an iterator over a subset of the sorted ranges in the map, bounded by range.

Source

pub fn iter_mut(&mut self) -> IterMut<'_, K, V>

Gets an iterator over the sorted ranges in the map, with mutable values

Ranges are used as keys and therefore cannot be mutable. To manipulate the bounds of stored ranges, they must be removed and re-inserted to ensure bound integrity.

§Examples

Basic usage:

use std::collections::BTreeMap;

let mut map = BTreeMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);

// add 10 to the value if the key isn't "a"
for (key, value) in map.iter_mut() {
    if key != &"a" {
        *value += 10;
    }
}
Source

pub fn ranges(&self) -> Ranges<'_, K, V>

Gets an iterator over the range keys of the map (similar to BTreeMap::keys())

§Examples

Basic usage:

use std::collections::BTreeMap;

let mut a = BTreeMap::new();
a.insert(2, "b");
a.insert(1, "a");

let keys: Vec<_> = a.keys().cloned().collect();
assert_eq!(keys, [1, 2]);
Source

pub fn values(&self) -> Values<'_, K, V>

Gets an iterator over the values of the map, in order by their range.

§Examples

Basic usage:

use std::collections::BTreeMap;

let mut a = BTreeMap::new();
a.insert(1, "hello");
a.insert(2, "goodbye");

let values: Vec<&str> = a.values().cloned().collect();
assert_eq!(values, ["hello", "goodbye"]);
Source

pub fn values_mut(&mut self) -> ValuesMut<'_, K, V>

Gets a mutable iterator over the values of the map, in order by their range.

§Examples

Basic usage:

use std::collections::BTreeMap;

let mut a = BTreeMap::new();
a.insert(1, String::from("hello"));
a.insert(2, String::from("goodbye"));

for value in a.values_mut() {
    value.push_str("!");
}

let values: Vec<String> = a.values().cloned().collect();
assert_eq!(values, [String::from("hello!"),
                    String::from("goodbye!")]);
Source

pub fn iter_subset<R>(&self, range: R) -> IterSubset<'_, K, V>
where R: RangeBounds<K>, K: Clone + Ord,

Source

pub fn subset<R>(&self, range: R) -> SegmentMap<K, &V>
where R: RangeBounds<K>, K: Clone + Ord,

Create a SegmentMap referencing a subset range in self

Source

pub fn iter_complement(&self) -> IterComplement<'_, K, V>

Source

pub fn complement(&self) -> SegmentSet<&K>
where K: Ord,

Source

pub fn iter_gaps(&self) -> Gaps<'_, K, V>

Gets an iterator over all maximally-sized gaps between ranges in the map

NOTE: Empty regions before and after those stored in this map (i.e. before the first range and after the last range) will not be included in this iterator

Source

pub fn gaps(&self) -> SegmentSet<&K>
where K: Ord,

Source§

impl<K, V> SegmentMap<K, V>

Source

pub fn new() -> SegmentMap<K, V>
where K: Ord,

Makes a new, empty SegmentMap.

Does not allocate anything on its own.

§Examples

Basic usage:

let mut map = SegmentMap::new();

// entries can now be inserted into the empty map
map.insert(0..1, "a");
Source

pub fn with_value(value: V) -> SegmentMap<K, V>
where K: Ord,

Makes a new, empty SegmentMap with a value for the full range.

§Examples

Basic usage:

let mut map = SegmentMap::with_value(true);

// All values will return something
assert_eq!(map[&0], true);
assert_eq!(map[&10], true);
assert_eq!(map[&12345678], true);
Source

pub fn clear(&mut self)

Clears the map, removing all elements.

This also resets the capacity of the internal store.

§Examples

Basic usage:

let mut a = SegmentMap::new();
a.insert(0..1, "a");
a.clear();
assert!(a.is_empty());
Source

pub fn shrink_to_fit(&mut self)

Resets the capacity of store

Source

pub fn get(&self, at: &K) -> Option<&V>
where K: Clone + Ord,

Returns a reference to the value corresponding to the given point, if the point is covered by any range in the map.

§Examples

Basic usage:

let mut map = SegmentMap::new();
map.insert(0..1, "a");
assert_eq!(map.get(&0), Some(&"a"));
assert_eq!(map.get(&2), None);
Source

pub fn get_range_value(&self, at: &K) -> Option<(&Segment<K>, &V)>
where K: Clone + Ord,

Returns the range-value pair (as a pair of references) corresponding to the given point, if the point is covered by any range in the map.

§Examples
let mut map = SegmentMap::new();
map.insert(0..1, "a");
assert_eq!(map.get_range_value(&0), Some((&Segment::from(0..1), &"a")));
assert_eq!(map.get_range_value(&2), None);
Source

pub fn contains(&self, point: &K) -> bool
where K: Clone + Ord,

Returns true if any range in the map covers the specified point.

§Examples

Basic usage:

let mut map = SegmentMap::new();
map.insert(0..1, "a");
assert_eq!(map.contains(&0), true);
assert_eq!(map.contains(&2), false);
Source

pub fn bounds(&self) -> Option<Segment<&K>>

Get the widest bounds covered by the ranges in this map

NOTE: This is not necessarily (or likely) a contiguous range!

§Examples
let mut map = SegmentMap::new();
map.insert(0..9, "a");
map.insert(15..30, "b");
map.insert(35..90, "c");

assert_eq!(map.bounds(), Some(Segment::from(0..90).as_ref()));
Source

pub fn lower_bound(&self) -> Option<&Bound<K>>

Get the lowest bound covered by the ranges in this map

§Examples
let mut map = SegmentMap::new();
map.insert(0..9, "a");
map.insert(15..30, "b");
map.insert(35..90, "c");

assert_eq!(map.lower_bound(), Some(&Bound::Included(0)));
Source

pub fn upper_bound(&self) -> Option<&Bound<K>>

Get the highest bound covered by the ranges in this map

§Examples
let mut map = SegmentMap::new();
map.insert(0..9, "a");
map.insert(15..30, "b");
map.insert(35..90, "c");

assert_eq!(map.upper_bound(), Some(&Bound::Excluded(90)));
Source

pub fn retain<F>(&mut self, f: F)
where K: Ord, F: FnMut(&Segment<K>, &mut V) -> bool,

Retains only the elements specified by the predicate.

In other words, remove all pairs (k, v) such that f(&k, &mut v) returns false.

§Examples
let mut map = SegmentMap::new();
map.set(0..5, true);
map.set(5..10, false);
map.set(10..15, true);
map.set(15..20, false);
map.set(20..25, true);

// Keep only the ranges with even numbered starts
map.retain(|k, _| k.start_value().unwrap() % 2 == 0);

assert!(map[&0] == true);
assert!(map[&10] == true);
assert!(map[&12] == true);
assert!(map[&20] == true);
assert!(map[&24] == true);

assert!(map.get(&15).is_none());
Source

pub fn insert<R>(&mut self, range: R, value: V) -> Option<SegmentMap<K, V>>
where R: RangeBounds<K>, K: Clone + Ord, V: Clone + Eq,

Insert a value for the specified range

If the inserted range completely overlaps any existing range in the map, the existing range (or ranges) will be replaced by the inserted range.

If the inserted range partially overlaps any existing range in the map, the existing ranges will be truncated to non-overlapping regions.

If the inserted range overlaps or is touching an existing range that maps to the same value, the ranges will be merged into one contiguous range

§Returns

Much like other maps (BTreeMap::insert or [HashMap::insert]), insert returns the overwritten values (if any existed). Because multiple ranges might be overwritten, another map will be constructed with those values.

Note: This will allocate a new underlying SegmentMap, though, so an option is used in case no ranges were overwritten. If you don’t care about the overwritten values, use [SegmentMap::set_range] instead.

§Examples
§Basic Usage
let mut map = SegmentMap::new();
map.insert(0..4, "a");
assert_eq!(map.is_empty(), false);

map.insert(2..6, "b");
assert_eq!(map[&1], "a");
assert_eq!(map[&3], "b");
§Overwriting
let mut map = SegmentMap::new();
map.insert(0..10, "a");
let out = map.insert(3..6, "b").unwrap();

assert_eq!(map[&2], "a");
assert_eq!(map[&4], "b");
assert_eq!(map[&7], "a");
assert!(out.into_iter().eq(vec![(Segment::from(3..6), "a")]));
§Coalescing
let mut map = SegmentMap::new();
map.insert(0..10, "a");
map.insert(10..20, "a");

assert!(map.into_iter().eq(vec![(Segment::from(0..20), "a")]));
§See Also
Source

pub fn set<R>(&mut self, range: R, value: V)
where R: RangeBounds<K>, K: Clone + Ord, V: Clone + Eq,

Set a value for the specified range, overwriting any existing subset ranges. This is the same as SegmentMap::insert, but without a return value, so overlapping ranges will be truncated and adjacent ranges with the same value will be merged.

§Examples
§Basic Usage
let mut map = SegmentMap::new();
map.set(0..4, "a");
assert_eq!(map.is_empty(), false);

map.set(2..6, "b");
assert_eq!(map[&1], "a");
assert_eq!(map[&3], "b");
§Overwriting
let mut map = SegmentMap::new();
map.set(0..10, "a");
map.set(3..6, "b");

assert_eq!(map[&2], "a");
assert_eq!(map[&4], "b");
assert_eq!(map[&7], "a");
§Coalescing
let mut map = SegmentMap::new();
map.set(0..10, "a");
map.set(10..20, "a");

assert!(map.into_iter().eq(vec![(Segment::from(0..20), "a")]))
§See Also
Source

pub fn insert_if_empty<R>(&mut self, range: R, value: V) -> Option<V>
where R: RangeBounds<K>, K: Clone + Ord, V: Clone + Eq,

Insert a value into the map, only if there are no existing overlapping ranges. Returns the given value if it wasn’t inserted.

§Examples
let mut map = SegmentMap::new();
assert!(map.insert_if_empty(0..5, true).is_none());
assert!(map.insert_if_empty(5..10, true).is_none());
assert!(map.insert_if_empty(3..6, true).is_some());
§See Also
Source

pub fn insert_in_gaps<R>(&mut self, range: R, value: V)
where R: RangeBounds<K>, K: Clone + Ord, V: Clone + Eq,

Insert a value for empty regions (gaps) in the specified range. If values exist for ranges overlapping this range, those values will be preserved. As such, this method may add multiple ranges for the given value.

§Examples
let mut map = SegmentMap::new();
map.set(5..10, "a");
map.set(15..20, "a");
map.insert_in_gaps(0..30, "b");

assert!(map.into_iter().eq(vec![
    (Segment::from(0..5), "b"),
    (Segment::from(5..10), "a"),
    (Segment::from(10..15), "b"),
    (Segment::from(15..20), "a"),
    (Segment::from(20..30), "b"),
]));
§See Also
Source

pub fn remove<R>(&mut self, range: R) -> Option<SegmentMap<K, V>>
where R: RangeBounds<K>, K: Clone + Ord, V: Clone,

Remove all values in a given range, returning the removed values. Overlapping ranges will be truncated at the bounds of this range.

Note: This will allocate another SegmentMap for returning the removed ranges, so if you don’t care about them, use SegmentMap::clear_range instead

§Examples
let mut map = SegmentMap::new();
map.insert(0..=10, 5);
let removed = map.remove(2..4).unwrap();

assert_eq!(map[&0], 5);
assert!(map.get(&2).is_none());
assert!(map.get(&3).is_none());
assert_eq!(map[&4], 5);
assert_eq!(map[&10], 5);

assert_eq!(removed[&2], 5);
assert_eq!(removed[&3], 5);
§See Also
Source

pub fn clear_range<R>(&mut self, range: R)
where R: RangeBounds<K>, K: Clone + Ord, V: Clone,

Remove all values in a given range. Overlapping ranges will be truncated at the bounds of this range.

§Examples
let mut map = SegmentMap::new();
map.insert(0..=10, 5);
map.clear_range(2..4);

assert_eq!(map[&0], 5);
assert!(map.get(&2).is_none());
assert!(map.get(&3).is_none());
assert_eq!(map[&4], 5);
assert_eq!(map[&10], 5);
§See Also
Source

pub fn append(&mut self, other: &mut SegmentMap<K, V>)
where K: Clone + Ord, V: Clone + Eq,

Moves all elements from other into Self, leaving other empty.

Note thate V must be Clone in case any ranges need to be split

§Examples
let mut a = SegmentMap::new();
a.insert(0..1, "a");
a.insert(1..2, "b");
a.insert(2..3, "c");

let mut b = SegmentMap::new();
b.insert(2..3, "d");
b.insert(3..4, "e");
b.insert(4..5, "f");

a.append(&mut b);

assert_eq!(a.len(), 5);
assert_eq!(b.len(), 0);

assert_eq!(a[&0], "a");
assert_eq!(a[&1], "b");
assert_eq!(a[&2], "d");
assert_eq!(a[&3], "e");
assert_eq!(a[&4], "f");
Source

pub fn split_off(&mut self, at: Bound<K>) -> SegmentMap<K, V>
where K: Clone + Ord, V: Clone,

Split the map into two at the given bound. Returns everything including and after that bound.

§Examples
§Basic Usage
let mut a = SegmentMap::new();
a.insert(0..1, "a");
a.insert(1..2, "b");
a.insert(2..3, "c");
a.insert(3..4, "d");

let b = a.split_off(Bound::Included(2));

assert!(a.into_iter().eq(vec![
    (Segment::from(0..1), "a"),
    (Segment::from(1..2), "b"),
]));
assert!(b.into_iter().eq(vec![
    (Segment::from(2..3), "c"),
    (Segment::from(3..4), "d"),
]));
§Mixed Bounds
let mut a = SegmentMap::new();
a.insert(0..1, "a");
a.insert(1..2, "b");
a.insert(2..3, "c");
a.insert(3..4, "d");
a.insert(4..5, "e");
a.insert(5..6, "f");
a.insert(6..7, "g");

let c = a.split_off(Bound::Excluded(4));
let b = a.split_off(Bound::Included(2));

assert_eq!(a.len(), 2);
assert_eq!(b.len(), 3);
assert_eq!(c.len(), 3);

assert_eq!(a[&0], "a");
assert_eq!(a[&1], "b");
assert!(a.get(&2).is_none());

assert!(b.get(&1).is_none());
assert_eq!(b[&2], "c");
assert_eq!(b[&3], "d");
assert_eq!(b[&4], "e");
assert!(b.get(&5).is_none());

// `c` also has a a range (4, 5), which is inaccessible with integers.
// if we were using floats, `c[4.5]` would be `"e"`.
assert!(c.get(&4).is_none());
assert_eq!(c[&5], "f");
assert_eq!(c[&6], "g");
assert!(c.get(&7).is_none());

Trait Implementations§

Source§

impl<K, V> Clone for SegmentMap<K, V>
where K: Clone, V: Clone,

Source§

fn clone(&self) -> SegmentMap<K, V>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<K, V> Debug for SegmentMap<K, V>
where K: Debug + Ord + Clone, V: Debug + Eq + Clone,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl<K, V> Default for SegmentMap<K, V>
where K: Ord,

Source§

fn default() -> SegmentMap<K, V>

Returns the “default value” for a type. Read more
Source§

impl<R, K, V> Extend<(R, V)> for SegmentMap<K, V>
where R: RangeBounds<K>, K: Clone + Ord, V: Clone + Eq,

Source§

fn extend<T>(&mut self, iter: T)
where T: IntoIterator<Item = (R, V)>,

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl<R, K, V> FromIterator<(R, V)> for SegmentMap<K, V>
where R: RangeBounds<K>, K: Clone + Ord, V: Clone + Eq,

Source§

fn from_iter<T>(iter: T) -> SegmentMap<K, V>
where T: IntoIterator<Item = (R, V)>,

Creates a value from an iterator. Read more
Source§

impl<K, V> Hash for SegmentMap<K, V>
where K: Hash, V: Hash,

Source§

fn hash<H>(&self, state: &mut H)
where H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<K, V> Index<&K> for SegmentMap<K, V>
where K: Clone + Ord, V: Eq + Clone,

Source§

fn index(&self, key: &K) -> &V

Returns a reference to the value corresponding to the supplied key.

§Panics

Panics if the key is not present in the SegmentMap.

Source§

type Output = V

The returned type after indexing.
Source§

impl<'a, K, V> IntoIterator for &'a SegmentMap<K, V>

Source§

type Item = (&'a Segment<K>, &'a V)

The type of the elements being iterated over.
Source§

type IntoIter = Iter<'a, K, V>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Iter<'a, K, V>

Creates an iterator from a value. Read more
Source§

impl<'a, K, V> IntoIterator for &'a mut SegmentMap<K, V>

Source§

type Item = (&'a Segment<K>, &'a mut V)

The type of the elements being iterated over.
Source§

type IntoIter = IterMut<'a, K, V>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> IterMut<'a, K, V>

Creates an iterator from a value. Read more
Source§

impl<K, V> IntoIterator for SegmentMap<K, V>

Source§

type Item = (Segment<K>, V)

The type of the elements being iterated over.
Source§

type IntoIter = IntoIter<K, V>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> <SegmentMap<K, V> as IntoIterator>::IntoIter

Creates an iterator from a value. Read more
Source§

impl<K, V> Ord for SegmentMap<K, V>
where K: Ord, V: Ord,

Source§

fn cmp(&self, other: &SegmentMap<K, V>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl<K, V> PartialEq for SegmentMap<K, V>
where K: PartialEq, V: PartialEq,

Source§

fn eq(&self, other: &SegmentMap<K, V>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<K, V> PartialOrd for SegmentMap<K, V>
where K: PartialOrd + Ord, V: PartialOrd,

Source§

fn partial_cmp(&self, other: &SegmentMap<K, V>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<V: Clone + Eq> TextMap<V> for SegmentMap<usize, V>

Source§

fn merge_only_longest<I: IntoIterator<Item = (Segment<usize>, V)>>( &mut self, other: I, )

Source§

impl<K, V> Eq for SegmentMap<K, V>
where K: Eq, V: Eq,

Auto Trait Implementations§

§

impl<K, V> Freeze for SegmentMap<K, V>

§

impl<K, V> RefUnwindSafe for SegmentMap<K, V>

§

impl<K, V> Send for SegmentMap<K, V>
where V: Send, K: Send,

§

impl<K, V> Sync for SegmentMap<K, V>
where V: Sync, K: Sync,

§

impl<K, V> Unpin for SegmentMap<K, V>
where K: Unpin,

§

impl<K, V> UnwindSafe for SegmentMap<K, V>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.