Skip to main content

OrderedSliceMap

Struct OrderedSliceMap 

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

An ordered map based on an ordered slice. This structures provides a subset of the methods offered by the standard library’s BTreeMap.

§Examples

use static_mapset::OrderedSliceMap;

let movie_reviews_data = [
    ("Office Space", "Deals with real issues in the workplace."),
    ("Pulp Fiction", "Masterpiece."),
    ("The Godfather", "Very enjoyable."),
    ("The Blues Brothers", "Eye lyked it a lot.")
];
let movie_reviews = OrderedSliceMap::new_unchecked(&movie_reviews_data);

// check for a specific one.
if !movie_reviews.contains_key("Les Misérables") {
    println!("We've got {} reviews, but Les Misérables ain't one.",
             movie_reviews.len());
}

// look up the values associated with some keys.
let to_find = ["Up!", "Office Space"];
for movie in &to_find {
    match movie_reviews.get(movie) {
       Some(review) => println!("{movie}: {review}"),
       None => println!("{movie} is unreviewed.")
    }
}

// Look up the value for a key (will panic if the key is not found).
println!("Movie review: {}", movie_reviews[&"Office Space"]);

// iterate over everything.
for (movie, review) in &movie_reviews {
    println!("{movie}: \"{review}\"");
}

Implementations§

Source§

impl<'a, K, V> OrderedSliceMap<'a, K, V>

Source

