use alloc::boxed::Box; use alloc::vec::Vec; use core::cmp::Ordering; use core::fmt; use core::hash::{Hash, Hasher}; use core::ops::{self, Bound, Index, IndexMut, RangeBounds};
/// A dynamically-sized slice of key-value pairs in an [`IndexMap`]. /// /// This supports indexed operations much like a `[(K, V)]` slice, /// but not any hashed operations on the map keys. /// /// Unlike `IndexMap`, `Slice` does consider the order for [`PartialEq`] /// and [`Eq`], and it also implements [`PartialOrd`], [`Ord`], and [`Hash`]. #[repr(transparent)] pubstruct Slice<K, V> { pub(crate) entries: [Bucket<K, V>],
}
// SAFETY: `Slice<K, V>` is a transparent wrapper around `[Bucket<K, V>]`, // and reference lifetimes are bound together in function signatures. #[allow(unsafe_code)] impl<K, V> Slice<K, V> { pub(super) constfn from_slice(entries: &[Bucket<K, V>]) -> &Self { unsafe { &*(entries as *const [Bucket<K, V>] as *constSelf) }
}
/// Return the number of key-value pairs in the map slice. #[inline] pubconstfn len(&self) -> usize { self.entries.len()
}
/// Returns true if the map slice contains no elements. #[inline] pubconstfn is_empty(&self) -> bool { self.entries.is_empty()
}
/// Get a key-value pair by index. /// /// Valid indices are *0 <= index < self.len()* pubfn get_index(&self, index: usize) -> Option<(&K, &V)> { self.entries.get(index).map(Bucket::refs)
}
/// Get a key-value pair by index, with mutable access to the value. /// /// Valid indices are *0 <= index < self.len()* pubfn get_index_mut(&mutself, index: usize) -> Option<(&K, &style='color:red'>mut V)> { self.entries.get_mut(index).map(Bucket::ref_mut)
}
/// Returns a slice of key-value pairs in the given range of indices. /// /// Valid indices are *0 <= index < self.len()* pubfn get_range<R: RangeBounds<usize>>(&self, range: R) -> Option<& style='color:red'>Self> { let range = try_simplify_range(range, self.entries.len())?; self.entries.get(range).map(Slice::from_slice)
}
/// Returns a mutable slice of key-value pairs in the given range of indices. /// /// Valid indices are *0 <= index < self.len()* pubfn get_range_mut<R: RangeBounds<usize>>(&mutself, range: R) -> Option<&mutSelf> { let range = try_simplify_range(range, self.entries.len())?; self.entries.get_mut(range).map(Slice::from_mut_slice)
}
/// Get the first key-value pair. pubfn first(&self) -> Option<(&K, &V)> { self.entries.first().map(Bucket::refs)
}
/// Get the first key-value pair, with mutable access to the value. pubfn first_mut(&mutself) -> Option<(&K, &mut V)> { self.entries.first_mut().map(Bucket::ref_mut)
}
/// Get the last key-value pair. pubfn last(&self) -> Option<(&K, &V)> { self.entries.last().map(Bucket::refs)
}
/// Get the last key-value pair, with mutable access to the value. pubfn last_mut(&mutself) -> Option<(&K, &>mut V)> { self.entries.last_mut().map(Bucket::ref_mut)
}
/// Divides one slice into two at an index. /// /// ***Panics*** if `index > len`. pubfn split_at(&self, index: usize) -> (&Self, &Self) { let (first, second) = self.entries.split_at(index);
(Self::from_slice(first), Self::from_slice(second))
}
/// Divides one mutable slice into two at an index. /// /// ***Panics*** if `index > len`. pubfn split_at_mut(&mutself, index: usize) -> (&mutSelf, &mutSelf) { let (first, second) = self.entries.split_at_mut(index);
(Self::from_mut_slice(first), Self::from_mut_slice(second))
}
/// Returns the first key-value pair and the rest of the slice, /// or `None` if it is empty. pubfn split_first(&self) -> Option<((&K, &V), &Self)> { iflet [first, rest @ ..] = &self.entries {
Some((first.refs(), Self::from_slice(rest)))
} else {
None
}
}
/// Returns the first key-value pair and the rest of the slice, /// with mutable access to the value, or `None` if it is empty. pubfn split_first_mut(&mutself) -> Option<((&K, &mut V), &mutSelf)> { iflet [first, rest @ ..] = &mutself.entries {
Some((first.ref_mut(), Self::from_mut_slice(rest)))
} else {
None
}
}
/// Returns the last key-value pair and the rest of the slice, /// or `None` if it is empty. pubfn split_last(&self) -> Option<((&K, &V), &Self)> { iflet [rest @ .., last] = &self.entries {
Some((last.refs(), Self::from_slice(rest)))
} else {
None
}
}
/// Returns the last key-value pair and the rest of the slice, /// with mutable access to the value, or `None` if it is empty. pubfn split_last_mut(&mutself) -> Option<((&K, &mut V), &mutSelf)> { iflet [rest @ .., last] = &mutself.entries {
Some((last.ref_mut(), Self::from_mut_slice(rest)))
} else {
None
}
}
/// Return an iterator over the key-value pairs of the map slice. pubfn iter(&self) -> Iter<'_, K, V> {
Iter::new(&self.entries)
}
/// Return an iterator over the key-value pairs of the map slice. pubfn iter_mut(&mutself) -> IterMut<'_, K, V> {
IterMut::new(&mutself.entries)
}
/// Return an iterator over the keys of the map slice. pubfn keys(&self) -> Keys<'_, K, V> {
Keys::new(&self.entries)
}
/// Return an owning iterator over the keys of the map slice. pubfn into_keys(self: Box<Self>) -> IntoKeys<K, V> {
IntoKeys::new(self.into_entries())
}
/// Return an iterator over the values of the map slice. pubfn values(&self) -> Values<'_, K, V> {
Values::new(&self.entries)
}
/// Return an iterator over mutable references to the the values of the map slice. pubfn values_mut(&mutself) -> ValuesMut<'_, K, V> {
ValuesMut::new(&mutself.entries)
}
/// Return an owning iterator over the values of the map slice. pubfn into_values(self: Box<Self>) -> IntoValues<K, V> {
IntoValues::new(self.into_entries())
}
/// Search over a sorted map for a key. /// /// Returns the position where that key is present, or the position where it can be inserted to /// maintain the sort. See [`slice::binary_search`] for more details. /// /// Computes in **O(log(n))** time, which is notably less scalable than looking the key up in /// the map this is a slice from using [`IndexMap::get_index_of`], but this can also position /// missing keys. pubfn binary_search_keys(&self, x: &K) -> Result<usize, usize> where
K: Ord,
{ self.binary_search_by(|p, _| p.cmp(x))
}
/// Search over a sorted map with a comparator function. /// /// Returns the position where that value is present, or the position where it can be inserted /// to maintain the sort. See [`slice::binary_search_by`] for more details. /// /// Computes in **O(log(n))** time. #[inline] pubfn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize> where
F: FnMut(&'a K, &'a V) -> Ordering,
{ self.entries.binary_search_by(move |a| f(&a.key, &a.value))
}
/// Search over a sorted map with an extraction function. /// /// Returns the position where that value is present, or the position where it can be inserted /// to maintain the sort. See [`slice::binary_search_by_key`] for more details. /// /// Computes in **O(log(n))** time. #[inline] pubfn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize> where
F: FnMut(&'a K, &'a V) -> B,
B: Ord,
{ self.binary_search_by(|k, v| f(k, v).cmp(b))
}
/// Returns the index of the partition point of a sorted map according to the given predicate /// (the index of the first element of the second partition). /// /// See [`slice::partition_point`] for more details. /// /// Computes in **O(log(n))** time. #[must_use] pubfn partition_point<P>(&self, mut pred: P) -> usize where
P: FnMut(&K, &V) -> bool,
{ self.entries
.partition_point(move |a| pred(&a.key, &a.value))
}
}
impl<'a, K, V> IntoIterator for &'a Slice<K, V> { type IntoIter = Iter<'a, K, V>; type Item = (&'a K, &'a V);
impl<K, V> IndexMut<usize> for Slice<K, V> { fn index_mut(&mutself, index: usize) -> &mut V {
&mutself.entries[index].value
}
}
// We can't have `impl<I: RangeBounds<usize>> Index<I>` because that conflicts // both upstream with `Index<usize>` and downstream with `Index<&Q>`. // Instead, we repeat the implementations for all the core range types.
macro_rules! impl_index {
($($range:ty),*) => {$( impl<K, V, S> Index<$range> for IndexMap<K, V, S> { type Output = Slice<K, V>;
let vec: Vec<(i32, i32)> = (0..10).map(|i| (i, i * i)).collect(); let map: IndexMap<i32, i32> = vec.iter().cloned().collect(); let slice = map.as_slice();
for i in0usize..10 { // Index
assert_eq!(vec[i].1, map[i]);
assert_eq!(vec[i].1, slice[i]);
assert_eq!(map[&(i as i32)], map[i]);
assert_eq!(map[&(i as i32)], slice[i]);
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.