no_std support
[anymap] / src / lib.rs
index 761936763fa48a3e0185e3b82d9eea66cadd4630..6366c70b5a3781fda251734893cf2585d7f196bc 100644 (file)
@@ -1,16 +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(all(feature = "bench", test), feature(test))]
 #![warn(missing_docs, unused_results)]
 
-#[cfg(all(feature = "bench", test))]
-extern crate test;
+#![cfg_attr(not(feature = "std"), no_std)]
 
-use std::any::TypeId;
-use std::marker::PhantomData;
+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");
+
+#[cfg(not(feature = "std"))]
+extern crate alloc;
+
+#[cfg(not(feature = "std"))]
+use alloc::boxed::Box;
 
 use raw::RawMap;
-use any::{UncheckedAnyExt, IntoBox, Any};
+use any::{UncheckedAnyExt, IntoBox};
+pub use any::CloneAny;
 
 macro_rules! impl_common_methods {
     (
@@ -79,24 +89,46 @@ macro_rules! impl_common_methods {
                 self.$field.clear()
             }
         }
+
+        impl<A: ?Sized + UncheckedAnyExt> Default for $t<A> {
+            #[inline]
+            fn default() -> $t<A> {
+                $t::new()
+            }
+        }
     }
 }
 
-pub mod 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 `anymap::any::Any`, but there are other choices:
+/// 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`.
-/// - You can add on `+ Send` and/or `+ Sync` (e.g. `Map<Any + Send>`) to add those bounds.
+/// - 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));
@@ -117,12 +149,13 @@ pub mod raw;
 ///
 /// Values containing non-static references are not permitted.
 #[derive(Debug)]
-pub struct Map<A: ?Sized + UncheckedAnyExt = Any> {
+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(),
@@ -130,12 +163,12 @@ impl<A: ?Sized + UncheckedAnyExt> Clone for Map<A> where Box<A>: Clone {
     }
 }
 
