Skip to main content

Collection

Struct Collection 

Source
pub struct Collection<K, V, S = DefaultHashBuilder> { /* private fields */ }
Expand description

A map that remembers the order its keys were first inserted in, with the helpers of discord.js’ Collection.

Iteration, first, last, at and random follow insertion order (D-209); inserting an existing key replaces its value in place, and remove keeps the order of the rest (D-215). Lookups are hash-based, with foldhash by default (D-216).

The helpers follow discord.js (D-210), with Rust’s ownership (D-214):

discord.js’ each, some, every, reduce and tap have no counterpart: use the iterators (.values().any(…), .iter().fold(…), …). Callbacks receive the value first and the key second, as in discord.js.

discord.js counterpart: Collection (@discordjs/collection).

§Examples

use djs_collection::Collection;

let mut scores: Collection<&str, u32> = Collection::new();
scores.insert("ada", 31);
scores.insert("grace", 27);
scores.insert("linus", 40);

assert_eq!(scores.first(), Some(&31));
assert_eq!(scores.find_key(|&score, _| score > 30), Some(&"ada"));

scores.sort_by(|a, b, _, _| b.cmp(a));
assert_eq!(scores.keys().copied().collect::<Vec<_>>(), ["linus", "ada", "grace"]);

let (high, low) = scores.partition(|&score, _| score >= 30);
assert_eq!(high.len(), 2);
assert_eq!(low.get("grace"), Some(&27));

Implementations§

Source§

impl<K, V> Collection<K, V>

Source

pub fn new() -> Self

Creates an empty collection.

discord.js counterpart: new Collection().

Source

pub fn with_capacity(capacity: usize) -> Self

Creates an empty collection with room for capacity entries before it reallocates.

discord.js counterpart: none (JavaScript maps have no capacity).

Source§

impl<K, V, S> Collection<K, V, S>

Source

pub const fn with_hasher(hasher: S) -> Self

Creates an empty collection hashing keys with hasher.

discord.js counterpart: none (JavaScript maps have no hasher).

Source

pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> Self

Creates an empty collection with room for capacity entries, hashing with hasher.

discord.js counterpart: none (JavaScript maps have no capacity or hasher).

Source

pub fn len(&self) -> usize

The number of entries.

discord.js counterpart: size.

Source

pub fn is_empty(&self) -> bool

Whether there are no entries.

discord.js counterpart: collection.size === 0.

Source

pub fn capacity(&self) -> usize

How many entries fit before the collection reallocates.

discord.js counterpart: none (JavaScript maps have no capacity).

Source

pub fn clear(&mut self)

Removes every entry, keeping the memory for reuse.

discord.js counterpart: clear.

Source

pub fn hasher(&self) -> &S

The hasher keys are hashed with.

discord.js counterpart: none (JavaScript maps have no hasher).

Source

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

The entries in order, as (&key, &value).

discord.js counterpart: entries.

Source

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

The entries in order, with mutable values.

discord.js counterpart: none (JavaScript values are mutated in place).

Source

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

The keys in order.

discord.js counterpart: keys.

Source

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

The values in order.

discord.js counterpart: values.

Source

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

The values in order, mutable.

discord.js counterpart: none (JavaScript values are mutated in place).

Source

pub fn into_keys(self) -> IntoKeys<K, V> ⓘ

The keys in order, moved out of the collection.

discord.js counterpart: Map#keys.

Source

pub fn into_values(self) -> IntoValues<K, V> ⓘ

The values in order, moved out of the collection.

discord.js counterpart: Map#values.

Source

pub const fn as_index_map(&self) -> &IndexMap<K, V, S>

The inner IndexMap, for operations this type does not offer (D-217).

discord.js counterpart: none (the Map a Collection extends).

Source

pub const fn as_index_map_mut(&mut self) -> &mut IndexMap<K, V, S>

The inner IndexMap, mutable (D-217).

