HashMap feature parity: impl Extend, notes on more
[anymap] / src / lib.rs
index d32af5f2aa4327826844727c183a09f47c247fb7..d4f227a293da168d6b4ffa0119ffc1c8aa7946f5 100644 (file)
@@ -1,17 +1,26 @@
-//! This crate provides the `AnyMap` type, a safe and convenient store for one value of each type.
+//! This crate provides a safe and convenient store for one value of each type.
+//!
+//! Your starting point is [`Map`]. It has an example.
 
-#![cfg_attr(feature = "nightly", feature(core, std_misc))]
-#![cfg_attr(test, feature(test))]
 #![warn(missing_docs, unused_results)]
 
-#[cfg(test)]
-extern crate test;
+#![cfg_attr(not(feature = "std"), no_std)]
+
+use core::any::{Any, TypeId};
+use core::marker::PhantomData;
+
+#[cfg(not(any(feature = "std", feature = "hashbrown")))]
+compile_error!("anymap: you must enable the 'std' feature or the 'hashbrown' feature");
 
-use std::any::TypeId;
-use std::marker::PhantomData;
+#[cfg(not(feature = "std"))]
+extern crate alloc;
 
-use raw::{RawAnyMap, Any};
-use unchecked_any::UncheckedAnyExt;
+#[cfg(not(feature = "std"))]
+use alloc::boxed::Box;
+
+use raw::RawMap;
+use any::{UncheckedAnyExt, IntoBox};
+pub use any::CloneAny;
 
 macro_rules! impl_common_methods {
     (
@@ -19,10 +28,10 @@ macro_rules! impl_common_methods {
         new() => $new:expr;
         with_capacity($with_capacity_arg:ident) => $with_capacity:expr;
     ) => {
-        impl $t {
+        impl<A: ?Sized + UncheckedAnyExt> $t<A> {
             /// Create an empty collection.
             #[inline]
-            pub fn new() -> $t {
+            pub fn new() -> $t<A> {
                 $t {
                     $field: $new,
                 }
@@ -30,7 +39,7 @@ macro_rules! impl_common_methods {
 
             /// Creates an empty collection with the given initial capacity.
             #[inline]
-            pub fn with_capacity($with_capacity_arg: usize) -> $t {
+            pub fn with_capacity($with_capacity_arg: usize) -> $t<A> {
                 $t {
                     $field: $with_capacity,
                 }
@@ -62,6 +71,10 @@ macro_rules! impl_common_methods {
                 self.$field.shrink_to_fit()
             }
 
+            // Additional stable methods (as of 1.60.0-nightly) that could be added:
+            // try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>    (1.57.0)
+            // shrink_to(&mut self, min_capacity: usize)                                   (1.56.0)
+
             /// Returns the number of items in the collection.
             #[inline]
             pub fn len(&self) -> usize {
@@ -80,18 +93,46 @@ macro_rules! impl_common_methods {
                 self.$field.clear()
             }
         }
+
+        impl<A: ?Sized + UncheckedAnyExt> Default for $t<A> {
+            #[inline]
+            fn default() -> $t<A> {
+                $t::new()
+            }
+        }
     }
 }
 
-mod unchecked_any;
+mod any;
 pub mod raw;
 
 /// A collection containing zero or one values for any given type and allowing convenient,
 /// type-safe access to those values.
 ///
+/// The type parameter `A` allows you to use a different value type; normally you will want it to
+/// be `core::any::Any` (also known as `std::any::Any`), but there are other choices:
+///
+/// - If you want the entire map to be cloneable, use `CloneAny` instead of `Any`; with that, you
+///   can only add types that implement `Clone` to the map.
+/// - You can add on `+ Send` or `+ Send + Sync` (e.g. `Map<dyn Any + Send>`) to add those auto
+///   traits.
+///
+/// Cumulatively, there are thus six forms of map:
+///
+/// - <code>[Map]&lt;dyn [core::any::Any]&gt;</code>, also spelled [`AnyMap`] for convenience.
+/// - <code>[Map]&lt;dyn [core::any::Any] + Send&gt;</code>
+/// - <code>[Map]&lt;dyn [core::any::Any] + Send + Sync&gt;</code>
+/// - <code>[Map]&lt;dyn [CloneAny]&gt;</code>
+/// - <code>[Map]&lt;dyn [CloneAny] + Send&gt;</code>
+/// - <code>[Map]&lt;dyn [CloneAny] + Send + Sync&gt;</code>
+///
+/// ## Example
+///
+/// (Here using the [`AnyMap`] convenience alias; the first line could use
+/// <code>[anymap::Map][Map]::&lt;[core::any::Any]&gt;::new()</code> instead if desired.)
+///
 /// ```rust
-/// # use anymap::AnyMap;
-/// let mut data = AnyMap::new();
+/// let mut data = anymap::AnyMap::new();
 /// assert_eq!(data.get(), None::<&i32>);
 /// data.insert(42i32);
 /// assert_eq!(data.get(), Some(&42i32));
@@ -112,27 +153,45 @@ pub mod raw;
 ///
 /// Values containing non-static references are not permitted.
 #[derive(Debug)]
-#[cfg_attr(feature = "clone", derive(Clone))]
-pub struct AnyMap {
-    raw: RawAnyMap,
+pub struct Map<A: ?Sized + UncheckedAnyExt = dyn Any> {
+    raw: RawMap<A>,
 }
 
+// #[derive(Clone)] would want A to implement Clone, but in reality it’s only Box<A> that can.
+impl<A: ?Sized + UncheckedAnyExt> Clone for Map<A> where Box<A>: Clone {
+    #[inline]
+    fn clone(&self) -> Map<A> {
+        Map {
+            raw: self.raw.clone(),
+        }
+    }
+}
+
+/// The most common type of `Map`: just using `Any`; <code>[Map]&lt;dyn [Any]&gt;</code>.
+///
+/// Why is this a separate type alias rather than a default value for `Map<A>`? `Map::new()`
+/// doesn’t seem to be happy to infer that it should go with the default value.
+/// It’s a bit sad, really. Ah well, I guess this approach will do.
+pub type AnyMap = Map<dyn Any>;
+
 impl_common_methods! {
-    field: AnyMap.raw;
-    new() => RawAnyMap::new();
-    with_capacity(capacity) => RawAnyMap::with_capacity(capacity);
+    field: Map.raw;
+    new() => RawMap::new();
+    with_capacity(capacity) => RawMap::with_capacity(capacity);
 }
 
-impl AnyMap {
+impl<A: ?Sized + UncheckedAnyExt> Map<A> {
     /// Returns a reference to the value stored in the collection for the type `T`, if it exists.
-    pub fn get<T: Any>(&self) -> Option<&T> {
+    #[inline]
+    pub fn get<T: IntoBox<A>>(&self) -> Option<&T> {
         self.raw.get(&TypeId::of::<T>())
             .map(|any| unsafe { any.downcast_ref_unchecked::<T>() })
     }
 
     /// Returns a mutable reference to the value stored in the collection for the type `T`,
     /// if it exists.
-    pub fn get_mut<T: Any>(&mut self) -> Option<&mut T> {
+    #[inline]
+    pub fn get_mut<T: IntoBox<A>>(&mut self) -> Option<&mut T> {
         self.raw.get_mut(&TypeId::of::<T>())
             .map(|any| unsafe { any.downcast_mut_unchecked::<T>() })
     }
@@ -140,28 +199,33 @@ impl AnyMap {
     /// Sets the value stored in the collection for the type `T`.
     /// If the collection already had a value of type `T`, that value is returned.
     /// Otherwise, `None` is returned.
-    pub fn insert<T: Any>(&mut self, value: T) -> Option<T> {
+    #[inline]
+    pub fn insert<T: IntoBox<A>>(&mut self, value: T) -> Option<T> {
         unsafe {
-            self.raw.insert(TypeId::of::<T>(), Box::new(value))
+            self.raw.insert(TypeId::of::<T>(), value.into_box())
                 .map(|any| *any.downcast_unchecked::<T>())
         }
     }
 
+    // rustc 1.60.0-nightly has another method try_insert that would be nice to add when stable.
+
     /// Removes the `T` value from the collection,
     /// returning it if there was one or `None` if there was not.
-    pub fn remove<T: Any>(&mut self) -> Option<T> {
+    #[inline]
+    pub fn remove<T: IntoBox<A>>(&mut self) -> Option<T> {
         self.raw.remove(&TypeId::of::<T>())
             .map(|any| *unsafe { any.downcast_unchecked::<T>() })
     }
 
     /// Returns true if the collection contains a value of type `T`.
     #[inline]
-    pub fn contains<T: Any>(&self) -> bool {
+    pub fn contains<T: IntoBox<A>>(&self) -> bool {
         self.raw.contains_key(&TypeId::of::<T>())
     }
 
     /// Gets the entry for the given type in the collection for in-place manipulation
-    pub fn entry<T: Any>(&mut self) -> Entry<T> {
+    #[inline]
+    pub fn entry<T: IntoBox<A>>(&mut self) -> Entry<A, T> {
         match self.raw.entry(TypeId::of::<T>()) {
             raw::Entry::Occupied(e) => Entry::Occupied(OccupiedEntry {
                 inner: e,
@@ -175,47 +239,60 @@ impl AnyMap {
     }
 }
 
-impl AsRef<RawAnyMap> for AnyMap {
-    fn as_ref(&self) -> &RawAnyMap {
+impl<A: ?Sized + UncheckedAnyExt> Extend<Box<A>> for Map<A> {
+    #[inline]
+    fn extend<T: IntoIterator<Item = Box<A>>>(&mut self, iter: T) {
+        for item in iter {
+            let _ = unsafe { self.raw.insert(item.type_id(), item) };
+        }
+    }
+}
+
+impl<A: ?Sized + UncheckedAnyExt> AsRef<RawMap<A>> for Map<A> {
+    #[inline]
+    fn as_ref(&self) -> &RawMap<A> {
         &self.raw
     }
 }
 
-impl AsMut<RawAnyMap> for AnyMap {
-    fn as_mut(&mut self) -> &mut RawAnyMap {
+impl<A: ?Sized + UncheckedAnyExt> AsMut<RawMap<A>> for Map<A> {
+    #[inline]
+    fn as_mut(&mut self) -> &mut RawMap<A> {
         &mut self.raw
     }
 }
 
-impl Into<RawAnyMap> for AnyMap {
-    fn into(self) -> RawAnyMap {
-        self.raw
+impl<A: ?Sized + UncheckedAnyExt> From<Map<A>> for RawMap<A> {
+    #[inline]
+    fn from(map: Map<A>) -> RawMap<A> {
+        map.raw
     }
 }
 
-/// A view into a single occupied location in an `AnyMap`.
-pub struct OccupiedEntry<'a, V: 'a> {
-    inner: raw::OccupiedEntry<'a>,
+/// A view into a single occupied location in an `Map`.
+pub struct OccupiedEntry<'a, A: ?Sized + UncheckedAnyExt, V: 'a> {
+    inner: raw::OccupiedEntry<'a, A>,
     type_: PhantomData<V>,
 }
 
-/// A view into a single empty location in an `AnyMap`.
-pub struct VacantEntry<'a, V: 'a> {
-    inner: raw::VacantEntry<'a>,
+/// A view into a single empty location in an `Map`.
+pub struct VacantEntry<'a, A: ?Sized + UncheckedAnyExt, V: 'a> {
+    inner: raw::VacantEntry<'a, A>,
     type_: PhantomData<V>,
 }
 
-/// A view into a single location in an `AnyMap`, which may be vacant or occupied.
-pub enum Entry<'a, V: 'a> {
+/// A view into a single location in an `Map`, which may be vacant or occupied.
+pub enum Entry<'a, A: ?Sized + UncheckedAnyExt, V: 'a> {
     /// An occupied Entry
-    Occupied(OccupiedEntry<'a, V>),
+    Occupied(OccupiedEntry<'a, A, V>),
     /// A vacant Entry
-    Vacant(VacantEntry<'a, V>),
+    Vacant(VacantEntry<'a, A, V>),
 }
 
-impl<'a, V: Any + Clone> Entry<'a, V> {
+impl<'a, A: ?Sized + UncheckedAnyExt, V: IntoBox<A>> Entry<'a, A, V> {
     /// Ensures a value is in the entry by inserting the default if empty, and returns
     /// a mutable reference to the value in the entry.
+    #[inline]
     pub fn or_insert(self, default: V) -> &'a mut V {
         match self {
             Entry::Occupied(inner) => inner.into_mut(),
@@ -225,6 +302,7 @@ impl<'a, V: Any + Clone> Entry<'a, V> {
 
     /// Ensures a value is in the entry by inserting the result of the default function if empty,
     /// and returns a mutable reference to the value in the entry.
+    #[inline]
     pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
         match self {
             Entry::Occupied(inner) => inner.into_mut(),
@@ -233,77 +311,51 @@ impl<'a, V: Any + Clone> Entry<'a, V> {
     }
 }
 
-impl<'a, V: Any> OccupiedEntry<'a, V> {
+impl<'a, A: ?Sized + UncheckedAnyExt, V: IntoBox<A>> OccupiedEntry<'a, A, V> {
     /// Gets a reference to the value in the entry
+    #[inline]
     pub fn get(&self) -> &V {
         unsafe { self.inner.get().downcast_ref_unchecked() }
     }
 
     /// Gets a mutable reference to the value in the entry
+    #[inline]
     pub fn get_mut(&mut self) -> &mut V {
         unsafe { self.inner.get_mut().downcast_mut_unchecked() }
     }
 
     /// Converts the OccupiedEntry into a mutable reference to the value in the entry
     /// with a lifetime bound to the collection itself
+    #[inline]
     pub fn into_mut(self) -> &'a mut V {
         unsafe { self.inner.into_mut().downcast_mut_unchecked() }
     }
 
     /// Sets the value of the entry, and returns the entry's old value
+    #[inline]
     pub fn insert(&mut self, value: V) -> V {
-        unsafe { *self.inner.insert(Box::new(value)).downcast_unchecked() }
+        unsafe { *self.inner.insert(value.into_box()).downcast_unchecked() }
     }
 
     /// Takes the value out of the entry, and returns it
+    #[inline]
     pub fn remove(self) -> V {
         unsafe { *self.inner.remove().downcast_unchecked() }
     }
 }
 
-impl<'a, V: Any> VacantEntry<'a, V> {
+impl<'a, A: ?Sized + UncheckedAnyExt, V: IntoBox<A>> VacantEntry<'a, A, V> {
     /// Sets the value of the entry with the VacantEntry's key,
     /// and returns a mutable reference to it
+    #[inline]
     pub fn insert(self, value: V) -> &'a mut V {
-        unsafe { self.inner.insert(Box::new(value)).downcast_mut_unchecked() }
+        unsafe { self.inner.insert(value.into_box()).downcast_mut_unchecked() }
     }
 }
 
-#[bench]
-fn bench_insertion(b: &mut ::test::Bencher) {
-    b.iter(|| {
-        let mut data = AnyMap::new();
-        for _ in 0..100 {
-            let _ = data.insert(42);
-        }
-    })
-}
-
-#[bench]
-fn bench_get_missing(b: &mut ::test::Bencher) {
-    b.iter(|| {
-        let data = AnyMap::new();
-        for _ in 0..100 {
-            assert_eq!(data.get(), None::<&i32>);
-        }
-    })
-}
-
-#[bench]
-fn bench_get_present(b: &mut ::test::Bencher) {
-    b.iter(|| {
-        let mut data = AnyMap::new();
-        let _ = data.insert(42);
-        // These inner loops are a feeble attempt to drown the other factors.
-        for _ in 0..100 {
-            assert_eq!(data.get(), Some(&42));
-        }
-    })
-}
-
 #[cfg(test)]
 mod tests {
-    use {AnyMap, Entry};
+    use super::*;
 
     #[derive(Clone, Debug, PartialEq)] struct A(i32);
     #[derive(Clone, Debug, PartialEq)] struct B(i32);
@@ -313,77 +365,89 @@ mod tests {
     #[derive(Clone, Debug, PartialEq)] struct F(i32);
     #[derive(Clone, Debug, PartialEq)] struct J(i32);
 
-    #[test]
-    fn test_entry() {
-        let mut map: AnyMap = AnyMap::new();
-        assert_eq!(map.insert(A(10)), None);
-        assert_eq!(map.insert(B(20)), None);
-        assert_eq!(map.insert(C(30)), None);
-        assert_eq!(map.insert(D(40)), None);
-        assert_eq!(map.insert(E(50)), None);
-        assert_eq!(map.insert(F(60)), None);
-
-        // Existing key (insert)
-        match map.entry::<A>() {
-            Entry::Vacant(_) => unreachable!(),
-            Entry::Occupied(mut view) => {
-                assert_eq!(view.get(), &A(10));
-                assert_eq!(view.insert(A(100)), A(10));
-            }
-        }
-        assert_eq!(map.get::<A>().unwrap(), &A(100));
-        assert_eq!(map.len(), 6);
+    macro_rules! test_entry {
+        ($name:ident, $init:ty) => {
+            #[test]
+            fn $name() {
+                let mut map = <$init>::new();
+                assert_eq!(map.insert(A(10)), None);
+                assert_eq!(map.insert(B(20)), None);
+                assert_eq!(map.insert(C(30)), None);
+                assert_eq!(map.insert(D(40)), None);
+                assert_eq!(map.insert(E(50)), None);
+                assert_eq!(map.insert(F(60)), None);
+
+                // Existing key (insert)
+                match map.entry::<A>() {
+                    Entry::Vacant(_) => unreachable!(),
+                    Entry::Occupied(mut view) => {
+                        assert_eq!(view.get(), &A(10));
+                        assert_eq!(view.insert(A(100)), A(10));
+                    }
+                }
+                assert_eq!(map.get::<A>().unwrap(), &A(100));
+                assert_eq!(map.len(), 6);
+
+
+                // Existing key (update)
+                match map.entry::<B>() {
+                    Entry::Vacant(_) => unreachable!(),
+                    Entry::Occupied(mut view) => {
+                        let v = view.get_mut();
+                        let new_v = B(v.0 * 10);
+                        *v = new_v;
+                    }
+                }
+                assert_eq!(map.get::<B>().unwrap(), &B(200));
+                assert_eq!(map.len(), 6);
 
 
-        // Existing key (update)
-        match map.entry::<B>() {
-            Entry::Vacant(_) => unreachable!(),
-            Entry::Occupied(mut view) => {
-                let v = view.get_mut();
-                let new_v = B(v.0 * 10);
-                *v = new_v;
-            }
-        }
-        assert_eq!(map.get::<B>().unwrap(), &B(200));
-        assert_eq!(map.len(), 6);
+                // Existing key (remove)
+                match map.entry::<C>() {
+                    Entry::Vacant(_) => unreachable!(),
+                    Entry::Occupied(view) => {
+                        assert_eq!(view.remove(), C(30));
+                    }
+                }
+                assert_eq!(map.get::<C>(), None);
+                assert_eq!(map.len(), 5);
 
 
-        // Existing key (remove)
-        match map.entry::<C>() {
-            Entry::Vacant(_) => unreachable!(),
-            Entry::Occupied(view) => {
-                assert_eq!(view.remove(), C(30));
+                // Inexistent key (insert)
+                match map.entry::<J>() {
+                    Entry::Occupied(_) => unreachable!(),
+                    Entry::Vacant(view) => {
+                        assert_eq!(*view.insert(J(1000)), J(1000));
+                    }
+                }
+                assert_eq!(map.get::<J>().unwrap(), &J(1000));
+                assert_eq!(map.len(), 6);
+
+                // Entry.or_insert on existing key
+                map.entry::<B>().or_insert(B(71)).0 += 1;
+                assert_eq!(map.get::<B>().unwrap(), &B(201));
+                assert_eq!(map.len(), 6);
+
+                // Entry.or_insert on nonexisting key
+                map.entry::<C>().or_insert(C(300)).0 += 1;
+                assert_eq!(map.get::<C>().unwrap(), &C(301));
+                assert_eq!(map.len(), 7);
             }
         }
-        assert_eq!(map.get::<C>(), None);
-        assert_eq!(map.len(), 5);
+    }
 
+    test_entry!(test_entry_any, AnyMap);
+    test_entry!(test_entry_cloneany, Map<dyn CloneAny>);
 
-        // Inexistent key (insert)
-        match map.entry::<J>() {
-            Entry::Occupied(_) => unreachable!(),
-            Entry::Vacant(view) => {
-                assert_eq!(*view.insert(J(1000)), J(1000));
-            }
-        }
-        assert_eq!(map.get::<J>().unwrap(), &J(1000));
-        assert_eq!(map.len(), 6);
-
-        // Entry.or_insert on existing key
-        map.entry::<B>().or_insert(B(71)).0 += 1;
-        assert_eq!(map.get::<B>().unwrap(), &B(201));
-        assert_eq!(map.len(), 6);
-
-        // Entry.or_insert on nonexisting key
-        map.entry::<C>().or_insert(C(300)).0 += 1;
-        assert_eq!(map.get::<C>().unwrap(), &C(301));
-        assert_eq!(map.len(), 7);
+    #[test]
+    fn test_default() {
+        let map: AnyMap = Default::default();
+        assert_eq!(map.len(), 0);
     }
 
-    #[cfg(feature = "clone")]
     #[test]
     fn test_clone() {
-        let mut map = AnyMap::new();
+        let mut map: Map<dyn CloneAny> = Map::new();
         let _ = map.insert(A(1));
         let _ = map.insert(B(2));
         let _ = map.insert(D(3));
@@ -401,10 +465,26 @@ mod tests {
         assert_eq!(map2.get::<J>(), Some(&J(6)));
     }
 
-    #[cfg(feature = "concurrent")]
     #[test]
-    fn test_concurrent() {
-        fn assert_concurrent<T: Send + Sync>() { }
-        assert_concurrent::<AnyMap>();
+    fn test_varieties() {
+        fn assert_send<T: Send>() { }
+        fn assert_sync<T: Sync>() { }
+        fn assert_clone<T: Clone>() { }
+        fn assert_debug<T: ::core::fmt::Debug>() { }
+        assert_send::<Map<dyn Any + Send>>();
+        assert_send::<Map<dyn Any + Send + Sync>>();
+        assert_sync::<Map<dyn Any + Send + Sync>>();
+        assert_debug::<Map<dyn Any>>();
+        assert_debug::<Map<dyn Any + Send>>();
+        assert_debug::<Map<dyn Any + Send + Sync>>();
+        assert_send::<Map<dyn CloneAny + Send>>();
+        assert_send::<Map<dyn CloneAny + Send + Sync>>();
+        assert_sync::<Map<dyn CloneAny + Send + Sync>>();
+        assert_clone::<Map<dyn CloneAny + Send>>();
+        assert_clone::<Map<dyn CloneAny + Send + Sync>>();
+        assert_clone::<Map<dyn CloneAny + Send + Sync>>();
+        assert_debug::<Map<dyn CloneAny>>();
+        assert_debug::<Map<dyn CloneAny + Send>>();
+        assert_debug::<Map<dyn CloneAny + Send + Sync>>();
     }
 }