stry_common/utils/fenn/vec_map.rs
1//! A [`Vec`] backed map implementation.
2//!
3//! [`Vec`]: https://doc.rust-lang.org/std/vec/struct.Vec.html
4
5use {
6 super::lib::{
7 fmt,
8 vec::{Drain as VecDrain, IntoIter as VecIntoIter},
9 },
10 core::{
11 borrow::Borrow,
12 iter::{
13 DoubleEndedIterator, ExactSizeIterator, FromIterator, FusedIterator, IntoIterator,
14 Iterator, Zip,
15 },
16 marker::PhantomData,
17 ops::{Index, IndexMut},
18 slice::{Iter as SliceIter, IterMut as SliceIterMut},
19 },
20};
21
22/// Create a [`VecMap`](../vec_map/struct.VecMap.html) from a list of key-value pairs.
23///
24/// While based off of [maplit](https://github.com/bluss/maplit), this is an
25/// extended version with the ability to enable a `strict` mode.
26///
27/// # Examples
28///
29/// ```
30/// let map = fenn::vecmap! {
31/// "a" => 1,
32/// "b" => 2,
33/// };
34///
35/// assert_eq!(map["a"], 1);
36/// assert_eq!(map["b"], 2);
37/// assert_eq!(map.get("c"), None);
38/// ```
39///
40/// When `strict` mode is active, a duplicate key will cause a panic.
41///
42/// ```should_panic
43/// let map = fenn::vecmap! {
44/// strict,
45/// data = {
46/// "a" => 1,
47/// "a" => 2, // panics
48/// }
49/// };
50/// ```
51#[macro_export]
52macro_rules! vecmap {
53 (@single $($x:tt)*) => (());
54 (@count $($rest:expr),*) => (<[()]>::len(&[ $($crate::vecmap!(@single $rest)),* ]));
55
56 ( strict, data = { $( $key:expr => $value:expr, )+ } $( , )? ) => {{
57 $crate::vecmap!(strict, data = { $( $key => $value ),+ })
58 }};
59 ( strict, data = { $( $key:expr => $value:expr ),* } $( , )? ) => {{
60 use $crate::{vec_map::VecMapExt, Peep};
61 let _cap = $crate::vecmap!(@count $($key),*);
62 $crate::vec_map::VecMap::with_capacity(_cap)
63 $(
64 .peep(|map| assert!(map.get(&$key).is_some()) )
65 .inserted($key, $value)
66 )*
67 }};
68
69 ( $( $key:expr => $value:expr, )+ ) => {{
70 $crate::vecmap!( $( $key => $value ),+ )
71 }};
72 ( $( $key:expr => $value:expr ),* ) => {{
73 use $crate::vec_map::VecMapExt;
74 let _cap = $crate::vecmap!(@count $($key),*);
75 $crate::vec_map::VecMap::with_capacity(_cap)
76 $(
77 .inserted($key, $value)
78 )*
79 }};
80
81 () => {
82 $crate::vec_map::VecMap::new()
83 };
84}
85
86/// A [`Vec`] backed map implementation.
87///
88/// [`Vec`]: https://doc.rust-lang.org/std/vec/struct.Vec.html
89// TODO: Better docs for this
90pub struct VecMap<K, V> {
91 keys: Vec<K>,
92 values: Vec<V>,
93}
94
95impl<K, V> VecMap<K, V> {
96 /// Creates an empty [`VecMap`].
97 ///
98 /// The map is initially created with a capacity of 0, so it will not allocate until it
99 /// is first inserted into.
100 ///
101 /// [`VecMap`]: ../vec_map/struct.VecMap.html
102 ///
103 /// # Examples
104 ///
105 /// ```
106 /// use fenn::vec_map::VecMap;
107 ///
108 /// let mut map: VecMap<&str, i32> = VecMap::new();
109 /// ```
110 #[inline]
111 pub fn new() -> VecMap<K, V> {
112 VecMap::default()
113 }
114
115 /// Creates an empty [`VecMap`] with the specified capacity.
116 ///
117 /// The map will be able to hold at least `capacity` elements without
118 /// reallocating. If `capacity` is 0, the map will not allocate.
119 ///
120 /// [`VecMap`]: ../vec_map/struct.VecMap.html
121 ///
122 /// # Examples
123 ///
124 /// ```
125 /// use fenn::vec_map::VecMap;
126 ///
127 /// let mut map: VecMap<&str, i32> = VecMap::with_capacity(10);
128 /// ```
129 #[inline]
130 pub fn with_capacity(capacity: usize) -> VecMap<K, V> {
131 VecMap {
132 keys: Vec::with_capacity(capacity),
133 values: Vec::with_capacity(capacity),
134 }
135 }
136
137 /// Returns the number of elements the map can hold without reallocating.
138 ///
139 /// This number is a lower bound; the [`VecMap`]`<K, V>` might be able to hold
140 /// more, but is guaranteed to be able to hold at least this many.
141 ///
142 /// [`VecMap`]: ../vec_map/struct.VecMap.html
143 ///
144 /// # Examples
145 ///
146 /// ```
147 /// use fenn::vec_map::VecMap;
148 ///
149 /// let map: VecMap<i32, i32> = VecMap::with_capacity(100);
150 ///
151 /// assert!(map.capacity() >= 100);
152 /// ```
153 #[inline]
154 pub fn capacity(&self) -> usize {
155 self.keys.capacity().min(self.values.capacity())
156 }
157
158 /// An iterator visiting all keys in arbitrary order.
159 /// The iterator element type is `&'a K`.
160 ///
161 /// # Examples
162 ///
163 /// ```
164 /// use fenn::vec_map::VecMap;
165 ///
166 /// let mut map = VecMap::new();
167 ///
168 /// map.insert("a", 1);
169 /// map.insert("b", 2);
170 /// map.insert("c", 3);
171 ///
172 /// for key in map.keys() {
173 /// println!("{}", key);
174 /// }
175 /// ```
176 #[inline]
177 pub fn keys(&self) -> Keys<'_, K, V> {
178 Keys {
179 iter: self.keys.iter(),
180 _phantom: PhantomData,
181 }
182 }
183
184 /// An iterator visiting all values in arbitrary order.
185 /// The iterator element type is `&'a V`.
186 ///
187 /// # Examples
188 ///
189 /// ```
190 /// use fenn::vec_map::VecMap;
191 ///
192 /// let mut map = VecMap::new();
193 ///
194 /// map.insert("a", 1);
195 /// map.insert("b", 2);
196 /// map.insert("c", 3);
197 ///
198 /// for val in map.values() {
199 /// println!("{}", val);
200 /// }
201 /// ```
202 #[inline]
203 pub fn values(&self) -> Values<'_, K, V> {
204 Values {
205 iter: self.values.iter(),
206 _phantom: PhantomData,
207 }
208 }
209
210 /// An iterator visiting all values mutably in arbitrary order.
211 /// The iterator element type is `&'a mut V`.
212 ///
213 /// # Examples
214 ///
215 /// ```
216 /// use fenn::vec_map::VecMap;
217 ///
218 /// let mut map = VecMap::new();
219 ///
220 /// map.insert("a", 1);
221 /// map.insert("b", 2);
222 /// map.insert("c", 3);
223 ///
224 /// for val in map.values_mut() {
225 /// *val = *val + 10;
226 /// }
227 ///
228 /// for val in map.values() {
229 /// println!("{}", val);
230 /// }
231 /// ```
232 #[inline]
233 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
234 ValuesMut {
235 iter: self.values.iter_mut(),
236 _phantom: PhantomData,
237 }
238 }
239
240 /// An iterator visiting all key-value pairs in arbitrary order.
241 /// The iterator element type is `(&'a K, &'a V)`.
242 ///
243 /// # Examples
244 ///
245 /// ```
246 /// use fenn::vec_map::VecMap;
247 ///
248 /// let mut map = VecMap::new();
249 ///
250 /// map.insert("a", 1);
251 /// map.insert("b", 2);
252 /// map.insert("c", 3);
253 ///
254 /// for (key, val) in map.iter() {
255 /// println!("key: {} val: {}", key, val);
256 /// }
257 /// ```
258 #[inline]
259 pub fn iter(&self) -> Iter<'_, K, V> {
260 Iter {
261 iter: self.keys.iter().zip(self.values.iter()),
262 }
263 }
264 /// An iterator visiting all key-value pairs in arbitrary order,
265 /// with mutable references to the values.
266 ///
267 /// The iterator element type is `(&'a K, &'a mut V)`.
268 ///
269 /// # Examples
270 ///
271 /// ```
272 /// use fenn::vec_map::VecMap;
273 ///
274 /// let mut map = VecMap::new();
275 ///
276 /// map.insert("a", 1);
277 /// map.insert("b", 2);
278 /// map.insert("c", 3);
279 ///
280 /// // Update all values
281 /// for (_, val) in map.iter_mut() {
282 /// *val *= 2;
283 /// }
284 ///
285 /// for (key, val) in &map {
286 /// println!("key: {} val: {}", key, val);
287 /// }
288 /// ```
289 #[inline]
290 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
291 IterMut {
292 iter: self.keys.iter().zip(self.values.iter_mut()),
293 }
294 }
295
296 /// Returns the number of elements in the map.
297 ///
298 /// # Examples
299 ///
300 /// ```
301 /// use fenn::vec_map::VecMap;
302 ///
303 /// let mut map = VecMap::new();
304 ///
305 /// assert_eq!(map.len(), 0);
306 ///
307 /// map.insert(1, "a");
308 ///
309 /// assert_eq!(map.len(), 1);
310 /// ```
311 #[inline]
312 pub fn len(&self) -> usize {
313 self.keys.len()
314 }
315
316 /// Returns `true` if the map contains no elements.
317 ///
318 /// # Examples
319 ///
320 /// ```
321 /// use fenn::vec_map::VecMap;
322 ///
323 /// let mut map = VecMap::new();
324 ///
325 /// assert!(map.is_empty());
326 ///
327 /// map.insert(1, "a");
328 ///
329 /// assert!(!map.is_empty());
330 /// ```
331 #[inline]
332 pub fn is_empty(&self) -> bool {
333 self.len() == 0
334 }
335
336 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
337 /// allocated memory for reuse.
338 ///
339 /// # Examples
340 ///
341 /// ```
342 /// use fenn::vec_map::VecMap;
343 ///
344 /// let mut map = VecMap::new();
345 ///
346 /// map.insert(1, "a");
347 /// map.insert(2, "b");
348 ///
349 /// for (k, v) in map.drain().take(1) {
350 /// assert!(k == 1 || k == 2);
351 /// assert!(v == "a" || v == "b");
352 /// }
353 ///
354 /// assert!(map.is_empty());
355 /// ```
356 #[inline]
357 pub fn drain(&mut self) -> Drain<'_, K, V> {
358 Drain {
359 iter: self.keys.drain(..).zip(self.values.drain(..)),
360 }
361 }
362
363 /// Retains only the elements specified by the predicate.
364 ///
365 /// In other words, remove all pairs `(k, v)` such that `f(&k,&mut v)` returns `false`.
366 ///
367 /// # Examples
368 ///
369 /// ```
370 /// use fenn::vec_map::VecMap;
371 ///
372 /// let mut map: VecMap<i32, i32> = (0..8).map(|x|(x, x*10)).collect();
373 ///
374 /// map.retain(|&k, _| k % 2 == 0);
375 ///
376 /// assert_eq!(map.len(), 4);
377 /// ```
378 #[inline]
379 pub fn retain<F>(&mut self, mut f: F)
380 where
381 F: FnMut(&K, &mut V) -> bool,
382 {
383 for i in (0..self.len()).rev() {
384 if !f(&self.keys[i], &mut self.values[i]) {
385 self.keys.swap_remove(i);
386 self.values.swap_remove(i);
387 }
388 }
389 }
390
391 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
392 /// for reuse.
393 ///
394 /// # Examples
395 ///
396 /// ```
397 /// use fenn::vec_map::VecMap;
398 ///
399 /// let mut map = VecMap::new();
400 ///
401 /// map.insert(1, "a");
402 ///
403 /// map.clear();
404 ///
405 /// assert!(map.is_empty());
406 /// ```
407 #[inline]
408 pub fn clear(&mut self) {
409 self.keys.clear();
410 self.values.clear();
411 }
412
413 /// Reserves capacity for at least `additional` more elements to be inserted
414 /// in the [`VecMap`]. The collection may reserve more space to avoid
415 /// frequent reallocations.
416 ///
417 /// [`VecMap`]: ../vec_map/struct.VecMap.html
418 ///
419 /// # Panics
420 ///
421 /// Panics if the new allocation size overflows [`usize`].
422 ///
423 /// [`usize`]: https://doc.rust-lang.org/std/primitive.usize.html
424 ///
425 /// # Examples
426 ///
427 /// ```
428 /// use fenn::vec_map::VecMap;
429 ///
430 /// let mut map: VecMap<&str, i32> = VecMap::new();
431 ///
432 /// map.reserve(10);
433 /// ```
434 #[inline]
435 pub fn reserve(&mut self, additional: usize) {
436 self.keys.reserve(additional);
437 self.values.reserve(additional);
438 }
439
440 /// Shrinks the capacity of the map as much as possible. It will drop
441 /// down as much as possible while maintaining the internal rules
442 /// and possibly leaving some space in accordance with the resize policy.
443 ///
444 /// # Examples
445 ///
446 /// ```
447 /// use fenn::vec_map::VecMap;
448 ///
449 /// let mut map: VecMap<i32, i32> = VecMap::with_capacity(100);
450 ///
451 /// map.insert(1, 2);
452 /// map.insert(3, 4);
453 ///
454 /// assert!(map.capacity() >= 100);
455 ///
456 /// map.shrink_to_fit();
457 ///
458 /// assert!(map.capacity() >= 2);
459 /// ```
460 #[inline]
461 pub fn shrink_to_fit(&mut self) {
462 self.keys.shrink_to_fit();
463 self.values.shrink_to_fit();
464 }
465
466 #[inline]
467 pub fn truncate(&mut self, len: usize) {
468 self.keys.truncate(len);
469 self.values.truncate(len);
470 }
471}
472
473impl<K, V> VecMap<K, V>
474where
475 K: Eq,
476{
477 /// Gets the given key's corresponding entry in the map for in-place manipulation.
478 ///
479 /// # Examples
480 ///
481 /// ```
482 /// use fenn::vec_map::VecMap;
483 ///
484 /// let mut letters = VecMap::new();
485 ///
486 /// for ch in "a short treatise on fungi".chars() {
487 /// let counter = letters.entry(ch).or_insert(0);
488 ///
489 /// *counter += 1;
490 /// }
491 ///
492 /// assert_eq!(letters[&'s'], 2);
493 /// assert_eq!(letters[&'t'], 3);
494 /// assert_eq!(letters[&'u'], 1);
495 /// assert_eq!(letters.get(&'y'), None);
496 /// ```
497 #[inline]
498 pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
499 match self.iter_mut().position(|(k, _)| &key == k) {
500 Some(index) => Entry::Occupied(OccupiedEntry { index, map: self }),
501 None => Entry::Vacant(VacantEntry { key, map: self }),
502 }
503 }
504
505 /// Returns a reference to the value corresponding to the key.
506 ///
507 /// The key may be any borrowed form of the map's key type, but
508 /// [`PartialEq`] on the borrowed form *must* match those for
509 /// the key type.
510 ///
511 /// [`PartialEq`]: https://doc.rust-lang.org/std/cmp/trait.PartialEq.html
512 ///
513 /// # Examples
514 ///
515 /// ```
516 /// use fenn::vec_map::VecMap;
517 ///
518 /// let mut map = VecMap::new();
519 ///
520 /// map.insert(1, "a");
521 ///
522 /// assert_eq!(map.get(&1), Some(&"a"));
523 /// assert_eq!(map.get(&2), None);
524 /// ```
525 #[inline]
526 pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&'_ V>
527 where
528 K: Borrow<Q>,
529 Q: Eq,
530 {
531 self.keys
532 .iter()
533 .position(|k| key.eq(k.borrow()))
534 .map(|p| &self.values[p])
535 }
536
537 /// Returns the key-value pair corresponding to the supplied key.
538 ///
539 /// The supplied key may be any borrowed form of the map's key type, but
540 /// [`PartialEq`] on the borrowed form *must* match those for
541 /// the key type.
542 ///
543 /// [`PartialEq`]: https://doc.rust-lang.org/std/cmp/trait.PartialEq.html
544 ///
545 /// # Examples
546 ///
547 /// ```
548 /// use fenn::vec_map::VecMap;
549 ///
550 /// let mut map = VecMap::new();
551 ///
552 /// map.insert(1, "a");
553 ///
554 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
555 /// assert_eq!(map.get_key_value(&2), None);
556 /// ```
557 #[inline]
558 pub fn get_key_value<Q: ?Sized>(&self, key: &Q) -> Option<(&'_ K, &'_ V)>
559 where
560 K: Borrow<Q>,
561 Q: PartialEq<K>,
562 {
563 self.keys
564 .iter()
565 .position(|k| key == k)
566 .map(|p| (&self.keys[p], &self.values[p]))
567 }
568
569 /// Returns the key-value pair corresponding to the supplied key, with a mutable reference to value.
570 ///
571 /// The supplied key may be any borrowed form of the map's key type, but
572 /// [`PartialEq`] on the borrowed form *must* match those for
573 /// the key type.
574 ///
575 /// [`PartialEq`]: https://doc.rust-lang.org/std/cmp/trait.PartialEq.html
576 ///
577 /// # Examples
578 ///
579 /// ```
580 /// use fenn::vec_map::VecMap;
581 ///
582 /// let mut map = VecMap::new();
583 ///
584 /// map.insert(1, "a");
585 ///
586 /// let (k, v) = map.get_key_value_mut(&1).unwrap();
587 ///
588 /// assert_eq!(k, &1);
589 /// assert_eq!(v, &mut "a");
590 ///
591 /// *v = "b";
592 ///
593 /// assert_eq!(map.get_key_value_mut(&1), Some((&1, &mut "b")));
594 /// assert_eq!(map.get_key_value_mut(&2), None);
595 /// ```
596 #[inline]
597 pub fn get_key_value_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<(&'_ K, &'_ mut V)>
598 where
599 K: Borrow<Q>,
600 Q: PartialEq<K>,
601 {
602 self.keys
603 .iter_mut()
604 .position(|k| key == k)
605 .map(move |p| (&self.keys[p], &mut self.values[p]))
606 }
607
608 /// Returns `true` if the map contains a value for the specified key.
609 ///
610 /// The key may be any borrowed form of the map's key type, but
611 /// [`PartialEq`] on the borrowed form *must* match those for
612 /// the key type.
613 ///
614 /// [`PartialEq`]: https://doc.rust-lang.org/std/cmp/trait.PartialEq.html
615 ///
616 /// # Examples
617 ///
618 /// ```
619 /// use fenn::vec_map::VecMap;
620 ///
621 /// let mut map = VecMap::new();
622 ///
623 /// map.insert(1, "a");
624 ///
625 /// assert_eq!(map.contains_key(&1), true);
626 /// assert_eq!(map.contains_key(&2), false);
627 /// ```
628 #[inline]
629 pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
630 where
631 K: Borrow<Q>,
632 Q: PartialEq<K>,
633 {
634 self.keys.iter().any(|k| key == k)
635 }
636
637 /// Returns a mutable reference to the value corresponding to the key.
638 ///
639 /// The key may be any borrowed form of the map's key type, but
640 /// [`PartialEq`] on the borrowed form *must* match those for
641 /// the key type.
642 ///
643 /// [`PartialEq`]: https://doc.rust-lang.org/std/cmp/trait.PartialEq.html
644 ///
645 /// # Examples
646 ///
647 /// ```
648 /// use fenn::vec_map::VecMap;
649 ///
650 /// let mut map = VecMap::new();
651 ///
652 /// map.insert(1, "a");
653 ///
654 /// if let Some(x) = map.get_mut(&1) {
655 /// *x = "b";
656 /// }
657 ///
658 /// assert_eq!(map[&1], "b");
659 /// ```
660 #[inline]
661 pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&'_ mut V>
662 where
663 K: Borrow<Q>,
664 Q: Eq,
665 {
666 self.keys
667 .iter()
668 .position(|k| key.eq(k.borrow()))
669 .map(move |p| &mut self.values[p])
670 }
671
672 /// Inserts a key-value pair into the map.
673 ///
674 /// If the map did not have this key present, [`None`] is returned.
675 ///
676 /// If the map did have this key present, the value is updated, and the old
677 /// value is returned. The key is not updated, though; this matters for
678 /// types that can be `==` without being identical.
679 ///
680 /// [`None`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None
681 ///
682 /// # Examples
683 ///
684 /// ```
685 /// use fenn::vec_map::VecMap;
686 ///
687 /// let mut map = VecMap::new();
688 ///
689 /// assert_eq!(map.insert(37, "a"), None);
690 /// assert_eq!(map.is_empty(), false);
691 ///
692 /// map.insert(37, "b");
693 ///
694 /// assert_eq!(map.insert(37, "c"), Some("b"));
695 /// assert_eq!(map[&37], "c");
696 /// ```
697 #[inline]
698 pub fn insert(&mut self, key: K, mut value: V) -> Option<V> {
699 if let Some(position) = self.keys.iter().position(|k| &key == k) {
700 core::mem::swap(&mut value, &mut self.values[position]);
701
702 Some(value)
703 } else {
704 self.keys.push(key);
705 self.values.push(value);
706
707 None
708 }
709 }
710
711 /// Removes a key from the map, returning the value at the key if the key
712 /// was previously in the map.
713 ///
714 /// The key may be any borrowed form of the map's key type, but
715 /// [`PartialEq`] on the borrowed form *must* match those for
716 /// the key type.
717 ///
718 /// [`PartialEq`]: https://doc.rust-lang.org/std/cmp/trait.PartialEq.html
719 ///
720 /// # Examples
721 ///
722 /// ```
723 /// use fenn::vec_map::VecMap;
724 ///
725 /// let mut map = VecMap::new();
726 ///
727 /// map.insert(1, "a");
728 ///
729 /// assert_eq!(map.remove(&1), Some("a"));
730 /// assert_eq!(map.remove(&1), None);
731 /// ```
732 #[inline]
733 pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
734 where
735 K: Borrow<Q>,
736 Q: PartialEq<K>,
737 {
738 if let Some(index) = self.keys.iter().position(|k| key == k) {
739 self.keys.swap_remove(index);
740
741 Some(self.values.swap_remove(index))
742 } else {
743 None
744 }
745 }
746
747 /// Removes a key from the map, returning the stored key and value if the
748 /// key was previously in the map.
749 ///
750 /// The key may be any borrowed form of the map's key type, but
751 /// [`PartialEq`] on the borrowed form *must* match those for
752 /// the key type.
753 ///
754 /// [`PartialEq`]: https://doc.rust-lang.org/std/cmp/trait.PartialEq.html
755 ///
756 /// # Examples
757 ///
758 /// ```
759 /// use fenn::vec_map::VecMap;
760 ///
761 /// let mut map = VecMap::new();
762 ///
763 /// map.insert(1, "a");
764 ///
765 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
766 /// assert_eq!(map.remove(&1), None);
767 /// ```
768 #[inline]
769 pub fn remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
770 where
771 K: Borrow<Q>,
772 Q: PartialEq<K>,
773 {
774 if let Some(index) = self.keys.iter().position(|k| key == k) {
775 Some((self.keys.swap_remove(index), self.values.swap_remove(index)))
776 } else {
777 None
778 }
779 }
780}
781
782impl<'a, K, V> IntoIterator for &'a VecMap<K, V> {
783 type Item = (&'a K, &'a V);
784 type IntoIter = Iter<'a, K, V>;
785
786 #[inline]
787 fn into_iter(self) -> Self::IntoIter {
788 self.iter()
789 }
790}
791
792impl<'a, K, V> IntoIterator for &'a mut VecMap<K, V> {
793 type Item = (&'a K, &'a mut V);
794 type IntoIter = IterMut<'a, K, V>;
795
796 #[inline]
797 fn into_iter(self) -> Self::IntoIter {
798 self.iter_mut()
799 }
800}
801
802impl<K, V> IntoIterator for VecMap<K, V> {
803 type Item = (K, V);
804 type IntoIter = IntoIter<K, V>;
805
806 #[inline]
807 fn into_iter(self) -> Self::IntoIter {
808 IntoIter {
809 iter: self.keys.into_iter().zip(self.values.into_iter()),
810 }
811 }
812}
813
814impl<K, V> FromIterator<(K, V)> for VecMap<K, V>
815where
816 K: Eq,
817{
818 #[inline]
819 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
820 let iter = iter.into_iter();
821
822 let mut map = Self::with_capacity(iter.size_hint().0);
823
824 iter.for_each(|(k, v)| {
825 map.insert(k, v);
826 });
827
828 map
829 }
830}
831
832impl<K, Q: ?Sized, V> Index<&Q> for VecMap<K, V>
833where
834 K: Eq + Borrow<Q>,
835 Q: Eq,
836{
837 type Output = V;
838
839 #[inline]
840 fn index(&self, key: &Q) -> &V {
841 self.get(key).expect("no entry found for key")
842 }
843}
844
845impl<K, Q: ?Sized, V> IndexMut<&Q> for VecMap<K, V>
846where
847 K: Eq + Borrow<Q>,
848 Q: Eq,
849{
850 #[inline]
851 fn index_mut(&mut self, key: &Q) -> &mut V {
852 self.get_mut(key).expect("no entry found for key")
853 }
854}
855
856impl<K, V> Clone for VecMap<K, V>
857where
858 K: Clone,
859 V: Clone,
860{
861 #[inline]
862 fn clone(&self) -> Self {
863 VecMap {
864 keys: self.keys.clone(),
865 values: self.values.clone(),
866 }
867 }
868
869 #[inline]
870 fn clone_from(&mut self, source: &Self) {
871 self.keys.clone_from(&source.keys);
872 self.values.clone_from(&source.values);
873 }
874}
875
876impl<K, V> fmt::Debug for VecMap<K, V>
877where
878 K: fmt::Debug,
879 V: fmt::Debug,
880{
881 #[inline]
882 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
883 f.debug_map().entries(self.iter()).finish()
884 }
885}
886
887impl<K, V> Default for VecMap<K, V> {
888 #[inline]
889 fn default() -> Self {
890 Self::with_capacity(0)
891 }
892}
893
894impl<K, V> PartialEq<VecMap<K, V>> for VecMap<K, V>
895where
896 K: PartialEq,
897 V: PartialEq,
898{
899 #[inline]
900 fn eq(&self, other: &Self) -> bool {
901 if self.len() != other.len() {
902 return false;
903 }
904
905 self.keys.eq(&other.keys) && self.values.eq(&other.values)
906 }
907}
908
909impl<K, V> Eq for VecMap<K, V>
910where
911 K: Eq,
912 V: Eq,
913{
914}
915
916pub struct Keys<'a, K, V> {
917 iter: SliceIter<'a, K>,
918 _phantom: PhantomData<V>,
919}
920
921impl<'a, K, V> Clone for Keys<'a, K, V> {
922 #[inline]
923 fn clone(&self) -> Self {
924 Self {
925 iter: self.iter.clone(),
926 _phantom: PhantomData,
927 }
928 }
929}
930
931impl<'a, K, V> Iterator for Keys<'a, K, V> {
932 type Item = &'a K;
933
934 #[inline]
935 fn next(&mut self) -> Option<Self::Item> {
936 self.iter.next()
937 }
938
939 #[inline]
940 fn size_hint(&self) -> (usize, Option<usize>) {
941 self.iter.size_hint()
942 }
943}
944
945impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
946 #[inline]
947 fn next_back(&mut self) -> Option<Self::Item> {
948 self.iter.next_back()
949 }
950}
951
952impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {
953 #[inline]
954 fn len(&self) -> usize {
955 self.iter.len()
956 }
957}
958
959pub struct Values<'a, K, V> {
960 iter: SliceIter<'a, V>,
961 _phantom: PhantomData<K>,
962}
963
964impl<'a, K, V> Clone for Values<'a, K, V> {
965 #[inline]
966 fn clone(&self) -> Self {
967 Self {
968 iter: self.iter.clone(),
969 _phantom: PhantomData,
970 }
971 }
972}
973
974impl<K, V> fmt::Debug for Values<'_, K, V>
975where
976 K: fmt::Debug,
977 V: fmt::Debug,
978{
979 #[inline]
980 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
981 self.iter.fmt(f)
982 }
983}
984
985impl<'a, K, V> Iterator for Values<'a, K, V> {
986 type Item = &'a V;
987
988 #[inline]
989 fn next(&mut self) -> Option<Self::Item> {
990 self.iter.next()
991 }
992
993 #[inline]
994 fn size_hint(&self) -> (usize, Option<usize>) {
995 self.iter.size_hint()
996 }
997}
998
999impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1000 #[inline]
1001 fn next_back(&mut self) -> Option<Self::Item> {
1002 self.iter.next_back()
1003 }
1004}
1005
1006impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {
1007 #[inline]
1008 fn len(&self) -> usize {
1009 self.iter.len()
1010 }
1011}
1012
1013impl<'a, K, V> FusedIterator for Values<'a, K, V> {}
1014
1015pub struct ValuesMut<'a, K, V> {
1016 iter: SliceIterMut<'a, V>,
1017 _phantom: PhantomData<K>,
1018}
1019
1020impl<K, V> fmt::Debug for ValuesMut<'_, K, V>
1021where
1022 K: fmt::Debug,
1023 V: fmt::Debug,
1024{
1025 #[inline]
1026 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1027 self.iter.fmt(f)
1028 }
1029}
1030
1031impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1032 type Item = &'a mut V;
1033
1034 #[inline]
1035 fn next(&mut self) -> Option<Self::Item> {
1036 self.iter.next()
1037 }
1038
1039 #[inline]
1040 fn size_hint(&self) -> (usize, Option<usize>) {
1041 self.iter.size_hint()
1042 }
1043}
1044
1045impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
1046 #[inline]
1047 fn next_back(&mut self) -> Option<Self::Item> {
1048 self.iter.next_back()
1049 }
1050}
1051
1052impl<'a, K, V> ExactSizeIterator for ValuesMut<'a, K, V> {
1053 #[inline]
1054 fn len(&self) -> usize {
1055 self.iter.len()
1056 }
1057}
1058
1059impl<'a, K, V> FusedIterator for ValuesMut<'a, K, V> {}
1060
1061pub struct Iter<'a, K, V> {
1062 iter: Zip<SliceIter<'a, K>, SliceIter<'a, V>>,
1063}
1064
1065impl<K, V> fmt::Debug for Iter<'_, K, V>
1066where
1067 K: fmt::Debug,
1068 V: fmt::Debug,
1069{
1070 #[inline]
1071 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1072 self.iter.fmt(f)
1073 }
1074}
1075
1076impl<'a, K, V> Iterator for Iter<'a, K, V> {
1077 type Item = (&'a K, &'a V);
1078
1079 #[inline]
1080 fn next(&mut self) -> Option<Self::Item> {
1081 self.iter.next()
1082 }
1083
1084 #[inline]
1085 fn size_hint(&self) -> (usize, Option<usize>) {
1086 self.iter.size_hint()
1087 }
1088}
1089
1090impl<'a, K, V> DoubleEndedIterator for Iter<'a, K, V> {
1091 #[inline]
1092 fn next_back(&mut self) -> Option<Self::Item> {
1093 self.iter.next_back()
1094 }
1095}
1096
1097impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {
1098 #[inline]
1099 fn len(&self) -> usize {
1100 self.iter.len()
1101 }
1102}
1103
1104impl<'a, K, V> FusedIterator for Iter<'a, K, V> {}
1105
1106pub struct IterMut<'a, K, V> {
1107 iter: Zip<SliceIter<'a, K>, SliceIterMut<'a, V>>,
1108}
1109
1110impl<K, V> fmt::Debug for IterMut<'_, K, V>
1111where
1112 K: fmt::Debug,
1113 V: fmt::Debug,
1114{
1115 #[inline]
1116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1117 self.iter.fmt(f)
1118 }
1119}
1120
1121impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1122 type Item = (&'a K, &'a mut V);
1123
1124 #[inline]
1125 fn next(&mut self) -> Option<Self::Item> {
1126 self.iter.next()
1127 }
1128
1129 #[inline]
1130 fn size_hint(&self) -> (usize, Option<usize>) {
1131 self.iter.size_hint()
1132 }
1133}
1134
1135impl<'a, K, V> DoubleEndedIterator for IterMut<'a, K, V> {
1136 #[inline]
1137 fn next_back(&mut self) -> Option<Self::Item> {
1138 self.iter.next_back()
1139 }
1140}
1141
1142impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> {
1143 #[inline]
1144 fn len(&self) -> usize {
1145 self.iter.len()
1146 }
1147}
1148
1149impl<'a, K, V> FusedIterator for IterMut<'a, K, V> {}
1150
1151pub struct IntoIter<K, V> {
1152 iter: Zip<VecIntoIter<K>, VecIntoIter<V>>,
1153}
1154
1155impl<K, V> fmt::Debug for IntoIter<K, V>
1156where
1157 K: fmt::Debug,
1158 V: fmt::Debug,
1159{
1160 #[inline]
1161 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1162 self.iter.fmt(f)
1163 }
1164}
1165
1166impl<K, V> Iterator for IntoIter<K, V> {
1167 type Item = (K, V);
1168
1169 #[inline]
1170 fn next(&mut self) -> Option<Self::Item> {
1171 self.iter.next()
1172 }
1173
1174 #[inline]
1175 fn size_hint(&self) -> (usize, Option<usize>) {
1176 self.iter.size_hint()
1177 }
1178}
1179
1180impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
1181 #[inline]
1182 fn next_back(&mut self) -> Option<Self::Item> {
1183 self.iter.next_back()
1184 }
1185}
1186
1187impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1188 #[inline]
1189 fn len(&self) -> usize {
1190 self.iter.len()
1191 }
1192}
1193
1194impl<K, V> FusedIterator for IntoIter<K, V> {}
1195
1196pub struct Drain<'a, K, V> {
1197 iter: Zip<VecDrain<'a, K>, VecDrain<'a, V>>,
1198}
1199
1200impl<K, V> fmt::Debug for Drain<'_, K, V>
1201where
1202 K: fmt::Debug,
1203 V: fmt::Debug,
1204{
1205 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1206 self.iter.fmt(f)
1207 }
1208}
1209
1210impl<'a, K, V> Iterator for Drain<'a, K, V> {
1211 type Item = (K, V);
1212
1213 #[inline]
1214 fn next(&mut self) -> Option<Self::Item> {
1215 self.iter.next()
1216 }
1217
1218 #[inline]
1219 fn size_hint(&self) -> (usize, Option<usize>) {
1220 self.iter.size_hint()
1221 }
1222}
1223
1224impl<'a, K, V> DoubleEndedIterator for Drain<'a, K, V> {
1225 #[inline]
1226 fn next_back(&mut self) -> Option<Self::Item> {
1227 self.iter.next_back()
1228 }
1229}
1230
1231impl<'a, K, V> ExactSizeIterator for Drain<'a, K, V> {
1232 #[inline]
1233 fn len(&self) -> usize {
1234 self.iter.len()
1235 }
1236}
1237
1238impl<'a, K, V> FusedIterator for Drain<'a, K, V> {}
1239
1240pub enum Entry<'a, K, V> {
1241 Occupied(OccupiedEntry<'a, K, V>),
1242 Vacant(VacantEntry<'a, K, V>),
1243}
1244
1245impl<'a, K: 'a, V: 'a> Entry<'a, K, V> {
1246 #[inline]
1247 pub fn key(&self) -> &K {
1248 match self {
1249 Entry::Occupied(entry) => &entry.map.keys[entry.index],
1250 Entry::Vacant(entry) => entry.key(),
1251 }
1252 }
1253
1254 #[inline]
1255 pub fn and_modify<F>(self, f: F) -> Self
1256 where
1257 F: FnOnce(&mut V),
1258 {
1259 match self {
1260 Entry::Occupied(mut entry) => {
1261 f(entry.get_mut());
1262
1263 Entry::Occupied(entry)
1264 }
1265 Entry::Vacant(entry) => Entry::Vacant(entry),
1266 }
1267 }
1268}
1269
1270impl<'a, K: 'a, V: 'a> Entry<'a, K, V>
1271where
1272 K: Eq,
1273{
1274 #[inline]
1275 pub fn insert(self, value: V) -> OccupiedEntry<'a, K, V> {
1276 match self {
1277 Entry::Occupied(mut entry) => {
1278 entry.insert(value);
1279
1280 entry
1281 }
1282 Entry::Vacant(entry) => {
1283 entry.map.insert(entry.key, value);
1284
1285 OccupiedEntry {
1286 index: entry.map.values.len() - 1,
1287 map: entry.map,
1288 }
1289 }
1290 }
1291 }
1292
1293 #[inline]
1294 pub fn or_insert(self, default: V) -> &'a mut V {
1295 match self {
1296 Entry::Occupied(entry) => entry.into_mut(),
1297 Entry::Vacant(entry) => entry.insert(default),
1298 }
1299 }
1300}
1301
1302impl<'a, K: 'a, V: 'a> Entry<'a, K, V>
1303where
1304 K: Eq,
1305 V: Default,
1306{
1307 #[inline]
1308 pub fn or_default(self) -> &'a mut V {
1309 match self {
1310 Entry::Occupied(entry) => entry.into_mut(),
1311 Entry::Vacant(entry) => entry.insert(Default::default()),
1312 }
1313 }
1314}
1315
1316impl<K, V> fmt::Debug for Entry<'_, K, V>
1317where
1318 K: fmt::Debug,
1319 V: fmt::Debug,
1320{
1321 #[inline]
1322 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1323 match self {
1324 Entry::Occupied(ref e) => f.debug_tuple("Entry").field(e).finish(),
1325 Entry::Vacant(ref e) => f.debug_tuple("Entry").field(e).finish(),
1326 }
1327 }
1328}
1329
1330pub struct OccupiedEntry<'a, K, V> {
1331 index: usize,
1332 map: &'a mut VecMap<K, V>,
1333}
1334
1335impl<'a, K: 'a, V: 'a> OccupiedEntry<'a, K, V> {
1336 #[inline]
1337 pub fn key(&self) -> &K {
1338 &self.map.keys[self.index]
1339 }
1340
1341 #[inline]
1342 pub fn get(&self) -> &V {
1343 &self.map.values[self.index]
1344 }
1345
1346 #[inline]
1347 pub fn get_mut(&mut self) -> &mut V {
1348 &mut self.map.values[self.index]
1349 }
1350
1351 #[inline]
1352 pub fn into_mut(self) -> &'a mut V {
1353 &mut self.map.values[self.index]
1354 }
1355
1356 #[inline]
1357 pub fn insert(&mut self, mut value: V) -> V {
1358 core::mem::swap(&mut value, &mut self.map.values[self.index]);
1359
1360 value
1361 }
1362}
1363
1364impl<'a, K: 'a, V: 'a> OccupiedEntry<'a, K, V>
1365where
1366 K: PartialEq,
1367{
1368 #[inline]
1369 pub fn remove(self) -> V {
1370 self.map.keys.swap_remove(self.index);
1371
1372 self.map.values.swap_remove(self.index)
1373 }
1374
1375 #[inline]
1376 pub fn remove_entry(self) -> (K, V) {
1377 (
1378 self.map.keys.swap_remove(self.index),
1379 self.map.values.swap_remove(self.index),
1380 )
1381 }
1382}
1383
1384impl<K, V> fmt::Debug for OccupiedEntry<'_, K, V>
1385where
1386 K: fmt::Debug,
1387 V: fmt::Debug,
1388{
1389 #[inline]
1390 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1391 f.debug_struct("OccupiedEntry")
1392 .field("index", &self.index)
1393 .field("value", &self.map.values[self.index])
1394 .finish()
1395 }
1396}
1397
1398pub struct VacantEntry<'a, K, V> {
1399 key: K,
1400 map: &'a mut VecMap<K, V>,
1401}
1402
1403impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
1404 #[inline]
1405 pub fn key(&self) -> &K {
1406 &self.key
1407 }
1408
1409 #[inline]
1410 pub fn into_key(self) -> K {
1411 self.key
1412 }
1413}
1414
1415impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V>
1416where
1417 K: Eq,
1418{
1419 #[inline]
1420 pub fn insert(self, value: V) -> &'a mut V {
1421 self.map.insert(self.key, value);
1422
1423 let index = self.map.values.len() - 1;
1424
1425 self.map
1426 .values
1427 .get_mut(index)
1428 .expect("no entry found for key")
1429 }
1430}
1431
1432impl<K, V> fmt::Debug for VacantEntry<'_, K, V>
1433where
1434 K: fmt::Debug,
1435 V: fmt::Debug,
1436{
1437 #[inline]
1438 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1439 f.debug_struct("VacantEntry")
1440 .field("key", &self.key)
1441 .finish()
1442 }
1443}
1444
1445/// Extension trait that contains functions that allow for chaining of
1446/// [`VecMap`](./struct.VecMap.html) functions.
1447///
1448/// Before:
1449///
1450/// ```rust
1451/// use fenn::vec_map::VecMap;
1452///
1453/// let mut map = VecMap::new();
1454///
1455/// map.insert(37, "a");
1456/// map.insert(38, "b");
1457///
1458/// map.remove(&37);
1459///
1460/// assert_eq!(map.get(&37), None);
1461/// assert_eq!(map.get(&38), Some(&"b"));
1462/// ```
1463///
1464/// After:
1465///
1466/// ```rust
1467/// use fenn::vec_map::{VecMapExt, VecMap};
1468///
1469/// let map = VecMap::new()
1470/// .inserted(37, "a")
1471/// .inserted(38, "b")
1472/// .removed(&37);
1473///
1474/// assert_eq!(map.get(&37), None);
1475/// assert_eq!(map.get(&38), Some(&"b"));
1476/// ```
1477pub trait VecMapExt<K, V> {
1478 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
1479 /// for reuse.
1480 ///
1481 /// # Examples
1482 ///
1483 /// ```
1484 /// use fenn::vec_map::{VecMapExt, VecMap};
1485 ///
1486 /// let a = VecMap::new()
1487 /// .inserted(1, "a")
1488 /// .cleared();
1489 ///
1490 /// assert!(a.is_empty());
1491 /// ```
1492 fn cleared(self) -> Self;
1493
1494 /// Inserts a key-value pair into the map.
1495 ///
1496 /// If the map did have this key present, the value is updated. The key is
1497 /// not updated, though; this matters for types that can be `==` without
1498 /// being identical.
1499 ///
1500 /// # Warning
1501 ///
1502 /// Unlike the standard [`VecMap::insert`](./struct.VecMap.html#method.insert)
1503 /// that this wraps, this function ignores any returned values.
1504 ///
1505 /// # Examples
1506 ///
1507 /// ```
1508 /// use fenn::vec_map::{VecMapExt, VecMap};
1509 ///
1510 /// let map = VecMap::new()
1511 /// .inserted(37, "a");
1512 ///
1513 /// assert_eq!(map[&37], "a");
1514 /// assert_eq!(map.is_empty(), false);
1515 /// ```
1516 fn inserted(self, k: K, v: V) -> Self
1517 where
1518 K: Eq;
1519
1520 /// Removes a key from the map.
1521 ///
1522 /// The key may be any borrowed form of the map's key type, but
1523 /// [`Eq`] on the borrowed form *must* match those for
1524 /// the key type.
1525 ///
1526 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
1527 fn removed<Q>(self, k: &Q) -> Self
1528 where
1529 K: Eq + Borrow<Q>,
1530 Q: Eq + PartialEq<K>;
1531
1532 /// Retains only the elements specified by the predicate.
1533 ///
1534 /// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)`
1535 /// returns `false`.
1536 ///
1537 /// # Examples
1538 ///
1539 /// ```
1540 /// use fenn::vec_map::{VecMapExt, VecMap};
1541 ///
1542 /// let map = (0..8).map(|x|(x, x * 10)).collect::<VecMap<i32, i32>>()
1543 /// .retained(|&k, _| k % 2 == 0);
1544 ///
1545 /// assert_eq!(map.len(), 4);
1546 /// ```
1547 fn retained<F>(self, f: F) -> Self
1548 where
1549 K: Eq,
1550 F: FnMut(&K, &mut V) -> bool;
1551
1552 /// Shrinks the capacity of the map as much as possible. It will drop
1553 /// down as much as possible while maintaining the internal rules
1554 /// and possibly leaving some space in accordance with the resize policy.
1555 ///
1556 /// # Examples
1557 ///
1558 /// ```
1559 /// use fenn::vec_map::{VecMapExt, VecMap};
1560 ///
1561 /// let map: VecMap<i32, i32> = VecMap::with_capacity(100)
1562 /// .inserted(1, 2)
1563 /// .inserted(3, 4)
1564 /// .shrinked_to_fit();
1565 ///
1566 /// assert!(map.capacity() >= 2);
1567 /// ```
1568 fn shrinked_to_fit(self) -> Self
1569 where
1570 K: Eq;
1571}
1572
1573impl<K, V> VecMapExt<K, V> for VecMap<K, V> {
1574 fn cleared(mut self) -> Self {
1575 self.clear();
1576
1577 self
1578 }
1579
1580 fn inserted(mut self, k: K, v: V) -> Self
1581 where
1582 K: Eq,
1583 {
1584 let _ = self.insert(k, v);
1585
1586 self
1587 }
1588
1589 fn removed<Q>(mut self, k: &Q) -> Self
1590 where
1591 K: Eq + Borrow<Q>,
1592 Q: Eq + PartialEq<K>,
1593 {
1594 let _ = self.remove(k);
1595
1596 self
1597 }
1598
1599 fn retained<F>(mut self, f: F) -> Self
1600 where
1601 K: Eq,
1602 F: FnMut(&K, &mut V) -> bool,
1603 {
1604 self.retain(f);
1605
1606 self
1607 }
1608
1609 fn shrinked_to_fit(mut self) -> Self
1610 where
1611 K: Eq,
1612 {
1613 self.shrink_to_fit();
1614
1615 self
1616 }
1617}