discord.js counterpart: none (the Map a Collection extends).

Source

pub fn into_index_map(self) -> IndexMap<K, V, S>

Turns the collection into its inner IndexMap (D-217).

discord.js counterpart: none (the Map a Collection extends).

Source

pub fn first(&self) -> Option<&V>

The first value inserted, or None if the collection is empty. The first n are .values().take(n).

discord.js counterpart: first().

Source

pub fn first_key(&self) -> Option<&K>

The first key inserted.

discord.js counterpart: firstKey().

Source

pub fn last(&self) -> Option<&V>

The last value inserted. The last n are .values().rev().take(n).

discord.js counterpart: last().

Source

pub fn last_key(&self) -> Option<&K>

The last key inserted.

discord.js counterpart: lastKey().

Source

pub fn at(&self, index: isize) -> Option<&V>

The value at position index in insertion order; a negative index counts from the end (-1 is the last).

discord.js counterpart: at.

§Examples
use djs_collection::Collection;

let letters: Collection<u8, char> = [(1, 'a'), (2, 'b'), (3, 'c')].into();
assert_eq!(letters.at(0), Some(&'a'));
assert_eq!(letters.at(-1), Some(&'c'));
assert_eq!(letters.at(3), None);
assert_eq!(letters.key_at(-3), Some(&1));
Source

pub fn key_at(&self, index: isize) -> Option<&K>

The key at position index; a negative index counts from the end.

discord.js counterpart: keyAt.

Source

pub fn random(&self) -> Option<&V>

A random value, or None if the collection is empty.

The randomness comes from std’s RandomState (D-210): fine for games and giveaways, not for anything that must resist prediction.

discord.js counterpart: random().

Source

pub fn random_key(&self) -> Option<&K>

A random key.

discord.js counterpart: randomKey().

Source

pub fn random_n(&self, count: usize) -> Vec<&V>

Up to count different random values, in random order — all of them, shuffled, if count is at least the length.

discord.js counterpart: random(amount).

§Examples
use djs_collection::Collection;

let entrants: Collection<u64, &str> = [(1, "ada"), (2, "grace"), (3, "linus")].into();
let winners = entrants.random_n(2);
assert_eq!(winners.len(), 2);
assert_ne!(winners[0], winners[1]);
Source

pub fn find(&self, predicate: impl FnMut(&V, &K) -> bool) -> Option<&V>

The first value for which predicate(value, key) is true.

discord.js counterpart: find.

Source

pub fn find_key(&self, predicate: impl FnMut(&V, &K) -> bool) -> Option<&K>

The key of the first value for which predicate(value, key) is true.

discord.js counterpart: findKey.

Source

pub fn find_last(&self, predicate: impl FnMut(&V, &K) -> bool) -> Option<&V>

The last value for which predicate(value, key) is true.

discord.js counterpart: findLast.

Source

pub fn find_last_key(&self, predicate: impl FnMut(&V, &K) -> bool) -> Option<&K>

The key of the last value for which predicate(value, key) is true.

discord.js counterpart: findLastKey.

Source

pub fn map<T>(&self, f: impl FnMut(&V, &K) -> T) -> Vec<T>

f(value, key) of every entry, in order.

discord.js counterpart: map.

§Examples
use djs_collection::Collection;

let users: Collection<u64, &str> = [(1, "ada"), (2, "grace")].into();
assert_eq!(users.map(|name, id| format!("{id}:{name}")), ["1:ada", "2:grace"]);
Source

pub fn reverse(&mut self)

Reverses the order of the entries.

discord.js counterpart: reverse.

Source

pub fn to_reversed(self) -> Self

The collection with its entries in reverse order.

discord.js counterpart: toReversed.

Source

pub fn sort_by(&mut self, compare: impl FnMut(&V, &V, &K, &K) -> Ordering)

Sorts the entries with compare(value_a, value_b, key_a, key_b), keeping the order of equal ones.

