HashMap feature parity: impl Extend, notes on more
[anymap] / src / lib.rs
index bcd5c231a4e0d75e156974b833835dd68657a179..d4f227a293da168d6b4ffa0119ffc1c8aa7946f5 100644 (file)
@@ -1,12 +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.
 
 #![warn(missing_docs, unused_results)]
 
 
 #![warn(missing_docs, unused_results)]
 
-use std::any::TypeId;
-use std::marker::PhantomData;
+#![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");
+
+#[cfg(not(feature = "std"))]
+extern crate alloc;
+
+#[cfg(not(feature = "std"))]
+use alloc::boxed::Box;
 
 use raw::RawMap;
 
 use raw::RawMap;
-use any::{UncheckedAnyExt, IntoBox, Any};
+use any::{UncheckedAnyExt, IntoBox};
+pub use any::CloneAny;
 
 macro_rules! impl_common_methods {
     (
 
 macro_rules! impl_common_methods {
     (
@@ -57,6 +71,10 @@ macro_rules! impl_common_methods {
                 self.$field.shrink_to_fit()
             }
 
                 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 {
             /// Returns the number of items in the collection.
             #[inline]
             pub fn len(&self) -> usize {
@@ -75,24 +93,46 @@ macro_rules! impl_common_methods {
                 self.$field.clear()
             }
         }
                 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
 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`; 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:
 ///
 ///
-/// - 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.
+/// - <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
 ///
 /// ```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));
 /// assert_eq!(data.get(), None::<&i32>);
 /// data.insert(42i32);
 /// assert_eq!(data.get(), Some(&42i32));
@@ -113,7 +153,7 @@ pub mod raw;
 ///
 /// Values containing non-static references are not permitted.
 #[derive(Debug)]
 ///
 /// 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>,
 }
 
     raw: RawMap<A>,
 }
 
@@ -127,12 +167,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.
 ///
 /// 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;
 
 impl_common_methods! {
     field: Map.raw;
@@ -167,6 +207,8 @@ impl<A: ?Sized + UncheckedAnyExt> Map<A> {
         }
     }
 
         }
     }
 
+    // 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.
     #[inline]
     /// Removes the `T` value from the collection,
     /// returning it if there was one or `None` if there was not.
     #[inline]
@@ -197,6 +239,15 @@ impl<A: ?Sized + UncheckedAnyExt> Map<A> {
     }
 }
 
     }
 }
 
+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> {
 impl<A: ?Sized + UncheckedAnyExt> AsRef<RawMap<A>> for Map<A> {
     #[inline]
     fn as_ref(&self) -> &RawMap<A> {
@@ -211,10 +262,10 @@ impl<A: ?Sized + UncheckedAnyExt> AsMut<RawMap<A>> for Map<A> {
     }
 }
 
     }
 }
 
-impl<A: ?Sized + UncheckedAnyExt> Into<RawMap<A>> for Map<A> {
+impl<A: ?Sized + UncheckedAnyExt> From<Map<A>> for RawMap<A> {
     #[inline]
     #[inline]
-    fn into(self) -> RawMap<A> {
-        self.raw
+    fn from(map: Map<A>) -> RawMap<A> {
+        map.raw
     }
 }
 
     }
 }
 
@@ -304,8 +355,7 @@ impl<'a, A: ?Sized + UncheckedAnyExt, V: IntoBox<A>> VacantEntry<'a, A, V> {
 
 #[cfg(test)]
 mod tests {
 
 #[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);
 
     #[derive(Clone, Debug, PartialEq)] struct A(i32);
     #[derive(Clone, Debug, PartialEq)] struct B(i32);
@@ -387,11 +437,17 @@ mod tests {
     }
 
     test_entry!(test_entry_any, AnyMap);
     }
 
     test_entry!(test_entry_any, AnyMap);
-    test_entry!(test_entry_cloneany, Map<CloneAny>);
+    test_entry!(test_entry_cloneany, Map<dyn CloneAny>);
+
+    #[test]
+    fn test_default() {
+        let map: AnyMap = Default::default();
+        assert_eq!(map.len(), 0);
+    }
 
     #[test]
     fn test_clone() {
 
     #[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));
         let _ = map.insert(A(1));
         let _ = map.insert(B(2));
         let _ = map.insert(D(3));
@@ -414,26 +470,21 @@ mod tests {
         fn assert_send<T: Send>() { }
         fn assert_sync<T: Sync>() { }
         fn assert_clone<T: Clone>() { }
         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>>();
     }
 }
     }
 }