-/// The most common type of `Map`: just using `Any`.
+/// 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<Any>;
+pub type AnyMap = Map<dyn Any>;
 
 impl_common_methods! {
     field: Map.raw;
@@ -145,6 +178,7 @@ impl_common_methods! {
 
 impl<A: ?Sized + UncheckedAnyExt> Map<A> {
     /// Returns a reference to the value stored in the collection for the type `T`, if it exists.
+    #[inline]
     pub fn get<T: IntoBox<A>>(&self) -> Option<&T> {
         self.raw.get(&TypeId::of::<T>())
             .map(|any| unsafe { any.downcast_ref_unchecked::<T>() })
@@ -152,6 +186,7 @@ impl<A: ?Sized + UncheckedAnyExt> Map<A> {
 
     /// Returns a mutable reference to the value stored in the collection for the type `T`,
     /// if it exists.
+    #[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>() })
@@ -160,6 +195,7 @@ impl<A: ?Sized + UncheckedAnyExt> Map<A> {
     /// 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.
+    #[inline]
     pub fn insert<T: IntoBox<A>>(&mut self, value: T) -> Option<T> {
         unsafe {
             self.raw.insert(TypeId::of::<T>(), value.into_box())
@@ -169,6 +205,7 @@ impl<A: ?Sized + UncheckedAnyExt> Map<A> {
 
     /// Removes the `T` value from the collection,
     /// returning it if there was one or `None` if there was not.
+    #[inline]
     pub fn remove<T: IntoBox<A>>(&mut self) -> Option<T> {
         self.raw.remove(&TypeId::of::<T>())
             .map(|any| *unsafe { any.downcast_unchecked::<T>() })
@@ -181,6 +218,7 @@ impl<A: ?Sized + UncheckedAnyExt> Map<A> {
     }
 
     /// Gets the entry for the given type in the collection for in-place manipulation
+    #[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 {
@@ -196,20 +234,23 @@ impl<A: ?Sized + UncheckedAnyExt> Map<A> {
 }
 
 impl<A: ?Sized + UncheckedAnyExt> AsRef<RawMap<A>> for Map<A> {
+    #[inline]
     fn as_ref(&self) -> &RawMap<A> {
         &self.raw
     }
 }
 
 impl<A: ?Sized + UncheckedAnyExt> AsMut<RawMap<A>> for Map<A> {
+    #[inline]
     fn as_mut(&mut self) -> &mut RawMap<A> {
         &mut self.raw
     }
 }
 
-impl<A: ?Sized + UncheckedAnyExt> Into<RawMap<A>> for Map<A> {
-    fn into(self) -> RawMap<A> {
-        self.raw
+impl<A: ?Sized + UncheckedAnyExt> From<Map<A>> for RawMap<A> {
+    #[inline]
+    fn from(map: Map<A>) -> RawMap<A> {
+        map.raw
     }
 }
 
@@ -233,9 +274,10 @@ pub enum Entry<'a, A: ?Sized + UncheckedAnyExt, V: 'a> {
     Vacant(VacantEntry<'a, A, V>),
 }
 
-impl<'a, A: ?Sized + UncheckedAnyExt, V: IntoBox<A> + Clone> Entry<'a, 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(),
@@ -245,6 +287,7 @@ impl<'a, A: ?Sized + UncheckedAnyExt, V: IntoBox<A> + Clone> Entry<'a, 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(),
@@ -255,27 +298,32 @@ impl<'a, A: ?Sized + UncheckedAnyExt, V: IntoBox<A> + Clone> Entry<'a, 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(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() }
     }
@@ -284,50 +332,15 @@ impl<'a, A: ?Sized + UncheckedAnyExt, V: IntoBox<A>> OccupiedEntry<'a, 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(value.into_box()).downcast_mut_unchecked() }
     }
 }
 
-#[cfg(feature = "bench")]
-#[bench]
-fn bench_insertion(b: &mut ::test::Bencher) {
-    b.iter(|| {
-        let mut data = AnyMap::new();
-        for _ in 0..100 {
-            let _ = data.insert(42);
-        }
-    })
-}
-
-#[cfg(feature = "bench")]
-#[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>);
-        }
-    })
-}
-
-#[cfg(feature = "bench")]
-#[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 {Map, AnyMap, Entry};
-    use any::{Any, CloneAny};
+    use super::*;
 
     #[derive(Clone, Debug, PartialEq)] struct A(i32);
     #[derive(Clone, Debug, PartialEq)] struct B(i32);
@@ -337,76 +350,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);
     }
 
     #[test]
     fn test_clone() {
-        let mut map: Map<CloneAny> = Map::new();
+        let mut map: Map<dyn CloneAny> = Map::new();
         let _ = map.insert(A(1));
         let _ = map.insert(B(2));
         let _ = map.insert(D(3));
@@ -429,26 +455,21 @@ mod tests {
         fn assert_send<T: Send>() { }
         fn assert_sync<T: Sync>() { }
         fn assert_clone<T: Clone>() { }
-        fn assert_debug<T: ::std::fmt::Debug>() { }
-        assert_send::<Map<Any + Send>>();
-        assert_send::<Map<Any + Send + Sync>>();
-        assert_sync::<Map<Any + Sync>>();
-        assert_sync::<Map<Any + Send + Sync>>();
-        assert_debug::<Map<Any>>();
-        assert_debug::<Map<Any + Send>>();
-        assert_debug::<Map<Any + Sync>>();
-        assert_debug::<Map<Any + Send + Sync>>();
-        assert_send::<Map<CloneAny + Send>>();
-        assert_send::<Map<CloneAny + Send + Sync>>();
-        assert_sync::<Map<CloneAny + Sync>>();
-        assert_sync::<Map<CloneAny + Send + Sync>>();
-        assert_clone::<Map<CloneAny + Send>>();
-        assert_clone::<Map<CloneAny + Send + Sync>>();
-        assert_clone::<Map<CloneAny + Sync>>();
-        assert_clone::<Map<CloneAny + Send + Sync>>();
-        assert_debug::<Map<CloneAny>>();
-        assert_debug::<Map<CloneAny + Send>>();
-        assert_debug::<Map<CloneAny + Sync>>();
-        assert_debug::<Map<CloneAny + Send + Sync>>();
+        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>>();
     }
 }