discord.js counterpart: sort(compareFunction).

Source

pub fn to_sorted_by( self, compare: impl FnMut(&V, &V, &K, &K) -> Ordering, ) -> Self

The collection sorted with compare(value_a, value_b, key_a, key_b).

discord.js counterpart: toSorted(compareFunction).

Source

pub fn sort(&mut self)
where V: Ord,

Sorts the entries by value, keeping the order of equal ones.

discord.js counterpart: sort() (which compares values as strings).

Source

pub fn to_sorted(self) -> Self
where V: Ord,

The collection sorted by value.

discord.js counterpart: toSorted().

Source§

impl<K, V, S> Collection<K, V, S>
where K: Hash + Eq, S: BuildHasher,

Source

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

The value of key.

discord.js counterpart: get.

Source

pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
where K: Borrow<Q>, Q: Hash + Eq + ?Sized,

The value of key, mutable.

discord.js counterpart: none (JavaScript values are mutated in place).

Source

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

The stored key equal to key, with its value.

discord.js counterpart: none (Map#get returns the value only).

Source

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

Whether key has a value.

discord.js counterpart: has.

Source

pub fn index_of<Q>(&self, key: &Q) -> Option<usize>
where K: Borrow<Q>, Q: Hash + Eq + ?Sized,

The position of key in insertion order.

discord.js counterpart: none (the inverse of Collection#keyAt).

Source

pub fn insert(&mut self, key: K, value: V) -> Option<V>

Sets the value of key, returning the previous one. A new key goes last; an existing key keeps its position.

discord.js counterpart: set.

Source

pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
where K: Borrow<Q>, Q: Hash + Eq + ?Sized,

Removes key, returning its value; the entries after it move up, so the order is kept (O(n), D-215). swap_remove is O(1).

To remove many entries, use one sweep or retain pass, which is linear however many it removes: removing 1 000 entries near the front of a million one by one moves the rest 1 000 times (seconds instead of milliseconds).

discord.js counterpart: delete.

Source

pub fn remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V)>
where K: Borrow<Q>, Q: Hash + Eq + ?Sized,

Removes key, returning the stored key and its value, keeping the order.

discord.js counterpart: Map#delete.

Source

pub fn swap_remove<Q>(&mut self, key: &Q) -> Option<V>
where K: Borrow<Q>, Q: Hash + Eq + ?Sized,

Removes key in O(1) by moving the last entry into its place, so the order changes.

discord.js counterpart: none (Map#delete keeps the order).

Source

pub fn ensure(&mut self, key: K, default: impl FnOnce(&K) -> V) -> &mut V

The value of key, inserting default(&key) first if there is none.

discord.js counterpart: ensure.

§Examples
use djs_collection::Collection;

let mut warnings: Collection<u64, u32> = Collection::new();
*warnings.ensure(1, |_| 0) += 1;
*warnings.ensure(1, |_| 0) += 1;
assert_eq!(warnings.get(&1), Some(&2));
Source

pub fn has_all<'q, Q>(&self, keys: impl IntoIterator<Item = &'q Q>) -> bool
where K: Borrow<Q>, Q: Hash + Eq + ?Sized + 'q,

Whether every key of keys has a value.

discord.js counterpart: hasAll.

Source

pub fn has_any<'q, Q>(&self, keys: impl IntoIterator<Item = &'q Q>) -> bool
where K: Borrow<Q>, Q: Hash + Eq + ?Sized + 'q,

Whether any key of keys has a value.

discord.js counterpart: hasAny.

Source

pub fn retain(&mut self, keep: impl FnMut(&K, &mut V) -> bool)

Keeps only the entries for which keep(&key, &mut value) is true, in one pass that keeps the order.

discord.js counterpart: Collection#sweep, with the condition inverted.

Source

pub fn sweep(&mut self, remove: impl FnMut(&V, &K) -> bool) -> usize

