djs_collection/collection.rs
1//! [`Collection`]: an insertion-ordered map with discord.js' helpers.
2
3use core::{
4 borrow::Borrow,
5 cmp::Ordering,
6 fmt,
7 hash::{BuildHasher, Hash},
8 ops::Index,
9};
10
11use indexmap::IndexMap;
12
13use crate::{
14 iter::{IntoIter, IntoKeys, IntoValues, Iter, IterMut, Keys, Values, ValuesMut},
15 random,
16};
17
18/// The default hasher of a [`Collection`]: foldhash's fast hasher with a random seed
19/// (D-216), as in `djs-cache`.
20pub type DefaultHashBuilder = foldhash::fast::RandomState;
21
22/// A map that remembers the order its keys were first inserted in, with the helpers of
23/// discord.js' `Collection`.
24///
25/// Iteration, [`first`](Self::first), [`last`](Self::last), [`at`](Self::at) and
26/// [`random`](Self::random) follow insertion order (D-209); inserting an existing key replaces
27/// its value in place, and [`remove`](Self::remove) keeps the order of the rest (D-215).
28/// Lookups are hash-based, with foldhash by default (D-216).
29///
30/// The helpers follow discord.js (D-210), with Rust's ownership (D-214):
31///
32/// - reading — [`find`](Self::find), [`first`](Self::first), [`at`](Self::at),
33/// [`has_all`](Self::has_all), [`map`](Self::map), … — takes `&self`;
34/// - changing in place — [`sweep`](Self::sweep), [`sort_by`](Self::sort_by),
35/// [`reverse`](Self::reverse), [`ensure`](Self::ensure) — takes `&mut self`;
36/// - building a new collection — [`filter`](Self::filter), [`partition`](Self::partition),
37/// [`map_values`](Self::map_values), [`union`](Self::union), … — consumes the collection
38/// and clones nothing (call `.clone()` first to keep the original).
39///
40/// discord.js' `each`, `some`, `every`, `reduce` and `tap` have no counterpart: use the
41/// iterators (`.values().any(…)`, `.iter().fold(…)`, …). Callbacks receive the value first
42/// and the key second, as in discord.js.
43///
44/// discord.js counterpart: `Collection` (`@discordjs/collection`).
45///
46/// # Examples
47///
48/// ```
49/// use djs_collection::Collection;
50///
51/// let mut scores: Collection<&str, u32> = Collection::new();
52/// scores.insert("ada", 31);
53/// scores.insert("grace", 27);
54/// scores.insert("linus", 40);
55///
56/// assert_eq!(scores.first(), Some(&31));
57/// assert_eq!(scores.find_key(|&score, _| score > 30), Some(&"ada"));
58///
59/// scores.sort_by(|a, b, _, _| b.cmp(a));
60/// assert_eq!(scores.keys().copied().collect::<Vec<_>>(), ["linus", "ada", "grace"]);
61///
62/// let (high, low) = scores.partition(|&score, _| score >= 30);
63/// assert_eq!(high.len(), 2);
64/// assert_eq!(low.get("grace"), Some(&27));
65/// ```
66#[derive(Clone)]
67pub struct Collection<K, V, S = DefaultHashBuilder> {
68 map: IndexMap<K, V, S>,
69}
70
71impl<K, V> Collection<K, V> {
72 /// Creates an empty collection.
73 ///
74 /// discord.js counterpart: `new Collection()`.
75 #[must_use]
76 pub fn new() -> Self {
77 Self::with_hasher(DefaultHashBuilder::default())
78 }
79
80 /// Creates an empty collection with room for `capacity` entries before it reallocates.
81 ///
82 /// discord.js counterpart: none (JavaScript maps have no capacity).
83 #[must_use]
84 pub fn with_capacity(capacity: usize) -> Self {
85 Self::with_capacity_and_hasher(capacity, DefaultHashBuilder::default())
86 }
87}
88
89impl<K, V, S> Collection<K, V, S> {
90 /// Creates an empty collection hashing keys with `hasher`.
91 ///
92 /// discord.js counterpart: none (JavaScript maps have no hasher).
93 #[must_use]
94 pub const fn with_hasher(hasher: S) -> Self {
95 Self {
96 map: IndexMap::with_hasher(hasher),
97 }
98 }
99
100 /// Creates an empty collection with room for `capacity` entries, hashing with `hasher`.
101 ///
102 /// discord.js counterpart: none (JavaScript maps have no capacity or hasher).
103 #[must_use]
104 pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> Self {
105 Self {
106 map: IndexMap::with_capacity_and_hasher(capacity, hasher),
107 }
108 }
109
110 /// The number of entries.
111 ///
112 /// discord.js counterpart: `size`.
113 #[must_use]
114 pub fn len(&self) -> usize {
115 self.map.len()
116 }
117
118 /// Whether there are no entries.
119 ///
120 /// discord.js counterpart: `collection.size === 0`.
121 #[must_use]
122 pub fn is_empty(&self) -> bool {
123 self.map.is_empty()
124 }
125
126 /// How many entries fit before the collection reallocates.
127 ///
128 /// discord.js counterpart: none (JavaScript maps have no capacity).
129 #[must_use]
130 pub fn capacity(&self) -> usize {
131 self.map.capacity()
132 }
133
134 /// Removes every entry, keeping the memory for reuse.
135 ///
136 /// discord.js counterpart: `clear`.
137 pub fn clear(&mut self) {
138 self.map.clear();
139 }
140
141 /// The hasher keys are hashed with.
142 ///
143 /// discord.js counterpart: none (JavaScript maps have no hasher).
144 #[must_use]
145 pub fn hasher(&self) -> &S {
146 self.map.hasher()
147 }
148
149 /// The entries in order, as `(&key, &value)`.
150 ///
151 /// discord.js counterpart: `entries`.
152 pub fn iter(&self) -> Iter<'_, K, V> {
153 Iter(self.map.iter())
154 }
155
156 /// The entries in order, with mutable values.
157 ///
158 /// discord.js counterpart: none (JavaScript values are mutated in place).
159 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
160 IterMut(self.map.iter_mut())
161 }
162
163 /// The keys in order.
164 ///
165 /// discord.js counterpart: `keys`.
166 pub fn keys(&self) -> Keys<'_, K, V> {
167 Keys(self.map.keys())
168 }
169
170 /// The values in order.
171 ///
172 /// discord.js counterpart: `values`.
173 pub fn values(&self) -> Values<'_, K, V> {
174 Values(self.map.values())
175 }
176
177 /// The values in order, mutable.
178 ///
179 /// discord.js counterpart: none (JavaScript values are mutated in place).
180 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
181 ValuesMut(self.map.values_mut())
182 }
183
184 /// The keys in order, moved out of the collection.
185 ///
186 /// discord.js counterpart: `Map#keys`.
187 pub fn into_keys(self) -> IntoKeys<K, V> {
188 IntoKeys(self.map.into_keys())
189 }
190
191 /// The values in order, moved out of the collection.
192 ///
193 /// discord.js counterpart: `Map#values`.
194 pub fn into_values(self) -> IntoValues<K, V> {
195 IntoValues(self.map.into_values())
196 }
197
198 /// The inner `IndexMap`, for operations this type does not offer (D-217).
199 ///
200 /// discord.js counterpart: none (the `Map` a `Collection` extends).
201 #[must_use]
202 pub const fn as_index_map(&self) -> &IndexMap<K, V, S> {
203 &self.map
204 }
205
206 /// The inner `IndexMap`, mutable (D-217).
207 ///
208 /// discord.js counterpart: none (the `Map` a `Collection` extends).
209 pub const fn as_index_map_mut(&mut self) -> &mut IndexMap<K, V, S> {
210 &mut self.map
211 }
212
213 /// Turns the collection into its inner `IndexMap` (D-217).
214 ///
215 /// discord.js counterpart: none (the `Map` a `Collection` extends).
216 #[must_use]
217 pub fn into_index_map(self) -> IndexMap<K, V, S> {
218 self.map
219 }
220
221 /// The first value inserted, or `None` if the collection is empty. The first `n` are
222 /// `.values().take(n)`.
223 ///
224 /// discord.js counterpart: `first()`.
225 #[must_use]
226 pub fn first(&self) -> Option<&V> {
227 self.map.first().map(|(_, value)| value)
228 }
229
230 /// The first key inserted.
231 ///
232 /// discord.js counterpart: `firstKey()`.
233 #[must_use]
234 pub fn first_key(&self) -> Option<&K> {
235 self.map.first().map(|(key, _)| key)
236 }
237
238 /// The last value inserted. The last `n` are `.values().rev().take(n)`.
239 ///
240 /// discord.js counterpart: `last()`.
241 #[must_use]
242 pub fn last(&self) -> Option<&V> {
243 self.map.last().map(|(_, value)| value)
244 }
245
246 /// The last key inserted.
247 ///
248 /// discord.js counterpart: `lastKey()`.
249 #[must_use]
250 pub fn last_key(&self) -> Option<&K> {
251 self.map.last().map(|(key, _)| key)
252 }
253
254 /// The position `index` counts to: from the start, or from the end when negative.
255 fn position(&self, index: isize) -> Option<usize> {
256 if index >= 0 {
257 usize::try_from(index).ok()
258 } else {
259 self.len().checked_sub(index.unsigned_abs())
260 }
261 }
262
263 /// The value at position `index` in insertion order; a negative index counts from the
264 /// end (`-1` is the last).
265 ///
266 /// discord.js counterpart: `at`.
267 ///
268 /// # Examples
269 ///
270 /// ```
271 /// use djs_collection::Collection;
272 ///
273 /// let letters: Collection<u8, char> = [(1, 'a'), (2, 'b'), (3, 'c')].into();
274 /// assert_eq!(letters.at(0), Some(&'a'));
275 /// assert_eq!(letters.at(-1), Some(&'c'));
276 /// assert_eq!(letters.at(3), None);
277 /// assert_eq!(letters.key_at(-3), Some(&1));
278 /// ```
279 #[must_use]
280 pub fn at(&self, index: isize) -> Option<&V> {
281 let position = self.position(index)?;
282 self.map.get_index(position).map(|(_, value)| value)
283 }
284
285 /// The key at position `index`; a negative index counts from the end.
286 ///
287 /// discord.js counterpart: `keyAt`.
288 #[must_use]
289 pub fn key_at(&self, index: isize) -> Option<&K> {
290 let position = self.position(index)?;
291 self.map.get_index(position).map(|(key, _)| key)
292 }
293
294 /// A random value, or `None` if the collection is empty.
295 ///
296 /// The randomness comes from std's `RandomState` (D-210): fine for games and giveaways,
297 /// not for anything that must resist prediction.
298 ///
299 /// discord.js counterpart: `random()`.
300 #[must_use]
301 pub fn random(&self) -> Option<&V> {
302 self.random_entry().map(|(_, value)| value)
303 }
304
305 /// A random key.
306 ///
307 /// discord.js counterpart: `randomKey()`.
308 #[must_use]
309 pub fn random_key(&self) -> Option<&K> {
310 self.random_entry().map(|(key, _)| key)
311 }
312
313 fn random_entry(&self) -> Option<(&K, &V)> {
314 if self.is_empty() {
315 return None;
316 }
317 self.map.get_index(random::Rng::new().below(self.len()))
318 }
319
320 /// Up to `count` different random values, in random order — all of them, shuffled, if
321 /// `count` is at least the length.
322 ///
323 /// discord.js counterpart: `random(amount)`.
324 ///
325 /// # Examples
326 ///
327 /// ```
328 /// use djs_collection::Collection;
329 ///
330 /// let entrants: Collection<u64, &str> = [(1, "ada"), (2, "grace"), (3, "linus")].into();
331 /// let winners = entrants.random_n(2);
332 /// assert_eq!(winners.len(), 2);
333 /// assert_ne!(winners[0], winners[1]);
334 /// ```
335 #[must_use]
336 pub fn random_n(&self, count: usize) -> Vec<&V> {
337 let count = count.min(self.len());
338 random::distinct(self.len(), count)
339 .into_iter()
340 .filter_map(|index| self.map.get_index(index).map(|(_, value)| value))
341 .collect()
342 }
343
344 /// The first value for which `predicate(value, key)` is true.
345 ///
346 /// discord.js counterpart: `find`.
347 pub fn find(&self, mut predicate: impl FnMut(&V, &K) -> bool) -> Option<&V> {
348 self.iter()
349 .find(|&(key, value)| predicate(value, key))
350 .map(|(_, value)| value)
351 }
352
353 /// The key of the first value for which `predicate(value, key)` is true.
354 ///
355 /// discord.js counterpart: `findKey`.
356 pub fn find_key(&self, mut predicate: impl FnMut(&V, &K) -> bool) -> Option<&K> {
357 self.iter()
358 .find(|&(key, value)| predicate(value, key))
359 .map(|(key, _)| key)
360 }
361
362 /// The last value for which `predicate(value, key)` is true.
363 ///
364 /// discord.js counterpart: `findLast`.
365 pub fn find_last(&self, mut predicate: impl FnMut(&V, &K) -> bool) -> Option<&V> {
366 self.iter()
367 .rev()
368 .find(|&(key, value)| predicate(value, key))
369 .map(|(_, value)| value)
370 }
371
372 /// The key of the last value for which `predicate(value, key)` is true.
373 ///
374 /// discord.js counterpart: `findLastKey`.
375 pub fn find_last_key(&self, mut predicate: impl FnMut(&V, &K) -> bool) -> Option<&K> {
376 self.iter()
377 .rev()
378 .find(|&(key, value)| predicate(value, key))
379 .map(|(key, _)| key)
380 }
381
382 /// `f(value, key)` of every entry, in order.
383 ///
384 /// discord.js counterpart: `map`.
385 ///
386 /// # Examples
387 ///
388 /// ```
389 /// use djs_collection::Collection;
390 ///
391 /// let users: Collection<u64, &str> = [(1, "ada"), (2, "grace")].into();
392 /// assert_eq!(users.map(|name, id| format!("{id}:{name}")), ["1:ada", "2:grace"]);
393 /// ```
394 pub fn map<T>(&self, mut f: impl FnMut(&V, &K) -> T) -> Vec<T> {
395 self.iter().map(|(key, value)| f(value, key)).collect()
396 }
397
398 /// Reverses the order of the entries.
399 ///
400 /// discord.js counterpart: `reverse`.
401 pub fn reverse(&mut self) {
402 self.map.reverse();
403 }
404
405 /// The collection with its entries in reverse order.
406 ///
407 /// discord.js counterpart: `toReversed`.
408 #[must_use]
409 pub fn to_reversed(mut self) -> Self {
410 self.reverse();
411 self
412 }
413
414 /// Sorts the entries with `compare(value_a, value_b, key_a, key_b)`, keeping the order of
415 /// equal ones.
416 ///
417 /// discord.js counterpart: `sort(compareFunction)`.
418 pub fn sort_by(&mut self, mut compare: impl FnMut(&V, &V, &K, &K) -> Ordering) {
419 self.map
420 .sort_by(|key_a, value_a, key_b, value_b| compare(value_a, value_b, key_a, key_b));
421 }
422
423 /// The collection sorted with `compare(value_a, value_b, key_a, key_b)`.
424 ///
425 /// discord.js counterpart: `toSorted(compareFunction)`.
426 #[must_use]
427 pub fn to_sorted_by(mut self, compare: impl FnMut(&V, &V, &K, &K) -> Ordering) -> Self {
428 self.sort_by(compare);
429 self
430 }
431
432 /// Sorts the entries by value, keeping the order of equal ones.
433 ///
434 /// discord.js counterpart: `sort()` (which compares values as strings).
435 pub fn sort(&mut self)
436 where
437 V: Ord,
438 {
439 self.map.sort_by(|_, a, _, b| a.cmp(b));
440 }
441
442 /// The collection sorted by value.
443 ///
444 /// discord.js counterpart: `toSorted()`.
445 #[must_use]
446 pub fn to_sorted(mut self) -> Self
447 where
448 V: Ord,
449 {
450 self.sort();
451 self
452 }
453}
454
455impl<K, V, S> Collection<K, V, S>
456where
457 K: Hash + Eq,
458 S: BuildHasher,
459{
460 /// The value of `key`.
461 ///
462 /// discord.js counterpart: `get`.
463 #[must_use]
464 pub fn get<Q>(&self, key: &Q) -> Option<&V>
465 where
466 K: Borrow<Q>,
467 Q: Hash + Eq + ?Sized,
468 {
469 self.map.get(key)
470 }
471
472 /// The value of `key`, mutable.
473 ///
474 /// discord.js counterpart: none (JavaScript values are mutated in place).
475 #[must_use]
476 pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
477 where
478 K: Borrow<Q>,
479 Q: Hash + Eq + ?Sized,
480 {
481 self.map.get_mut(key)
482 }
483
484 /// The stored key equal to `key`, with its value.
485 ///
486 /// discord.js counterpart: none (`Map#get` returns the value only).
487 #[must_use]
488 pub fn get_key_value<Q>(&self, key: &Q) -> Option<(&K, &V)>
489 where
490 K: Borrow<Q>,
491 Q: Hash + Eq + ?Sized,
492 {
493 self.map.get_key_value(key)
494 }
495
496 /// Whether `key` has a value.
497 ///
498 /// discord.js counterpart: `has`.
499 #[must_use]
500 pub fn contains_key<Q>(&self, key: &Q) -> bool
501 where
502 K: Borrow<Q>,
503 Q: Hash + Eq + ?Sized,
504 {
505 self.map.contains_key(key)
506 }
507
508 /// The position of `key` in insertion order.
509 ///
510 /// discord.js counterpart: none (the inverse of `Collection#keyAt`).
511 #[must_use]
512 pub fn index_of<Q>(&self, key: &Q) -> Option<usize>
513 where
514 K: Borrow<Q>,
515 Q: Hash + Eq + ?Sized,
516 {
517 self.map.get_index_of(key)
518 }
519
520 /// Sets the value of `key`, returning the previous one. A new key goes last; an existing
521 /// key keeps its position.
522 ///
523 /// discord.js counterpart: `set`.
524 pub fn insert(&mut self, key: K, value: V) -> Option<V> {
525 self.map.insert(key, value)
526 }
527
528 /// Removes `key`, returning its value; the entries after it move up, so the order is
529 /// kept (O(n), D-215). [`swap_remove`](Self::swap_remove) is O(1).
530 ///
531 /// To remove many entries, use one [`sweep`](Self::sweep) or [`retain`](Self::retain)
532 /// pass, which is linear however many it removes: removing 1 000 entries near the front
533 /// of a million one by one moves the rest 1 000 times (seconds instead of milliseconds).
534 ///
535 /// discord.js counterpart: `delete`.
536 pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
537 where
538 K: Borrow<Q>,
539 Q: Hash + Eq + ?Sized,
540 {
541 self.map.shift_remove(key)
542 }
543
544 /// Removes `key`, returning the stored key and its value, keeping the order.
545 ///
546 /// discord.js counterpart: `Map#delete`.
547 pub fn remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V)>
548 where
549 K: Borrow<Q>,
550 Q: Hash + Eq + ?Sized,
551 {
552 self.map.shift_remove_entry(key)
553 }
554
555 /// Removes `key` in O(1) by moving the last entry into its place, so the order changes.
556 ///
557 /// discord.js counterpart: none (`Map#delete` keeps the order).
558 pub fn swap_remove<Q>(&mut self, key: &Q) -> Option<V>
559 where
560 K: Borrow<Q>,
561 Q: Hash + Eq + ?Sized,
562 {
563 self.map.swap_remove(key)
564 }
565
566 /// The value of `key`, inserting `default(&key)` first if there is none.
567 ///
568 /// discord.js counterpart: `ensure`.
569 ///
570 /// # Examples
571 ///
572 /// ```
573 /// use djs_collection::Collection;
574 ///
575 /// let mut warnings: Collection<u64, u32> = Collection::new();
576 /// *warnings.ensure(1, |_| 0) += 1;
577 /// *warnings.ensure(1, |_| 0) += 1;
578 /// assert_eq!(warnings.get(&1), Some(&2));
579 /// ```
580 pub fn ensure(&mut self, key: K, default: impl FnOnce(&K) -> V) -> &mut V {
581 self.map.entry(key).or_insert_with_key(default)
582 }
583
584 /// Whether every key of `keys` has a value.
585 ///
586 /// discord.js counterpart: `hasAll`.
587 pub fn has_all<'q, Q>(&self, keys: impl IntoIterator<Item = &'q Q>) -> bool
588 where
589 K: Borrow<Q>,
590 Q: Hash + Eq + ?Sized + 'q,
591 {
592 keys.into_iter().all(|key| self.contains_key(key))
593 }
594
595 /// Whether any key of `keys` has a value.
596 ///
597 /// discord.js counterpart: `hasAny`.
598 pub fn has_any<'q, Q>(&self, keys: impl IntoIterator<Item = &'q Q>) -> bool
599 where
600 K: Borrow<Q>,
601 Q: Hash + Eq + ?Sized + 'q,
602 {
603 keys.into_iter().any(|key| self.contains_key(key))
604 }
605
606 /// Keeps only the entries for which `keep(&key, &mut value)` is true, in one pass that
607 /// keeps the order.
608 ///
609 /// discord.js counterpart: `Collection#sweep`, with the condition inverted.
610 pub fn retain(&mut self, mut keep: impl FnMut(&K, &mut V) -> bool) {
611 self.map.retain(|key, value| keep(key, value));
612 }
613
614 /// Removes the entries for which `remove(value, key)` is true, in one pass that keeps the
615 /// order, and returns how many were removed.
616 ///
617 /// discord.js counterpart: `sweep`.
618 ///
619 /// # Examples
620 ///
621 /// ```
622 /// use djs_collection::Collection;
623 ///
624 /// let mut ages: Collection<&str, u32> = [("a", 3), ("b", 40), ("c", 7)].into();
625 /// assert_eq!(ages.sweep(|&age, _| age < 10), 2);
626 /// assert_eq!(ages.len(), 1);
627 /// ```
628 pub fn sweep(&mut self, mut remove: impl FnMut(&V, &K) -> bool) -> usize {
629 let before = self.len();
630 self.map.retain(|key, value| !remove(value, key));
631 before - self.len()
632 }
633
634 /// The entries for which `keep(value, key)` is true, in order (D-214: the collection is
635 /// consumed).
636 ///
637 /// discord.js counterpart: `filter`.
638 #[must_use]
639 pub fn filter(mut self, keep: impl FnMut(&V, &K) -> bool) -> Self {
640 self.sweep(not(keep));
641 self
642 }
643
644 /// Splits the entries in two, in order: those for which `predicate(value, key)` is true,
645 /// and the others.
646 ///
647 /// discord.js counterpart: `partition`.
648 #[must_use]
649 pub fn partition(self, mut predicate: impl FnMut(&V, &K) -> bool) -> (Self, Self)
650 where
651 S: Clone,
652 {
653 // The passing entries move to a new map; the others stay where they are, unhashed.
654 let mut failed = self.map;
655 let mut passed = IndexMap::with_hasher(failed.hasher().clone());
656 passed.extend(failed.extract_if(.., |key, value| predicate(value, key)));
657 (Self { map: passed }, Self { map: failed })
658 }
659
660 /// A collection with the same keys and the values `f(value, &key)`, in order.
661 ///
662 /// discord.js counterpart: `mapValues`.
663 #[must_use]
664 pub fn map_values<T>(self, mut f: impl FnMut(V, &K) -> T) -> Collection<K, T, S>
665 where
666 S: Clone,
667 {
668 let mut mapped =
669 Collection::with_capacity_and_hasher(self.len(), self.map.hasher().clone());
670 for (key, value) in self.map {
671 let value = f(value, &key);
672 mapped.map.insert(key, value);
673 }
674 mapped
675 }
676
677 /// The collections `f(value, key)` of every entry, joined in order; a later value of a
678 /// key replaces an earlier one.
679 ///
680 /// discord.js counterpart: `flatMap`.
681 #[must_use]
682 pub fn flat_map<K2, V2, S2>(
683 self,
684 mut f: impl FnMut(V, K) -> Collection<K2, V2, S2>,
685 ) -> Collection<K2, V2, S2>
686 where
687 K2: Hash + Eq,
688 S2: BuildHasher + Default,
689 {
690 let mut joined = Collection::with_hasher(S2::default());
691 for (key, value) in self.map {
692 joined.map.extend(f(value, key).map);
693 }
694 joined
695 }
696
697 /// The collection with the entries of `others` added in order; an existing key gets the
698 /// later value and keeps its position.
699 ///
700 /// discord.js counterpart: `concat`.
701 #[must_use]
702 pub fn concat<S2>(mut self, others: impl IntoIterator<Item = Collection<K, V, S2>>) -> Self {
703 for other in others {
704 self.map.extend(other.map);
705 }
706 self
707 }
708
709 /// The entries of the collection, then those of `other` whose keys it does not have.
710 ///
711 /// discord.js counterpart: `union`.
712 #[must_use]
713 pub fn union<S2>(mut self, other: Collection<K, V, S2>) -> Self {
714 for (key, value) in other.map {
715 self.map.entry(key).or_insert(value);
716 }
717 self
718 }
719
720 /// The entries whose keys `other` also has, in this collection's order.
721 ///
722 /// discord.js counterpart: `intersection`.
723 #[must_use]
724 pub fn intersection<V2, S2: BuildHasher>(mut self, other: &Collection<K, V2, S2>) -> Self {
725 self.map.retain(|key, _| other.contains_key(key));
726 self
727 }
728
729 /// The entries whose keys `other` does not have.
730 ///
731 /// discord.js counterpart: `difference`.
732 #[must_use]
733 pub fn difference<V2, S2: BuildHasher>(mut self, other: &Collection<K, V2, S2>) -> Self {
734 self.map.retain(|key, _| !other.contains_key(key));
735 self
736 }
737
738 /// The entries whose keys only one of the two collections has: this one's, then
739 /// `other`'s.
740 ///
741 /// discord.js counterpart: `symmetricDifference`.
742 #[must_use]
743 pub fn symmetric_difference<S2: BuildHasher>(mut self, other: Collection<K, V, S2>) -> Self {
744 let mut other = other.map;
745 let mut shared = vec![false; other.len()];
746 self.map.retain(|key, _| match other.get_index_of(key) {
747 Some(index) => {
748 shared[index] = true;
749 false
750 }
751 None => true,
752 });
753 let mut index = 0;
754 other.retain(|_, _| {
755 let keep = !shared[index];
756 index += 1;
757 keep
758 });
759 self.map.extend(other);
760 self
761 }
762
763 /// Combines this collection with `other` key by key, in the order of this collection's
764 /// keys and then `other`'s new ones: `in_self(value, key)` for a key only here,
765 /// `in_other(value, key)` for a key only in `other`, `in_both(value, other_value, key)`
766 /// for both. A key is kept when its function returns `Some`.
767 ///
768 /// discord.js counterpart: `merge` (`Some(value)` is `{ keep: true, value }`).
769 ///
770 /// # Examples
771 ///
772 /// ```
773 /// use djs_collection::Collection;
774 ///
775 /// let before: Collection<&str, u32> = [("ada", 1), ("grace", 2)].into();
776 /// let after: Collection<&str, u32> = [("grace", 5), ("linus", 3)].into();
777 /// let changes = before.merge(
778 /// after,
779 /// |_, _| Some("left"),
780 /// |_, _| Some("joined"),
781 /// |old, new, _| (old != new).then_some("changed"),
782 /// );
783 /// assert_eq!(changes.iter().collect::<Vec<_>>(), [(&"ada", &"left"), (&"grace", &"changed"), (&"linus", &"joined")]);
784 /// ```
785 #[must_use]
786 pub fn merge<O, R, S2: BuildHasher>(
787 self,
788 other: Collection<K, O, S2>,
789 mut in_self: impl FnMut(V, &K) -> Option<R>,
790 mut in_other: impl FnMut(O, &K) -> Option<R>,
791 mut in_both: impl FnMut(V, O, &K) -> Option<R>,
792 ) -> Collection<K, R, S>
793 where
794 S: Clone,
795 {
796 let matches: Vec<Option<usize>> = self
797 .map
798 .keys()
799 .map(|key| other.map.get_index_of(key))
800 .collect();
801 let mut others: Vec<Option<(K, O)>> = other.map.into_iter().map(Some).collect();
802 let mut merged = Collection::with_capacity_and_hasher(
803 self.map.len().max(others.len()),
804 self.map.hasher().clone(),
805 );
806 for ((key, value), matched) in self.map.into_iter().zip(matches) {
807 let result = match matched.and_then(|index| others[index].take()) {
808 Some((_, other_value)) => in_both(value, other_value, &key),
809 None => in_self(value, &key),
810 };
811 if let Some(result) = result {
812 merged.map.insert(key, result);
813 }
814 }
815 for (key, value) in others.into_iter().flatten() {
816 if let Some(result) = in_other(value, &key) {
817 merged.map.insert(key, result);
818 }
819 }
820 merged
821 }
822
823 /// A collection of `entries` in order, where a repeated key gets
824 /// `combine(earlier_value, later_value, key)`.
825 ///
826 /// discord.js counterpart: `Collection.combineEntries`.
827 ///
828 /// # Examples
829 ///
830 /// ```
831 /// use djs_collection::Collection;
832 ///
833 /// let votes = [("yes", 1), ("no", 1), ("yes", 1)];
834 /// let totals: Collection<&str, u32> = Collection::combine_entries(votes, |a, b, _| a + b);
835 /// assert_eq!(totals.get("yes"), Some(&2));
836 /// ```
837 #[must_use]
838 pub fn combine_entries(
839 entries: impl IntoIterator<Item = (K, V)>,
840 mut combine: impl FnMut(V, V, &K) -> V,
841 ) -> Self
842 where
843 S: Default,
844 {
845 let mut combined: IndexMap<K, Option<V>, S> = IndexMap::default();
846 for (key, value) in entries {
847 match combined.entry(key) {
848 indexmap::map::Entry::Occupied(mut entry) => {
849 let earlier = entry.get_mut().take();
850 let value = match earlier {
851 Some(earlier) => combine(earlier, value, entry.key()),
852 None => value,
853 };
854 *entry.get_mut() = Some(value);
855 }
856 indexmap::map::Entry::Vacant(entry) => {
857 entry.insert(Some(value));
858 }
859 }
860 }
861 let mut collection = Self::with_capacity_and_hasher(combined.len(), S::default());
862 collection.map.extend(
863 combined
864 .into_iter()
865 .filter_map(|(key, value)| Some((key, value?))),
866 );
867 collection
868 }
869}
870
871/// Negates a predicate.
872fn not<V, K>(mut predicate: impl FnMut(&V, &K) -> bool) -> impl FnMut(&V, &K) -> bool {
873 move |value, key| !predicate(value, key)
874}
875
876impl<K, V, S: Default> Default for Collection<K, V, S> {
877 fn default() -> Self {
878 Self::with_hasher(S::default())
879 }
880}
881
882impl<K: fmt::Debug, V: fmt::Debug, S> fmt::Debug for Collection<K, V, S> {
883 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
884 f.debug_map().entries(self.iter()).finish()
885 }
886}
887
888/// Two collections are equal when they have the same keys with equal values, in any order
889/// (as discord.js' `equals`).
890impl<K, V1, S1, V2, S2> PartialEq<Collection<K, V2, S2>> for Collection<K, V1, S1>
891where
892 K: Hash + Eq,
893 V1: PartialEq<V2>,
894 S1: BuildHasher,
895 S2: BuildHasher,
896{
897 fn eq(&self, other: &Collection<K, V2, S2>) -> bool {
898 self.map == other.map
899 }
900}
901
902impl<K: Hash + Eq, V: Eq, S: BuildHasher> Eq for Collection<K, V, S> {}
903
904/// Indexing by key.
905///
906/// # Panics
907///
908/// If the key has no value; use [`Collection::get`] when it may not.
909impl<K, V, Q, S> Index<&Q> for Collection<K, V, S>
910where
911 K: Hash + Eq + Borrow<Q>,
912 Q: Hash + Eq + ?Sized,
913 S: BuildHasher,
914{
915 type Output = V;
916
917 fn index(&self, key: &Q) -> &V {
918 self.get(key)
919 .expect("the collection has no entry for this key")
920 }
921}
922
923impl<K: Hash + Eq, V, S: BuildHasher + Default> FromIterator<(K, V)> for Collection<K, V, S> {
924 fn from_iter<I: IntoIterator<Item = (K, V)>>(entries: I) -> Self {
925 Self {
926 map: IndexMap::from_iter(entries),
927 }
928 }
929}
930
931impl<K: Hash + Eq, V, S: BuildHasher> Extend<(K, V)> for Collection<K, V, S> {
932 fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, entries: I) {
933 self.map.extend(entries);
934 }
935}
936
937impl<K: Hash + Eq, V, const N: usize> From<[(K, V); N]> for Collection<K, V> {
938 fn from(entries: [(K, V); N]) -> Self {
939 entries.into_iter().collect()
940 }
941}
942
943impl<K, V, S> From<IndexMap<K, V, S>> for Collection<K, V, S> {
944 fn from(map: IndexMap<K, V, S>) -> Self {
945 Self { map }
946 }
947}
948
949impl<K, V, S> From<Collection<K, V, S>> for IndexMap<K, V, S> {
950 fn from(collection: Collection<K, V, S>) -> Self {
951 collection.map
952 }
953}
954
955impl<K, V, S> IntoIterator for Collection<K, V, S> {
956 type Item = (K, V);
957 type IntoIter = IntoIter<K, V>;
958
959 fn into_iter(self) -> Self::IntoIter {
960 IntoIter(self.map.into_iter())
961 }
962}
963
964impl<'a, K, V, S> IntoIterator for &'a Collection<K, V, S> {
965 type Item = (&'a K, &'a V);
966 type IntoIter = Iter<'a, K, V>;
967
968 fn into_iter(self) -> Self::IntoIter {
969 self.iter()
970 }
971}
972
973impl<'a, K, V, S> IntoIterator for &'a mut Collection<K, V, S> {
974 type Item = (&'a K, &'a mut V);
975 type IntoIter = IterMut<'a, K, V>;
976
977 fn into_iter(self) -> Self::IntoIter {
978 self.iter_mut()
979 }
980}