pub fn new(items: &'a mut [(K, V)]) -> Self
where K: Ord,

Sorts the slice and creates an OrderedSliceMap. Duplicate keys are removed, keeping the last occurrence.

§Complexity

Linearithmic in self.len().

§Examples
use static_mapset::OrderedSliceMap;

let mut data = [(2, "b"), (1, "a")];
let map = OrderedSliceMap::new(&mut data);
assert_eq!(map.first_key_value(), Some((&1, &"a")));
Source

pub const fn new_unchecked(ordered_items: &'a [(K, V)]) -> Self

Creates an OrderedSliceMap from an immutable slice without sorting.

The slice must be sorted in ascending order with no duplicate keys.

§Complexity

Constant.

§Examples
use static_mapset::OrderedSliceMap;

static MAP: OrderedSliceMap<i32, &str> = OrderedSliceMap::new_unchecked(&[(1, "a"), (2, "b")]);
assert_eq!(MAP.get(&2), Some(&"b"));

// Incorrect key order or duplicates cause undefined behavior:
// let map = OrderedSliceMap::new_unchecked(&[(2, "a"), (1, "b")]);
// let map = OrderedSliceMap::new_unchecked(&[(1, "a"), (1, "b")]);
Source

pub fn is_valid(&self) -> bool
where K: PartialOrd,

Returns true if the map is ordered correctly.

§Complexity

Linear in self.len().

§Examples
use static_mapset::OrderedSliceMap;

let map = OrderedSliceMap::new_unchecked(&[(1, "a"), (2, "b"), (3, "b")]);
assert!(map.is_valid());

let map = OrderedSliceMap::new_unchecked(&[(1, "a"), (2, "b"), (2, "c")]);
assert!(!map.is_valid());
let map = OrderedSliceMap::new_unchecked(&[(1.0, "a"), (2.0, "b"), (f64::NAN, "c")]);
assert!(!map.is_valid());
Source

pub fn contains_key<Q>(&self, key: &Q) -> bool
where K: Borrow<Q>, Q: PartialOrd + ?Sized,

Returns true if the map contains a value for the specified key.

The key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must match the ordering on the key type. If equal keys are present, this returns true if any matching key exists.

§Complexity

Logarithmic in self.len().

§Examples
use static_mapset::OrderedSliceMap;

let data = [(1, "a")];
let map = OrderedSliceMap::new_unchecked(&data);
assert_eq!(map.contains_key(&1), true);
assert_eq!(map.contains_key(&2), false);

let data = [(1.0, "a"), (2.0, "b")];
let map = OrderedSliceMap::new_unchecked(&data);
// f64::NAN is incomparable, so key lookups by NaN never match.
assert_eq!(map.contains_key(&f64::NAN), false);
Source

pub fn first_key_value(&self) -> Option<(&K, &V)>

Returns the first key-value pair in the map. The key in this pair is the minimum key in the map.

§Complexity

Constant.

§Examples
use static_mapset::OrderedSliceMap;

let empty: &[(i32, &str)] = &[];
let map = OrderedSliceMap::new_unchecked(empty);
assert_eq!(map.first_key_value(), None);

let data = [(1, "b"), (2, "a")];
let map = OrderedSliceMap::new_unchecked(&data);
assert_eq!(map.first_key_value(), Some((&1, &"b")));
Source

pub fn get<Q>(&self, key: &Q) -> Option<&V>
where K: Borrow<Q>, Q: PartialOrd + ?Sized,

Returns a reference to the value corresponding to the key.

The key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must match the ordering on the key type.

§Complexity

Logarithmic in self.len().

§Examples
use static_mapset::OrderedSliceMap;

let data = [(1, "a")];
let map = OrderedSliceMap::new_unchecked(&data);
assert_eq!(map.get(&1), Some(&"a"));
assert_eq!(map.get(&2), None);

let data = [(1.0, "a"), (2.0, "b")];
let map = OrderedSliceMap::new_unchecked(&data);
// f64::NAN is incomparable, so key lookups by NaN never match.
assert_eq!(map.get(&f64::NAN), None);
Source

pub fn get_key_value<Q>(&self, key: &Q) -> Option<(&K, &V)>
where K: Borrow<Q>, Q: PartialOrd + ?Sized,

Returns the key-value pair corresponding to the supplied key.

The supplied key may be any borrowed form of the map’s key type, but the ordering on the borrowed form must match the ordering on the key type. If equal keys are present, the first matching entry in key order is returned.

§Complexity

Logarithmic in self.len().

§Examples
use std::cmp::Ordering;
use static_mapset::OrderedSliceMap;

#[derive(Clone, Copy, Debug)]
struct S {
    id: u32,
    name: &'static str, // ignored by equality and ordering operations
}

impl PartialEq for S {
    fn eq(&self, other: &S) -> bool {
        self.id == other.id
    }
}

impl Eq for S {}

impl PartialOrd for S {
    fn partial_cmp(&self, other: &S) -> Option<Ordering> {
        self.id.partial_cmp(&other.id)
    }
}

impl Ord for S {
    fn cmp(&self, other: &S) -> Ordering {
        self.id.cmp(&other.id)
    }
}

let j_a = S { id: 1, name: "Jessica" };
let j_b = S { id: 1, name: "Jess" };
let p = S { id: 2, name: "Paul" };
assert_eq!(j_a, j_b);

let data = [(j_a, "Paris")];
let map = OrderedSliceMap::new_unchecked(&data);
assert_eq!(map.get_key_value(&j_a), Some((&j_a, &"Paris")));
assert_eq!(map.get_key_value(&j_b), Some((&j_a, &"Paris"))); // the notable case
assert_eq!(map.get_key_value(&p), None);

let data = [(1.0, "a"), (2.0, "b")];
let map = OrderedSliceMap::new_unchecked(&data);
// f64::NAN is incomparable, so key lookups by NaN never match.
assert_eq!(map.get_key_value(&f64::NAN), None);
Source

pub const fn is_empty(&self) -> bool

Returns true if the map contains no elements.

§Complexity

Constant.

§Examples
use static_mapset::OrderedSliceMap;

let map: OrderedSliceMap<i32, &str> = OrderedSliceMap::new_unchecked(&[]);
assert!(map.is_empty());
let map = OrderedSliceMap::new_unchecked(&[(1, "a")]);
assert!(!map.is_empty());
Source

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

Gets an iterator over the entries of the map, sorted by key.

§Complexity

Linear in self.len() to iterate all elements.

§Examples
use static_mapset::OrderedSliceMap;

let mut data = [(2, "b"), (1, "a")];
let map = OrderedSliceMap::new(&mut data);

let (first_key, first_value) = map.iter().next().unwrap();
assert_eq!((*first_key, *first_value), (1, "a"));
Source

pub fn keys(&self) -> Keys<'_, K, V>

Gets an iterator over the keys of the map, in sorted order.

§Complexity

Linear in self.len() to iterate all elements.

§Examples
use static_mapset::OrderedSliceMap;

let mut data = [(2, "b"), (1, "a")];
let map = OrderedSliceMap::new(&mut data);

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

pub fn last_key_value(&self) -> Option<(&K, &V)>

Returns the last key-value pair in the map. The key in this pair is the maximum key in the map.

§Complexity

Constant.

§Examples
use static_mapset::OrderedSliceMap;

let data = [(1, "b"), (2, "a")];
let map = OrderedSliceMap::new_unchecked(&data);
assert_eq!(map.last_key_value(), Some((&2, &"a")));
Source

pub const fn len(&self) -> usize

Returns the number of elements in the map.

§Complexity

Constant.

Source

pub fn lower_bound<Q>(&self, bound: Bound<&Q>) -> Cursor<'_, K, V>
where K: Borrow<Q>, Q: PartialOrd + ?Sized,

Returns a Cursor pointing at the gap before the smallest key greater than the given bound.

Passing Bound::Included(x) will return a cursor pointing to the gap before the smallest key greater than or equal to x.

Passing Bound::Excluded(x) will return a cursor pointing to the gap before the smallest key greater than x.

Passing Bound::Unbounded will return a cursor pointing to the gap before the smallest key in the map. With equal keys, Included points before the first equal key and Excluded points after the last equal key.

§Complexity

Logarithmic in self.len() to find the bounds, and linear in the number of yielded elements to iterate them all.

§Examples
use static_mapset::OrderedSliceMap;
use std::ops::Bound;

let data = [
    (1, "a"),
    (2, "b"),
    (3, "c"),
    (4, "d"),
];
let map = OrderedSliceMap::new_unchecked(&data);

let cursor = map.lower_bound(Bound::Included(&2));
assert_eq!(cursor.peek_prev(), Some((&1, &"a")));
assert_eq!(cursor.peek_next(), Some((&2, &"b")));

let cursor = map.lower_bound(Bound::Excluded(&2));
assert_eq!(cursor.peek_prev(), Some((&2, &"b")));
assert_eq!(cursor.peek_next(), Some((&3, &"c")));

let cursor = map.lower_bound(Bound::Unbounded);
assert_eq!(cursor.peek_prev(), None);
assert_eq!(cursor.peek_next(), Some((&1, &"a")));

let data = [(1.0, "a"), (2.0, "b")];
let map = OrderedSliceMap::new_unchecked(&data);
// f64::NAN is incomparable, so the cursor points to the gap after the last key.
let cursor = map.lower_bound(Bound::Included(&f64::NAN));
assert_eq!(cursor.peek_prev(), Some((&2.0, &"b")));
Source

pub fn range<Q, R>(&self, range: R) -> Range<'_, K, V>
where K: Borrow<Q>, Q: PartialOrd + ?Sized, R: RangeBounds<Q>,

Constructs a double-ended iterator over a sub-range of elements in the map. The simplest way is to use the range syntax min..max, thus range(min..max) will yield elements from min (inclusive) to max (exclusive). The range may also be entered as (Bound<T>, Bound<T>), so for example range((Excluded(4), Included(10))) will yield a left-exclusive, right-inclusive range from 4 to 10.

§Panics

Panics if range start > end. Panics if range start == end and both bounds are Excluded. Panics if start (or end() is incomparable and end (or start) is bounded.

§Complexity

Logarithmic in self.len().

§Examples
use static_mapset::OrderedSliceMap;
use std::ops::Bound::Included;

let data = [
    (3, "a"),
    (5, "b"),
    (8, "c"),
];
let map = OrderedSliceMap::new_unchecked(&data);
for (&key, &value) in map.range((Included(&4), Included(&8))) {
    println!("{key}: {value}");
}
assert_eq!(Some((&5, &"b")), map.range(4..).next());
Source

pub fn upper_bound<Q>(&self, bound: Bound<&Q>) -> Cursor<'_, K, V>
where K: Borrow<Q>, Q: PartialOrd + ?Sized,

Returns a Cursor pointing at the gap after the greatest key smaller than the given bound.

Passing Bound::Included(x) will return a cursor pointing to the gap after the greatest key smaller than or equal to x.

Passing Bound::Excluded(x) will return a cursor pointing to the gap after the greatest key smaller than x.

Passing Bound::Unbounded will return a cursor pointing to the gap after the greatest key in the map. With equal keys, Excluded points before the first equal key and Included points after the last equal key.

§Complexity

Logarithmic in self.len().

§Examples

use static_mapset::OrderedSliceMap;
use std::ops::Bound;

let data = [
    (1, "a"),
    (2, "b"),
    (3, "c"),
    (4, "d"),
];
let map = OrderedSliceMap::new_unchecked(&data);

let cursor = map.upper_bound(Bound::Included(&3));
assert_eq!(cursor.peek_prev(), Some((&3, &"c")));
assert_eq!(cursor.peek_next(), Some((&4, &"d")));

let cursor = map.upper_bound(Bound::Excluded(&3));
assert_eq!(cursor.peek_prev(), Some((&2, &"b")));
assert_eq!(cursor.peek_next(), Some((&3, &"c")));

let cursor = map.upper_bound(Bound::Unbounded);
assert_eq!(cursor.peek_prev(), Some((&4, &"d")));
assert_eq!(cursor.peek_next(), None);

let data = [(1.0, "a"), (2.0, "b")];
let map = OrderedSliceMap::new_unchecked(&data);
// f64::NAN is incomparable, so the cursor points to the gap after the last key.
let cursor = map.upper_bound(Bound::Included(&f64::NAN));
assert_eq!(cursor.peek_prev(), Some((&2.0, &"b")));
Source

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

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

§Complexity

Linear in self.len() to iterate all elements.

§Examples
use static_mapset::OrderedSliceMap;

let mut data = [(2, "b"), (1, "a")];
let map = OrderedSliceMap::new(&mut data);

let values: Vec<_> = map.values().cloned().collect();
assert_eq!(values, ["a", "b"]);

Trait Implementations§

Source§

impl<'a, K, V> Clone for OrderedSliceMap<'a, K, V>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl<'a, K, V> Copy for OrderedSliceMap<'a, K, V>

Source§

impl<'a, K: Debug, V: Debug> Debug for OrderedSliceMap<'a, K, V>

Source§

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

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

impl<'a, K: Eq, V: Eq> Eq for OrderedSliceMap<'a, K, V>

Source§

impl<'a, K: Hash, V: Hash> Hash for OrderedSliceMap<'a, K, V>

Source§

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

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<'a, K, V, Q> Index<&Q> for OrderedSliceMap<'a, K, V>
where K: Borrow<Q>, Q: Ord,

Source§

type Output = V

The returned type after indexing.
Source§

fn index(&self, key: &Q) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
Source§

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

Source§

type Item = (&'a 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) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<'a, K: Ord, V: Ord> Ord for OrderedSliceMap<'a, K, V>

Source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

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

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

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

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

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

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

fn clamp_to<R>(self, range: R) -> Self
where Self: Sized, R: ClampBounds<Self>,

🔬This is a nightly-only experimental API. (clamp_to)
Restrict a value to a certain range. Read more
Source§

impl<'a, K: PartialEq, V: PartialEq> PartialEq for OrderedSliceMap<'a, K, V>

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

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

Inequality operator !=. Read more
Source§

impl<'a, K: PartialOrd, V: PartialOrd> PartialOrd for OrderedSliceMap<'a, K, V>

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · 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 (const: unstable) · 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 (const: unstable) · 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 (const: unstable) · 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<'a, K: PartialEq, V: PartialEq> StructuralPartialEq for OrderedSliceMap<'a, K, V>

Auto Trait Implementations§

§

impl<'a, K, V> Forget for OrderedSliceMap<'a, K, V>

§

impl<'a, K, V> Freeze for OrderedSliceMap<'a, K, V>
where &'a [(K, V)]: Freeze,

§

impl<'a, K, V> Move for OrderedSliceMap<'a, K, V>

§

impl<'a, K, V> RefUnwindSafe for OrderedSliceMap<'a, K, V>
where &'a [(K, V)]: RefUnwindSafe,

§

impl<'a, K, V> Send for OrderedSliceMap<'a, K, V>
where &'a [(K, V)]: Send,

§

impl<'a, K, V> Sync for OrderedSliceMap<'a, K, V>
where &'a [(K, V)]: Sync,

§

impl<'a, K, V> Unpin for OrderedSliceMap<'a, K, V>
where &'a [(K, V)]: Unpin,

§

impl<'a, K, V> UnsafeUnpin for OrderedSliceMap<'a, K, V>
where &'a [(K, V)]: UnsafeUnpin,

§

impl<'a, K, V> UnwindSafe for OrderedSliceMap<'a, K, V>
where &'a [(K, V)]: UnwindSafe,

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 = !

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

fn try_from(value: U) -> Result<T, !>

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.