Removes the entries for which remove(value, key) is true, in one pass that keeps the order, and returns how many were removed.

discord.js counterpart: sweep.

§Examples
use djs_collection::Collection;

let mut ages: Collection<&str, u32> = [("a", 3), ("b", 40), ("c", 7)].into();
assert_eq!(ages.sweep(|&age, _| age < 10), 2);
assert_eq!(ages.len(), 1);
Source

pub fn filter(self, keep: impl FnMut(&V, &K) -> bool) -> Self

The entries for which keep(value, key) is true, in order (D-214: the collection is consumed).

discord.js counterpart: filter.

Source

pub fn partition(self, predicate: impl FnMut(&V, &K) -> bool) -> (Self, Self)
where S: Clone,

Splits the entries in two, in order: those for which predicate(value, key) is true, and the others.

discord.js counterpart: partition.

Source

pub fn map_values<T>(self, f: impl FnMut(V, &K) -> T) -> Collection<K, T, S>
where S: Clone,

A collection with the same keys and the values f(value, &key), in order.

discord.js counterpart: mapValues.

Source

pub fn flat_map<K2, V2, S2>( self, f: impl FnMut(V, K) -> Collection<K2, V2, S2>, ) -> Collection<K2, V2, S2>
where K2: Hash + Eq, S2: BuildHasher + Default,

The collections f(value, key) of every entry, joined in order; a later value of a key replaces an earlier one.

discord.js counterpart: flatMap.

Source

pub fn concat<S2>( self, others: impl IntoIterator<Item = Collection<K, V, S2>>, ) -> Self

The collection with the entries of others added in order; an existing key gets the later value and keeps its position.

discord.js counterpart: concat.

Source

pub fn union<S2>(self, other: Collection<K, V, S2>) -> Self

The entries of the collection, then those of other whose keys it does not have.

discord.js counterpart: union.

Source

pub fn intersection<V2, S2: BuildHasher>( self, other: &Collection<K, V2, S2>, ) -> Self

The entries whose keys other also has, in this collection’s order.

discord.js counterpart: intersection.

Source

pub fn difference<V2, S2: BuildHasher>( self, other: &Collection<K, V2, S2>, ) -> Self

The entries whose keys other does not have.

discord.js counterpart: difference.

Source

pub fn symmetric_difference<S2: BuildHasher>( self, other: Collection<K, V, S2>, ) -> Self

The entries whose keys only one of the two collections has: this one’s, then other’s.

discord.js counterpart: symmetricDifference.

Source

pub fn merge<O, R, S2: BuildHasher>( self, other: Collection<K, O, S2>, in_self: impl FnMut(V, &K) -> Option<R>, in_other: impl FnMut(O, &K) -> Option<R>, in_both: impl FnMut(V, O, &K) -> Option<R>, ) -> Collection<K, R, S>
where S: Clone,

Combines this collection with other key by key, in the order of this collection’s keys and then other’s new ones: in_self(value, key) for a key only here, in_other(value, key) for a key only in other, in_both(value, other_value, key) for both. A key is kept when its function returns Some.

discord.js counterpart: merge (Some(value) is { keep: true, value }).

§Examples
use djs_collection::Collection;

let before: Collection<&str, u32> = [("ada", 1), ("grace", 2)].into();
let after: Collection<&str, u32> = [("grace", 5), ("linus", 3)].into();
let changes = before.merge(
    after,
    |_, _| Some("left"),
    |_, _| Some("joined"),
    |old, new, _| (old != new).then_some("changed"),
);
assert_eq!(changes.iter().collect::<Vec<_>>(), [(&"ada", &"left"), (&"grace", &"changed"), (&"linus", &"joined")]);
Source

pub fn combine_entries( entries: impl IntoIterator<Item = (K, V)>, combine: impl FnMut(V, V, &K) -> V, ) -> Self
where S: Default,

