abi_stable/std_types/map.rs
1//! Contains the ffi-safe equivalent of `std::collections::HashMap`, and related items.
2#![allow(clippy::missing_const_for_fn)]
3
4use std::{
5 borrow::Borrow,
6 cmp::{Eq, PartialEq},
7 collections::{hash_map::RandomState, HashMap},
8 fmt::{self, Debug},
9 hash::{BuildHasher, Hash, Hasher},
10 iter::FromIterator,
11 marker::PhantomData,
12 mem,
13 ops::{Index, IndexMut},
14 ptr::NonNull,
15};
16
17#[allow(unused_imports)]
18use core_extensions::SelfOps;
19
20use crate::{
21 erased_types::trait_objects::HasherObject,
22 marker_type::{
23 ErasedObject, ErasedPrefix, NonOwningPhantom, NotCopyNotClone, UnsafeIgnoredType,
24 },
25 pointer_trait::{AsMutPtr, AsPtr},
26 prefix_type::{PrefixRef, WithMetadata},
27 sabi_types::{RMut, RRef},
28 std_types::*,
29 traits::{ErasedType, IntoReprRust},
30 DynTrait, StableAbi,
31};
32
33mod entry;
34mod extern_fns;
35mod iterator_stuff;
36mod map_key;
37mod map_query;
38
39#[cfg(all(test, not(feature = "only_new_tests")))]
40mod test;
41
42use self::{entry::BoxedREntry, map_key::MapKey, map_query::MapQuery};
43
44pub use self::{
45 entry::{REntry, ROccupiedEntry, RVacantEntry},
46 iterator_stuff::{IntoIter, MutIterInterface, RefIterInterface, ValIterInterface},
47};
48
49/// An ffi-safe hashmap, which wraps `std::collections::HashMap<K, V, S>`,
50/// only requiring the `K: Eq + Hash` bounds when constructing it.
51///
52/// Most of the API in `HashMap` is implemented here, including the Entry API.
53///
54///
55/// # Example
56///
57/// This example demonstrates how one can use the RHashMap as a dictionary.
58///
59/// ```
60/// use abi_stable::std_types::{RHashMap, RSome, RString, Tuple2};
61///
62/// let mut map = RHashMap::new();
63///
64/// map.insert(
65/// "dictionary",
66/// "A book/document containing definitions of words",
67/// );
68/// map.insert("bibliophile", "Someone who loves books.");
69/// map.insert("pictograph", "A picture representating of a word.");
70///
71/// assert_eq!(
72/// map["dictionary"],
73/// "A book/document containing definitions of words",
74/// );
75///
76/// assert_eq!(map.remove("bibliophile"), RSome("Someone who loves books."),);
77///
78/// assert_eq!(
79/// map.get("pictograph"),
80/// Some(&"A picture representating of a word."),
81/// );
82///
83/// for Tuple2(k, v) in map {
84/// assert!(k == "dictionary" || k == "pictograph");
85///
86/// assert!(
87/// v == "A book/document containing definitions of words" ||
88/// v == "A picture representating of a word.",
89/// "{} => {}",
90/// k,
91/// v,
92/// );
93/// }
94///
95///
96/// ```
97///
98#[derive(StableAbi)]
99#[repr(C)]
100#[sabi(
101 // The hasher doesn't matter
102 unsafe_unconstrained(S),
103)]
104pub struct RHashMap<K, V, S = RandomState> {
105 map: RBox<ErasedMap<K, V, S>>,
106 #[sabi(unsafe_change_type = VTable_Ref<K, V, S>)]
107 vtable: PrefixRef<ErasedPrefix>,
108}
109
110///////////////////////////////////////////////////////////////////////////////
111
112struct BoxedHashMap<'a, K, V, S> {
113 map: HashMap<MapKey<K>, V, S>,
114 entry: Option<BoxedREntry<'a, K, V>>,
115}
116
117/// An RHashMap iterator,
118/// implementing `Iterator<Item= Tuple2< &K, &V > > + !Send + !Sync + Clone`
119pub type Iter<'a, K, V> = DynTrait<'a, RBox<()>, RefIterInterface<K, V>>;
120
121/// An RHashMap iterator,
122/// implementing `Iterator<Item= Tuple2< &K, &mut V > > + !Send + !Sync`
123pub type IterMut<'a, K, V> = DynTrait<'a, RBox<()>, MutIterInterface<K, V>>;
124
125/// An RHashMap iterator,
126/// implementing `Iterator<Item= Tuple2< K, V > > + !Send + !Sync`
127pub type Drain<'a, K, V> = DynTrait<'a, RBox<()>, ValIterInterface<K, V>>;
128
129/// Used as the erased type of the RHashMap type.
130#[repr(C)]
131#[derive(StableAbi)]
132#[sabi(
133 // The hasher doesn't matter
134 unsafe_unconstrained(S),
135)]
136struct ErasedMap<K, V, S>(PhantomData<(K, V)>, UnsafeIgnoredType<S>);
137
138impl<'a, K: 'a, V: 'a, S: 'a> ErasedType<'a> for ErasedMap<K, V, S> {
139 type Unerased = BoxedHashMap<'a, K, V, S>;
140}
141
142///////////////////////////////////////////////////////////////////////////////
143
144impl<K, V> RHashMap<K, V, RandomState> {
145 /// Constructs an empty RHashMap.
146 ///
147 /// # Example
148 ///
149 /// ```
150 /// use abi_stable::std_types::{RHashMap, RString};
151 ///
152 /// let mut map = RHashMap::<RString, u32>::new();
153 /// assert!(map.is_empty());
154 /// map.insert("Hello".into(), 10);
155 /// assert_eq!(map.is_empty(), false);
156 ///
157 /// ```
158 #[inline]
159 pub fn new() -> RHashMap<K, V>
160 where
161 Self: Default,
162 {
163 Self::default()
164 }
165
166 /// Constructs an empty RHashMap with at least the passed capacity.
167 ///
168 /// # Example
169 ///
170 /// ```
171 /// use abi_stable::std_types::{RHashMap, RString};
172 ///
173 /// let mut map = RHashMap::<RString, u32>::with_capacity(10);
174 /// assert!(map.capacity() >= 10);
175 ///
176 /// ```
177 #[inline]
178 pub fn with_capacity(capacity: usize) -> RHashMap<K, V>
179 where
180 Self: Default,
181 {
182 let mut this = Self::default();
183 this.reserve(capacity);
184 this
185 }
186}
187
188impl<K, V, S> RHashMap<K, V, S> {
189 /// Constructs an empty RHashMap with the passed `hash_builder` to hash the keys.
190 ///
191 /// # Example
192 ///
193 /// ```
194 /// use abi_stable::std_types::{RHashMap, RString};
195 /// use std::collections::hash_map::RandomState;
196 ///
197 /// let s = RandomState::new();
198 /// let mut map = RHashMap::<RString, u32, _>::with_hasher(s);
199 /// assert!(map.is_empty());
200 /// map.insert("Hello".into(), 10);
201 /// assert_eq!(map.is_empty(), false);
202 ///
203 /// ```
204 #[inline]
205 pub fn with_hasher(hash_builder: S) -> RHashMap<K, V, S>
206 where
207 K: Eq + Hash,
208 S: BuildHasher + Default,
209 {
210 Self::with_capacity_and_hasher(0, hash_builder)
211 }
212 /// Constructs an empty RHashMap with at least the passed capacity,
213 /// and the passed `hash_builder` to hash the keys.
214 ///
215 /// # Example
216 ///
217 /// ```
218 /// use abi_stable::std_types::{RHashMap, RString};
219 /// use std::collections::hash_map::RandomState;
220 ///
221 /// let s = RandomState::new();
222 /// let mut map = RHashMap::<RString, u32, _>::with_capacity_and_hasher(10, s);
223 /// assert!(map.capacity() >= 10);
224 ///
225 /// ```
226 pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> RHashMap<K, V, S>
227 where
228 K: Eq + Hash,
229 S: BuildHasher + Default,
230 {
231 let mut map = VTable::<K, V, S>::erased_map(hash_builder);
232 unsafe {
233 ErasedMap::reserve(map.as_rmut(), capacity);
234
235 RHashMap {
236 map,
237 vtable: VTable::<K, V, S>::VTABLE_REF.0.cast(),
238 }
239 }
240 }
241}
242
243impl<K, V, S> RHashMap<K, V, S> {
244 fn vtable(&self) -> VTable_Ref<K, V, S> {
245 unsafe { VTable_Ref::<K, V, S>(self.vtable.cast()) }
246 }
247}
248
249impl<K, V, S> RHashMap<K, V, S> {
250 /// Returns whether the map associates a value with the key.
251 ///
252 /// # Example
253 ///
254 /// ```
255 /// use abi_stable::std_types::{RHashMap, RString};
256 ///
257 /// let mut map = RHashMap::<RString, u32>::new();
258 /// assert_eq!(map.contains_key("boo"), false);
259 /// map.insert("boo".into(), 0);
260 /// assert_eq!(map.contains_key("boo"), true);
261 ///
262 /// ```
263 pub fn contains_key<Q>(&self, query: &Q) -> bool
264 where
265 K: Borrow<Q>,
266 Q: Hash + Eq + ?Sized,
267 {
268 self.get(query).is_some()
269 }
270
271 /// Returns a reference to the value associated with the key.
272 ///
273 /// Returns a `None` if there is no entry for the key.
274 ///
275 /// # Example
276 ///
277 /// ```
278 /// use abi_stable::std_types::{RHashMap, RString};
279 ///
280 /// let mut map = RHashMap::<RString, u32>::new();
281 /// assert_eq!(map.get("boo"), None);
282 /// map.insert("boo".into(), 0);
283 /// assert_eq!(map.get("boo"), Some(&0));
284 ///
285 /// ```
286 pub fn get<Q>(&self, query: &Q) -> Option<&V>
287 where
288 K: Borrow<Q>,
289 Q: Hash + Eq + ?Sized,
290 {
291 let vtable = self.vtable();
292 unsafe { vtable.get_elem()(self.map.as_rref(), MapQuery::new(&query)) }
293 }
294
295 /// Returns a mutable reference to the value associated with the key.
296 ///
297 /// Returns a `None` if there is no entry for the key.
298 ///
299 /// # Example
300 ///
301 /// ```
302 /// use abi_stable::std_types::{RHashMap, RString};
303 ///
304 /// let mut map = RHashMap::<RString, u32>::new();
305 /// assert_eq!(map.get_mut("boo"), None);
306 /// map.insert("boo".into(), 0);
307 /// assert_eq!(map.get_mut("boo"), Some(&mut 0));
308 ///
309 /// ```
310 pub fn get_mut<Q>(&mut self, query: &Q) -> Option<&mut V>
311 where
312 K: Borrow<Q>,
313 Q: Hash + Eq + ?Sized,
314 {
315 let vtable = self.vtable();
316 unsafe { vtable.get_mut_elem()(self.map.as_rmut(), MapQuery::new(&query)) }
317 }
318
319 /// Removes the value associated with the key.
320 ///
321 /// # Example
322 ///
323 /// ```
324 /// use abi_stable::std_types::{RHashMap, RSome, RNone};
325 ///
326 /// let mut map = vec![(0, 1), (3, 4)].into_iter().collect::<RHashMap<u32, u32>>();
327 ///
328 /// assert_eq!(map.remove(&0), RSome(1));
329 /// assert_eq!(map.remove(&0), RNone);
330 ///
331 /// assert_eq!(map.remove(&3), RSome(4));
332 /// assert_eq!(map.remove(&3), RNone);
333 ///
334 /// ```
335 pub fn remove<Q>(&mut self, query: &Q) -> ROption<V>
336 where
337 K: Borrow<Q>,
338 Q: Hash + Eq + ?Sized,
339 {
340 self.remove_entry(query).map(|x| x.1)
341 }
342
343 /// Removes the entry for the key.
344 ///
345 /// # Example
346 ///
347 /// ```
348 /// use abi_stable::std_types::{RHashMap, RSome, RNone, Tuple2};
349 ///
350 /// let mut map = vec![(0, 1), (3, 4)].into_iter().collect::<RHashMap<u32, u32>>();
351 ///
352 /// assert_eq!(map.remove_entry(&0), RSome(Tuple2(0, 1)));
353 /// assert_eq!(map.remove_entry(&0), RNone);
354 ///
355 /// assert_eq!(map.remove_entry(&3), RSome(Tuple2(3, 4)));
356 /// assert_eq!(map.remove_entry(&3), RNone);
357 ///
358 /// ```
359 pub fn remove_entry<Q>(&mut self, query: &Q) -> ROption<Tuple2<K, V>>
360 where
361 K: Borrow<Q>,
362 Q: Hash + Eq + ?Sized,
363 {
364 let vtable = self.vtable();
365 unsafe { vtable.remove_entry()(self.map.as_rmut(), MapQuery::new(&query)) }
366 }
367}
368
369impl<K, V, S> RHashMap<K, V, S> {
370 /// Returns whether the map associates a value with the key.
371 ///
372 /// # Example
373 ///
374 /// ```
375 /// use abi_stable::std_types::RHashMap;
376 ///
377 /// let mut map = RHashMap::<u32, u32>::new();
378 /// assert_eq!(map.contains_key(&11), false);
379 /// map.insert(11, 0);
380 /// assert_eq!(map.contains_key(&11), true);
381 ///
382 /// ```
383 pub fn contains_key_p(&self, key: &K) -> bool {
384 self.get_p(key).is_some()
385 }
386
387 /// Returns a reference to the value associated with the key.
388 ///
389 /// Returns a `None` if there is no entry for the key.
390 ///
391 /// # Example
392 ///
393 /// ```
394 /// use abi_stable::std_types::RHashMap;
395 ///
396 /// let mut map = RHashMap::<u32, u32>::new();
397 /// assert_eq!(map.get(&12), None);
398 /// map.insert(12, 0);
399 /// assert_eq!(map.get(&12), Some(&0));
400 ///
401 /// ```
402 pub fn get_p(&self, key: &K) -> Option<&V> {
403 let vtable = self.vtable();
404 unsafe { vtable.get_elem_p()(self.map.as_rref(), key) }
405 }
406
407 /// Returns a mutable reference to the value associated with the key.
408 ///
409 /// Returns a `None` if there is no entry for the key.
410 ///
411 /// # Example
412 ///
413 /// ```
414 /// use abi_stable::std_types::RHashMap;
415 ///
416 /// let mut map = RHashMap::<u32, u32>::new();
417 /// assert_eq!(map.get_mut(&12), None);
418 /// map.insert(12, 0);
419 /// assert_eq!(map.get_mut(&12), Some(&mut 0));
420 ///
421 /// ```
422 pub fn get_mut_p(&mut self, key: &K) -> Option<&mut V> {
423 let vtable = self.vtable();
424 unsafe { vtable.get_mut_elem_p()(self.map.as_rmut(), key) }
425 }
426
427 /// Removes the value associated with the key.
428 ///
429 /// # Example
430 ///
431 /// ```
432 /// use abi_stable::std_types::{RHashMap, RSome, RNone};
433 ///
434 /// let mut map = vec![(0, 1), (3, 4)].into_iter().collect::<RHashMap<u32, u32>>();
435 ///
436 /// assert_eq!(map.remove_p(&0), RSome(1));
437 /// assert_eq!(map.remove_p(&0), RNone);
438 ///
439 /// assert_eq!(map.remove_p(&3), RSome(4));
440 /// assert_eq!(map.remove_p(&3), RNone);
441 ///
442 /// ```
443 pub fn remove_p(&mut self, key: &K) -> ROption<V> {
444 self.remove_entry_p(key).map(|x| x.1)
445 }
446
447 /// Removes the entry for the key.
448 ///
449 /// # Example
450 ///
451 /// ```
452 /// use abi_stable::std_types::{RHashMap, RSome, RNone, Tuple2};
453 ///
454 /// let mut map = vec![(0, 1), (3, 4)].into_iter().collect::<RHashMap<u32, u32>>();
455 ///
456 /// assert_eq!(map.remove_entry_p(&0), RSome(Tuple2(0, 1)));
457 /// assert_eq!(map.remove_entry_p(&0), RNone);
458 ///
459 /// assert_eq!(map.remove_entry_p(&3), RSome(Tuple2(3, 4)));
460 /// assert_eq!(map.remove_entry_p(&3), RNone);
461 ///
462 /// ```
463 pub fn remove_entry_p(&mut self, key: &K) -> ROption<Tuple2<K, V>> {
464 let vtable = self.vtable();
465 unsafe { vtable.remove_entry_p()(self.map.as_rmut(), key) }
466 }
467
468 /// Returns a reference to the value associated with the key.
469 ///
470 /// # Panics
471 ///
472 /// Panics if the key is not associated with a value.
473 ///
474 /// # Example
475 ///
476 /// ```
477 /// use abi_stable::std_types::RHashMap;
478 ///
479 /// let mut map = vec![(0, 1), (3, 4)].into_iter().collect::<RHashMap<u32, u32>>();
480 ///
481 /// assert_eq!(map.index_p(&0), &1);
482 /// assert_eq!(map.index_p(&3), &4);
483 ///
484 /// ```
485 ///
486 /// ```should_panic
487 /// use abi_stable::std_types::RHashMap;
488 ///
489 /// let mut map = RHashMap::<u32, u32>::new();
490 ///
491 /// assert_eq!(map.index_p(&0), &1);
492 ///
493 /// ```
494 pub fn index_p(&self, key: &K) -> &V {
495 self.get_p(key)
496 .expect("no entry in RHashMap<_, _> found for key")
497 }
498
499 /// Returns a mutable reference to the value associated with the key.
500 ///
501 /// # Panics
502 ///
503 /// Panics if the key is not associated with a value.
504 ///
505 /// # Example
506 ///
507 /// ```
508 /// use abi_stable::std_types::RHashMap;
509 ///
510 /// let mut map = vec![(0, 1), (3, 4)].into_iter().collect::<RHashMap<u32, u32>>();
511 ///
512 /// assert_eq!(map.index_mut_p(&0), &mut 1);
513 /// assert_eq!(map.index_mut_p(&3), &mut 4);
514 ///
515 /// ```
516 ///
517 /// ```should_panic
518 /// use abi_stable::std_types::RHashMap;
519 ///
520 /// let mut map = RHashMap::<u32, u32>::new();
521 ///
522 /// assert_eq!(map.index_mut_p(&0), &mut 1);
523 ///
524 /// ```
525 pub fn index_mut_p(&mut self, key: &K) -> &mut V {
526 self.get_mut_p(key)
527 .expect("no entry in RHashMap<_, _> found for key")
528 }
529
530 //////////////////////////////////
531
532 /// Inserts a value into the map, associating it with a key, returning the previous value.
533 ///
534 /// # Example
535 ///
536 /// ```
537 /// use abi_stable::std_types::RHashMap;
538 ///
539 /// let mut map = RHashMap::<u32, u32>::new();
540 ///
541 /// map.insert(0, 1);
542 /// map.insert(2, 3);
543 ///
544 /// assert_eq!(map[&0], 1);
545 /// assert_eq!(map[&2], 3);
546 ///
547 /// ```
548 pub fn insert(&mut self, key: K, value: V) -> ROption<V> {
549 let vtable = self.vtable();
550 unsafe { vtable.insert_elem()(self.map.as_rmut(), key, value) }
551 }
552
553 /// Reserves enough space to insert `reserved` extra elements without reallocating.
554 ///
555 /// # Example
556 ///
557 /// ```
558 /// use abi_stable::std_types::RHashMap;
559 ///
560 /// let mut map = RHashMap::<u32, u32>::new();
561 /// map.reserve(10);
562 ///
563 /// ```
564 pub fn reserve(&mut self, reserved: usize) {
565 let vtable = self.vtable();
566
567 unsafe {
568 vtable.reserve()(self.map.as_rmut(), reserved);
569 }
570 }
571
572 /// Removes all the entries in the map.
573 ///
574 /// # Example
575 ///
576 /// ```
577 /// use abi_stable::std_types::RHashMap;
578 ///
579 /// let mut map = vec![(0, 1), (3, 4)].into_iter().collect::<RHashMap<u32, u32>>();
580 ///
581 /// assert_eq!(map.contains_key(&0), true);
582 /// assert_eq!(map.contains_key(&3), true);
583 ///
584 /// map.clear();
585 ///
586 /// assert_eq!(map.contains_key(&0), false);
587 /// assert_eq!(map.contains_key(&3), false);
588 ///
589 /// ```
590 pub fn clear(&mut self) {
591 let vtable = self.vtable();
592 unsafe {
593 vtable.clear_map()(self.map.as_rmut());
594 }
595 }
596
597 /// Returns the amount of entries in the map.
598 ///
599 /// # Example
600 ///
601 /// ```
602 /// use abi_stable::std_types::RHashMap;
603 ///
604 /// let mut map = RHashMap::<u32, u32>::new();
605 ///
606 /// assert_eq!(map.len(), 0);
607 /// map.insert(0, 1);
608 /// assert_eq!(map.len(), 1);
609 /// map.insert(2, 3);
610 /// assert_eq!(map.len(), 2);
611 ///
612 /// ```
613 pub fn len(&self) -> usize {
614 let vtable = self.vtable();
615 unsafe { vtable.len()(self.map.as_rref()) }
616 }
617
618 /// Returns the capacity of the map, the amount of elements it can store without reallocating.
619 ///
620 /// Note that this is a lower bound, since hash maps don't necessarily have an exact capacity.
621 ///
622 /// # Example
623 ///
624 /// ```
625 /// use abi_stable::std_types::RHashMap;
626 ///
627 /// let mut map = RHashMap::<u32, u32>::with_capacity(4);
628 ///
629 /// assert!(map.capacity() >= 4);
630 ///
631 /// ```
632 pub fn capacity(&self) -> usize {
633 let vtable = self.vtable();
634 unsafe { vtable.capacity()(self.map.as_rref()) }
635 }
636
637 /// Returns whether the map contains any entries.
638 ///
639 /// # Example
640 ///
641 /// ```
642 /// use abi_stable::std_types::RHashMap;
643 ///
644 /// let mut map = RHashMap::<u32, u32>::new();
645 ///
646 /// assert_eq!(map.is_empty(), true);
647 /// map.insert(0, 1);
648 /// assert_eq!(map.is_empty(), false);
649 ///
650 /// ```
651 pub fn is_empty(&self) -> bool {
652 self.len() == 0
653 }
654
655 /// Iterates over the entries in the map, with references to the values in the map.
656 ///
657 /// This returns a type that implements
658 /// `Iterator<Item= Tuple2< &K, &V > > + !Send + !Sync + Clone`
659 ///
660 /// # Example
661 ///
662 /// ```
663 /// use abi_stable::std_types::{RHashMap, Tuple2};
664 ///
665 /// let mut map = RHashMap::<u32, u32>::new();
666 ///
667 /// map.insert(0, 1);
668 /// map.insert(3, 4);
669 ///
670 /// let mut list = map.iter().collect::<Vec<_>>();
671 /// list.sort();
672 /// assert_eq!( list, vec![Tuple2(&0, &1), Tuple2(&3, &4)] );
673 ///
674 /// ```
675 pub fn iter(&self) -> Iter<'_, K, V> {
676 let vtable = self.vtable();
677
678 unsafe { vtable.iter()(self.map.as_rref()) }
679 }
680
681 /// Iterates over the entries in the map, with mutable references to the values in the map.
682 ///
683 /// This returns a type that implements
684 /// `Iterator<Item= Tuple2< &K, &mut V > > + !Send + !Sync`
685 ///
686 /// # Example
687 ///
688 /// ```
689 /// use abi_stable::std_types::{RHashMap, Tuple2};
690 ///
691 /// let mut map = RHashMap::<u32, u32>::new();
692 ///
693 /// map.insert(0, 1);
694 /// map.insert(3, 4);
695 ///
696 /// let mut list = map.iter_mut().collect::<Vec<_>>();
697 /// list.sort();
698 /// assert_eq!( list, vec![Tuple2(&0, &mut 1), Tuple2(&3, &mut 4)] );
699 ///
700 /// ```
701 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
702 let vtable = self.vtable();
703
704 unsafe { vtable.iter_mut()(self.map.as_rmut()) }
705 }
706
707 /// Clears the map, returning an iterator over all the entries that were removed.
708 ///
709 /// This returns a type that implements `Iterator<Item= Tuple2< K, V > > + !Send + !Sync`
710 ///
711 /// # Example
712 ///
713 /// ```
714 /// use abi_stable::std_types::{RHashMap, Tuple2};
715 ///
716 /// let mut map = RHashMap::<u32, u32>::new();
717 ///
718 /// map.insert(0, 1);
719 /// map.insert(3, 4);
720 ///
721 /// let mut list = map.drain().collect::<Vec<_>>();
722 /// list.sort();
723 /// assert_eq!( list, vec![Tuple2(0, 1), Tuple2(3, 4)] );
724 ///
725 /// assert!(map.is_empty());
726 ///
727 /// ```
728 pub fn drain(&mut self) -> Drain<'_, K, V> {
729 let vtable = self.vtable();
730
731 unsafe { vtable.drain()(self.map.as_rmut()) }
732 }
733
734 /// Gets a handle into the entry in the map for the key,
735 /// that allows operating directly on the entry.
736 ///
737 /// # Example
738 ///
739 /// ```
740 /// use abi_stable::std_types::RHashMap;
741 ///
742 /// let mut map = RHashMap::<u32, u32>::new();
743 ///
744 /// // Inserting an entry that wasn't there before.
745 /// {
746 /// let mut entry = map.entry(0);
747 /// assert_eq!(entry.get(), None);
748 /// assert_eq!(entry.or_insert(3), &mut 3);
749 /// assert_eq!(map.get(&0), Some(&3));
750 /// }
751 ///
752 ///
753 /// ```
754 ///
755 pub fn entry(&mut self, key: K) -> REntry<'_, K, V> {
756 let vtable = self.vtable();
757
758 unsafe { vtable.entry()(self.map.as_rmut(), key) }
759 }
760
761 /// An iterator visiting all keys in arbitrary order.
762 /// The iterator element type is `&'a K`.
763 ///
764 /// # Examples
765 ///
766 /// ```
767 /// use abi_stable::std_types::RHashMap;
768 ///
769 /// let mut map = RHashMap::new();
770 /// map.insert("a", 1);
771 /// map.insert("b", 2);
772 /// map.insert("c", 3);
773 ///
774 /// for key in map.keys() {
775 /// println!("{}", key);
776 /// }
777 /// ```
778 pub fn keys(&self) -> Keys<'_, K, V> {
779 Keys { inner: self.iter() }
780 }
781
782 /// An iterator visiting all values in arbitrary order.
783 /// The iterator element type is `&'a V`.
784 ///
785 /// # Examples
786 ///
787 /// ```
788 /// use abi_stable::std_types::RHashMap;
789 ///
790 /// let mut map = RHashMap::new();
791 /// map.insert("a", 1);
792 /// map.insert("b", 2);
793 /// map.insert("c", 3);
794 ///
795 /// for val in map.values() {
796 /// println!("{}", val);
797 /// }
798 /// ```
799 pub fn values(&self) -> Values<'_, K, V> {
800 Values { inner: self.iter() }
801 }
802}
803
804/// An iterator over the keys of a `RHashMap`.
805///
806/// This `struct` is created by the [`keys`] method on [`RHashMap`]. See its
807/// documentation for more.
808///
809/// [`keys`]: RHashMap::keys
810///
811/// # Example
812///
813/// ```
814/// use abi_stable::std_types::RHashMap;
815///
816/// let mut map = RHashMap::new();
817/// map.insert("a", 1);
818/// let iter_keys = map.keys();
819/// ```
820#[repr(C)]
821#[derive(StableAbi)]
822pub struct Keys<'a, K: 'a, V: 'a> {
823 inner: Iter<'a, K, V>,
824}
825
826// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
827impl<K, V> Clone for Keys<'_, K, V> {
828 #[inline]
829 fn clone(&self) -> Self {
830 Keys {
831 inner: self.inner.clone(),
832 }
833 }
834}
835
836impl<K: Debug, V> fmt::Debug for Keys<'_, K, V> {
837 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
838 f.debug_list().entries(self.clone()).finish()
839 }
840}
841
842impl<'a, K, V> Iterator for Keys<'a, K, V> {
843 type Item = &'a K;
844
845 #[inline]
846 fn next(&mut self) -> Option<&'a K> {
847 self.inner.next().map(|tuple| tuple.0)
848 }
849 #[inline]
850 fn size_hint(&self) -> (usize, Option<usize>) {
851 self.inner.size_hint()
852 }
853}
854
855/// An iterator over the values of a `HashMap`.
856///
857/// This `struct` is created by the [`values`] method on [`HashMap`]. See its
858/// documentation for more.
859///
860/// [`values`]: HashMap::values
861///
862/// # Example
863///
864/// ```
865/// use abi_stable::std_types::RHashMap;
866///
867/// let mut map = RHashMap::new();
868/// map.insert("a", 1);
869/// let iter_values = map.values();
870/// ```
871#[repr(C)]
872#[derive(StableAbi)]
873pub struct Values<'a, K: 'a, V: 'a> {
874 inner: Iter<'a, K, V>,
875}
876
877// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
878impl<K, V> Clone for Values<'_, K, V> {
879 #[inline]
880 fn clone(&self) -> Self {
881 Values {
882 inner: self.inner.clone(),
883 }
884 }
885}
886
887impl<K, V: Debug> fmt::Debug for Values<'_, K, V> {
888 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
889 f.debug_list().entries(self.clone()).finish()
890 }
891}
892
893impl<'a, K, V> Iterator for Values<'a, K, V> {
894 type Item = &'a V;
895
896 #[inline]
897 fn next(&mut self) -> Option<&'a V> {
898 self.inner.next().map(|tuple| tuple.1)
899 }
900 #[inline]
901 fn size_hint(&self) -> (usize, Option<usize>) {
902 self.inner.size_hint()
903 }
904}
905
906/// This returns an `Iterator<Item= Tuple2< K, V > >+!Send+!Sync`
907impl<K, V, S> IntoIterator for RHashMap<K, V, S> {
908 type Item = Tuple2<K, V>;
909 type IntoIter = IntoIter<K, V>;
910
911 fn into_iter(self) -> IntoIter<K, V> {
912 let vtable = self.vtable();
913
914 unsafe { vtable.iter_val()(self.map) }
915 }
916}
917
918/// This returns an `Iterator<Item= Tuple2< &K, &V > > + !Send + !Sync + Clone`
919impl<'a, K, V, S> IntoIterator for &'a RHashMap<K, V, S> {
920 type Item = Tuple2<&'a K, &'a V>;
921 type IntoIter = Iter<'a, K, V>;
922
923 fn into_iter(self) -> Self::IntoIter {
924 self.iter()
925 }
926}
927
928/// This returns a type that implements
929/// `Iterator<Item= Tuple2< &K, &mut V > > + !Send + !Sync`
930impl<'a, K, V, S> IntoIterator for &'a mut RHashMap<K, V, S> {
931 type Item = Tuple2<&'a K, &'a mut V>;
932 type IntoIter = IterMut<'a, K, V>;
933
934 fn into_iter(self) -> Self::IntoIter {
935 self.iter_mut()
936 }
937}
938
939impl<K, V, S> From<HashMap<K, V, S>> for RHashMap<K, V, S>
940where
941 Self: Default,
942{
943 fn from(map: HashMap<K, V, S>) -> Self {
944 map.into_iter().collect()
945 }
946}
947
948impl<K, V, S> From<RHashMap<K, V, S>> for HashMap<K, V, S>
949where
950 K: Eq + Hash,
951 S: BuildHasher + Default,
952{
953 fn from(this: RHashMap<K, V, S>) -> HashMap<K, V, S> {
954 this.into_iter().map(|x| x.into_tuple()).collect()
955 }
956}
957
958impl<K, V, S> FromIterator<(K, V)> for RHashMap<K, V, S>
959where
960 Self: Default,
961{
962 fn from_iter<I>(iter: I) -> Self
963 where
964 I: IntoIterator<Item = (K, V)>,
965 {
966 let mut map = Self::default();
967 map.extend(iter);
968 map
969 }
970}
971
972impl<K, V, S> FromIterator<Tuple2<K, V>> for RHashMap<K, V, S>
973where
974 Self: Default,
975{
976 fn from_iter<I>(iter: I) -> Self
977 where
978 I: IntoIterator<Item = Tuple2<K, V>>,
979 {
980 let mut map = Self::default();
981 map.extend(iter);
982 map
983 }
984}
985
986impl<K, V, S> Extend<(K, V)> for RHashMap<K, V, S> {
987 fn extend<I>(&mut self, iter: I)
988 where
989 I: IntoIterator<Item = (K, V)>,
990 {
991 let iter = iter.into_iter();
992 self.reserve(iter.size_hint().0);
993 for (k, v) in iter {
994 self.insert(k, v);
995 }
996 }
997}
998
999impl<K, V, S> Extend<Tuple2<K, V>> for RHashMap<K, V, S> {
1000 #[inline]
1001 fn extend<I>(&mut self, iter: I)
1002 where
1003 I: IntoIterator<Item = Tuple2<K, V>>,
1004 {
1005 self.extend(iter.into_iter().map(Tuple2::into_rust));
1006 }
1007}
1008
1009impl<K, V, S> Default for RHashMap<K, V, S>
1010where
1011 K: Eq + Hash,
1012 S: BuildHasher + Default,
1013{
1014 fn default() -> Self {
1015 Self::with_hasher(S::default())
1016 }
1017}
1018
1019impl<K, V, S> Clone for RHashMap<K, V, S>
1020where
1021 K: Clone,
1022 V: Clone,
1023 Self: Default,
1024{
1025 fn clone(&self) -> Self {
1026 self.iter()
1027 .map(|Tuple2(k, v)| (k.clone(), v.clone()))
1028 .collect()
1029 }
1030}
1031
1032impl<K, V, S> Debug for RHashMap<K, V, S>
1033where
1034 K: Debug,
1035 V: Debug,
1036{
1037 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1038 f.debug_map()
1039 .entries(self.iter().map(Tuple2::into_rust))
1040 .finish()
1041 }
1042}
1043
1044impl<K, V, S> Eq for RHashMap<K, V, S>
1045where
1046 K: Eq,
1047 V: Eq,
1048{
1049}
1050
1051impl<K, V, S> PartialEq for RHashMap<K, V, S>
1052where
1053 K: PartialEq,
1054 V: PartialEq,
1055{
1056 fn eq(&self, other: &Self) -> bool {
1057 if self.len() != other.len() {
1058 return false;
1059 }
1060
1061 self.iter()
1062 .all(|Tuple2(k, vl)| other.get_p(k).map_or(false, |vr| *vr == *vl))
1063 }
1064}
1065
1066unsafe impl<K, V, S> Send for RHashMap<K, V, S> where HashMap<K, V, S>: Send {}
1067
1068unsafe impl<K, V, S> Sync for RHashMap<K, V, S> where HashMap<K, V, S>: Sync {}
1069
1070impl<K, Q, V, S> Index<&Q> for RHashMap<K, V, S>
1071where
1072 K: Borrow<Q>,
1073 Q: Eq + Hash + ?Sized,
1074{
1075 type Output = V;
1076
1077 fn index(&self, query: &Q) -> &V {
1078 self.get(query)
1079 .expect("no entry in RHashMap<_, _> found for key")
1080 }
1081}
1082
1083impl<K, Q, V, S> IndexMut<&Q> for RHashMap<K, V, S>
1084where
1085 K: Borrow<Q>,
1086 Q: Eq + Hash + ?Sized,
1087{
1088 fn index_mut(&mut self, query: &Q) -> &mut V {
1089 self.get_mut(query)
1090 .expect("no entry in RHashMap<_, _> found for key")
1091 }
1092}
1093
1094mod serde {
1095 use super::*;
1096
1097 use ::serde::{
1098 de::{MapAccess, Visitor},
1099 ser::SerializeMap,
1100 Deserialize, Deserializer, Serialize, Serializer,
1101 };
1102
1103 struct RHashMapVisitor<K, V, S> {
1104 _marker: NonOwningPhantom<RHashMap<K, V, S>>,
1105 }
1106
1107 impl<K, V, S> RHashMapVisitor<K, V, S> {
1108 fn new() -> Self {
1109 RHashMapVisitor {
1110 _marker: NonOwningPhantom::NEW,
1111 }
1112 }
1113 }
1114
1115 impl<'de, K, V, S> Visitor<'de> for RHashMapVisitor<K, V, S>
1116 where
1117 K: Deserialize<'de>,
1118 V: Deserialize<'de>,
1119 RHashMap<K, V, S>: Default,
1120 {
1121 type Value = RHashMap<K, V, S>;
1122
1123 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1124 formatter.write_str("an RHashMap")
1125 }
1126
1127 fn visit_map<M>(self, mut map_access: M) -> Result<Self::Value, M::Error>
1128 where
1129 M: MapAccess<'de>,
1130 {
1131 let capacity = map_access.size_hint().unwrap_or(0);
1132 let mut map = RHashMap::default();
1133 map.reserve(capacity);
1134
1135 while let Some((k, v)) = map_access.next_entry()? {
1136 map.insert(k, v);
1137 }
1138
1139 Ok(map)
1140 }
1141 }
1142
1143 impl<'de, K, V, S> Deserialize<'de> for RHashMap<K, V, S>
1144 where
1145 K: Deserialize<'de>,
1146 V: Deserialize<'de>,
1147 Self: Default,
1148 {
1149 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1150 where
1151 D: Deserializer<'de>,
1152 {
1153 deserializer.deserialize_map(RHashMapVisitor::new())
1154 }
1155 }
1156
1157 impl<K, V, S> Serialize for RHashMap<K, V, S>
1158 where
1159 K: Serialize,
1160 V: Serialize,
1161 {
1162 fn serialize<Z>(&self, serializer: Z) -> Result<Z::Ok, Z::Error>
1163 where
1164 Z: Serializer,
1165 {
1166 let mut map = serializer.serialize_map(Some(self.len()))?;
1167 for Tuple2(k, v) in self.iter() {
1168 map.serialize_entry(k, v)?;
1169 }
1170 map.end()
1171 }
1172 }
1173}
1174
1175///////////////////////////////////////////////////////////////////////////////
1176
1177#[derive(StableAbi)]
1178#[repr(C)]
1179#[sabi(
1180 kind(Prefix),
1181 missing_field(panic),
1182 // The hasher doesn't matter
1183 unsafe_unconstrained(S),
1184 //debug_print,
1185)]
1186struct VTable<K, V, S> {
1187 ///
1188 insert_elem: unsafe extern "C" fn(RMut<'_, ErasedMap<K, V, S>>, K, V) -> ROption<V>,
1189
1190 get_elem: for<'a> unsafe extern "C" fn(
1191 RRef<'a, ErasedMap<K, V, S>>,
1192 MapQuery<'_, K>,
1193 ) -> Option<&'a V>,
1194 get_mut_elem: for<'a> unsafe extern "C" fn(
1195 RMut<'a, ErasedMap<K, V, S>>,
1196 MapQuery<'_, K>,
1197 ) -> Option<&'a mut V>,
1198 remove_entry: unsafe extern "C" fn(
1199 RMut<'_, ErasedMap<K, V, S>>,
1200 MapQuery<'_, K>,
1201 ) -> ROption<Tuple2<K, V>>,
1202
1203 get_elem_p: for<'a> unsafe extern "C" fn(RRef<'a, ErasedMap<K, V, S>>, &K) -> Option<&'a V>,
1204 get_mut_elem_p:
1205 for<'a> unsafe extern "C" fn(RMut<'a, ErasedMap<K, V, S>>, &K) -> Option<&'a mut V>,
1206 remove_entry_p: unsafe extern "C" fn(RMut<'_, ErasedMap<K, V, S>>, &K) -> ROption<Tuple2<K, V>>,
1207
1208 reserve: unsafe extern "C" fn(RMut<'_, ErasedMap<K, V, S>>, usize),
1209 clear_map: unsafe extern "C" fn(RMut<'_, ErasedMap<K, V, S>>),
1210 len: unsafe extern "C" fn(RRef<'_, ErasedMap<K, V, S>>) -> usize,
1211 capacity: unsafe extern "C" fn(RRef<'_, ErasedMap<K, V, S>>) -> usize,
1212 iter: unsafe extern "C" fn(RRef<'_, ErasedMap<K, V, S>>) -> Iter<'_, K, V>,
1213 iter_mut: unsafe extern "C" fn(RMut<'_, ErasedMap<K, V, S>>) -> IterMut<'_, K, V>,
1214 drain: unsafe extern "C" fn(RMut<'_, ErasedMap<K, V, S>>) -> Drain<'_, K, V>,
1215 iter_val: unsafe extern "C" fn(RBox<ErasedMap<K, V, S>>) -> IntoIter<K, V>,
1216 #[sabi(last_prefix_field)]
1217 entry: unsafe extern "C" fn(RMut<'_, ErasedMap<K, V, S>>, K) -> REntry<'_, K, V>,
1218}
1219
1220impl<K, V, S> VTable<K, V, S>
1221where
1222 K: Eq + Hash,
1223 S: BuildHasher,
1224{
1225 const VTABLE_VAL: WithMetadata<VTable<K, V, S>> = WithMetadata::new(Self::VTABLE);
1226
1227 const VTABLE_REF: VTable_Ref<K, V, S> = unsafe { VTable_Ref(Self::VTABLE_VAL.as_prefix()) };
1228
1229 fn erased_map(hash_builder: S) -> RBox<ErasedMap<K, V, S>> {
1230 unsafe {
1231 let map = HashMap::<MapKey<K>, V, S>::with_hasher(hash_builder);
1232 let boxed = BoxedHashMap { map, entry: None };
1233 let boxed = RBox::new(boxed);
1234 mem::transmute::<RBox<_>, RBox<ErasedMap<K, V, S>>>(boxed)
1235 }
1236 }
1237
1238 const VTABLE: VTable<K, V, S> = VTable {
1239 insert_elem: ErasedMap::insert_elem,
1240
1241 get_elem: ErasedMap::get_elem,
1242 get_mut_elem: ErasedMap::get_mut_elem,
1243 remove_entry: ErasedMap::remove_entry,
1244
1245 get_elem_p: ErasedMap::get_elem_p,
1246 get_mut_elem_p: ErasedMap::get_mut_elem_p,
1247 remove_entry_p: ErasedMap::remove_entry_p,
1248
1249 reserve: ErasedMap::reserve,
1250 clear_map: ErasedMap::clear_map,
1251 len: ErasedMap::len,
1252 capacity: ErasedMap::capacity,
1253 iter: ErasedMap::iter,
1254 iter_mut: ErasedMap::iter_mut,
1255 drain: ErasedMap::drain,
1256 iter_val: ErasedMap::iter_val,
1257 entry: ErasedMap::entry,
1258 };
1259}
1260
1261///////////////////////////////////////////////////////////////////////////////