A collection of entries in order, where a repeated key gets combine(earlier_value, later_value, key).

discord.js counterpart: Collection.combineEntries.

§Examples
use djs_collection::Collection;

let votes = [("yes", 1), ("no", 1), ("yes", 1)];
let totals: Collection<&str, u32> = Collection::combine_entries(votes, |a, b, _| a + b);
assert_eq!(totals.get("yes"), Some(&2));

Trait Implementations§

Source§

impl<K: Clone, V: Clone, S: Clone> Clone for Collection<K, V, S>

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<K: Debug, V: Debug, S> Debug for Collection<K, V, S>

Source§

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

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

impl<K, V, S: Default> Default for Collection<K, V, S>

Source§

fn default() -> Self

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

impl<K: Hash + Eq, V: Eq, S: BuildHasher> Eq for Collection<K, V, S>

Source§

impl<K: Hash + Eq, V, S: BuildHasher> Extend<(K, V)> for Collection<K, V, S>

Source§

fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, entries: I)

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

fn extend_one(&mut self, item: T)

🔬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<K, V, S> From<Collection<K, V, S>> for IndexMap<K, V, S>

Source§

fn from(collection: Collection<K, V, S>) -> Self

Converts to this type from the input type.
Source§

impl<K, V, S> From<IndexMap<K, V, S>> for Collection<K, V, S>

Source§

fn from(map: IndexMap<K, V, S>) -> Self

Converts to this type from the input type.
Source§

impl<K: Hash + Eq, V, const N: usize> From<[(K, V); N]> for Collection<K, V>

Source§

fn from(entries: [(K, V); N]) -> Self

Converts to this type from the input type.
Source§

impl<K: Hash + Eq, V, S: BuildHasher + Default> FromIterator<(K, V)> for Collection<K, V, S>

Source§

fn from_iter<I: IntoIterator<Item = (K, V)>>(entries: I) -> Self

Creates a value from an iterator. Read more
Source§

impl<K, V, Q, S> Index<&Q> for Collection<K, V, S>
where K: Hash + Eq + Borrow<Q>, Q: Hash + Eq + ?Sized, S: BuildHasher,

Indexing by key.

§Panics

If the key has no value; use Collection::get when it may not.

Source§

type Output = V

The returned type after indexing.
Source§

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

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

impl<K, V, S> IntoIterator for Collection<K, V, S>

Source§

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

Creates an iterator from a value. Read more
Source§

impl<'a, K, V, S> IntoIterator for &'a Collection<K, V, S>

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, V, S> IntoIterator for &'a mut Collection<K, V, S>

Source§

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

Creates an iterator from a value. Read more
Source§

impl<K, V1, S1, V2, S2> PartialEq<Collection<K, V2, S2>> for Collection<K, V1, S1>
where K: Hash + Eq, V1: PartialEq<V2>, S1: BuildHasher, S2: BuildHasher,

Two collections are equal when they have the same keys with equal values, in any order (as discord.js’ equals).

Source§

fn eq(&self, other: &Collection<K, V2, S2>) -> bool

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

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

Inequality operator !=. Read more

Auto Trait Implementations§

§

impl<K, V, S> Freeze for Collection<K, V, S>
where S: Freeze,

§

impl<K, V, S> RefUnwindSafe for Collection<K, V, S>

§

impl<K, V, S> Send for Collection<K, V, S>
where S: Send, K: Send, V: Send,

§

impl<K, V, S> Sync for Collection<K, V, S>
where S: Sync, K: Sync, V: Sync,

§

impl<K, V, S> Unpin for Collection<K, V, S>
where S: Unpin, K: Unpin, V: Unpin,

§

impl<K, V, S> UnsafeUnpin for Collection<K, V, S>
where S: UnsafeUnpin,

§

impl<K, V, S> UnwindSafe for Collection<K, V, S>
where S: UnwindSafe, K: UnwindSafe, 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
§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
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.