Remove now-unnecessary #[allow]s.
[anymap] / src / lib.rs
index 80769813c38a83755283ce5f92d5b91125ce2ec4..761936763fa48a3e0185e3b82d9eea66cadd4630 100644 (file)
@@ -1,17 +1,16 @@
 //! This crate provides the `AnyMap` type, a safe and convenient store for one value of each type.
 
-#![feature(core, std_misc)]
-#![cfg_attr(test, feature(test))]
+#![cfg_attr(all(feature = "bench", test), feature(test))]
 #![warn(missing_docs, unused_results)]
 
-#[cfg(test)]
+#[cfg(all(feature = "bench", test))]
 extern crate test;
 
-use std::any::{Any, TypeId};
+use std::any::TypeId;
 use std::marker::PhantomData;
 
-use raw::RawAnyMap;
-use unchecked_any::UncheckedAnyExt;
+use raw::RawMap;
+use any::{UncheckedAnyExt, IntoBox, Any};
 
 macro_rules! impl_common_methods {
     (
@@ -19,10 +18,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 +29,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,
                 }
@@ -83,12 +82,18 @@ macro_rules! impl_common_methods {
     }
 }
 
-mod unchecked_any;
+pub 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:
+///
+/// - 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.
+///
 /// ```rust
 /// # use anymap::AnyMap;
 /// let mut data = AnyMap::new();
@@ -98,7 +103,7 @@ pub mod raw;
 /// data.remove::<i32>();
 /// assert_eq!(data.get::<i32>(), None);
 ///
-/// #[derive(PartialEq, Debug)]
+/// #[derive(Clone, PartialEq, Debug)]
 /// struct Foo {
 ///     str: String,
 /// }
@@ -112,26 +117,42 @@ pub mod raw;
 ///
 /// Values containing non-static references are not permitted.
 #[derive(Debug)]
-pub struct AnyMap {
-    raw: RawAnyMap,
+pub struct Map<A: ?Sized + UncheckedAnyExt = 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 {
+    fn clone(&self) -> Map<A> {
+        Map {
+            raw: self.raw.clone(),
+        }
+    }
 }
 
+/// The most common type of `Map`: just using `Any`.
+///
+/// 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>;
+
 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> {
+    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> {
+    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>() })
     }
@@ -139,28 +160,28 @@ 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> {
+    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>())
         }
     }
 
     /// 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> {
+    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> {
+    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,
@@ -172,67 +193,47 @@ impl AnyMap {
             }),
         }
     }
+}
 
-    /// Get a reference to the raw untyped map underlying the `AnyMap`.
-    ///
-    /// Normal users will not need to use this, but generic libraries working with an `AnyMap` may
-    /// just find a use for it occasionally.
-    #[inline]
-    pub fn as_raw(&self) -> &RawAnyMap {
+impl<A: ?Sized + UncheckedAnyExt> AsRef<RawMap<A>> for Map<A> {
+    fn as_ref(&self) -> &RawMap<A> {
         &self.raw
     }
+}
 
-    /// Get a mutable reference to the raw untyped map underlying the `AnyMap`.
-    ///
-    /// Normal users will not need to use this, but generic libraries working with an `AnyMap` may
-    /// just find a use for it occasionally.
-    #[inline]
-    pub fn as_raw_mut(&mut self) -> &mut RawAnyMap {
+impl<A: ?Sized + UncheckedAnyExt> AsMut<RawMap<A>> for Map<A> {
+    fn as_mut(&mut self) -> &mut RawMap<A> {
         &mut self.raw
     }
+}
 
-    /// Convert the `AnyMap` into the raw untyped map that underlyies it.
-    ///
-    /// Normal users will not need to use this, but generic libraries working with an `AnyMap` may
-    /// just find a use for it occasionally.
-    #[inline]
-    pub fn into_raw(self) -> RawAnyMap {
+impl<A: ?Sized + UncheckedAnyExt> Into<RawMap<A>> for Map<A> {
+    fn into(self) -> RawMap<A> {
         self.raw
     }
-
-    /// Convert a raw untyped map into an `AnyMap`.
-    ///
-    /// Normal users will not need to use this, but generic libraries working with an `AnyMap` may
-    /// just find a use for it occasionally.
-    #[inline]
-    pub fn from_raw(raw: RawAnyMap) -> AnyMap {
-        AnyMap {
-            raw: 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> + Clone> 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.
     pub fn or_insert(self, default: V) -> &'a mut V {
@@ -252,7 +253,7 @@ 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
     pub fn get(&self) -> &V {
         unsafe { self.inner.get().downcast_ref_unchecked() }
@@ -271,7 +272,7 @@ impl<'a, V: Any> OccupiedEntry<'a, V> {
 
     /// Sets the value of the entry, and returns the entry's old value
     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
@@ -280,14 +281,15 @@ impl<'a, V: Any> OccupiedEntry<'a, V> {
     }
 }
 
-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
     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() }
     }
 }
 
+#[cfg(feature = "bench")]
 #[bench]
 fn bench_insertion(b: &mut ::test::Bencher) {
     b.iter(|| {
@@ -298,6 +300,7 @@ fn bench_insertion(b: &mut ::test::Bencher) {
     })
 }
 
+#[cfg(feature = "bench")]
 #[bench]
 fn bench_get_missing(b: &mut ::test::Bencher) {
     b.iter(|| {
@@ -308,6 +311,7 @@ fn bench_get_missing(b: &mut ::test::Bencher) {
     })
 }
 
+#[cfg(feature = "bench")]
 #[bench]
 fn bench_get_present(b: &mut ::test::Bencher) {
     b.iter(|| {
@@ -320,67 +324,131 @@ fn bench_get_present(b: &mut ::test::Bencher) {
     })
 }
 
-#[test]
-fn test_entry() {
-    #[derive(Debug, PartialEq)] struct A(i32);
-    #[derive(Debug, PartialEq)] struct B(i32);
-    #[derive(Debug, PartialEq)] struct C(i32);
-    #[derive(Debug, PartialEq)] struct D(i32);
-    #[derive(Debug, PartialEq)] struct E(i32);
-    #[derive(Debug, PartialEq)] struct F(i32);
-    #[derive(Debug, PartialEq)] struct J(i32);
-
-    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));
+#[cfg(test)]
+mod tests {
+    use {Map, AnyMap, Entry};
+    use any::{Any, CloneAny};
+
+    #[derive(Clone, Debug, PartialEq)] struct A(i32);
+    #[derive(Clone, Debug, PartialEq)] struct B(i32);
+    #[derive(Clone, Debug, PartialEq)] struct C(i32);
+    #[derive(Clone, Debug, PartialEq)] struct D(i32);
+    #[derive(Clone, Debug, PartialEq)] struct E(i32);
+    #[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);
+        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;
+        // 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().unwrap(), &B(200));
-    assert_eq!(map.len(), 6);
+        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));
+        // 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);
+        assert_eq!(map.get::<C>(), None);
+        assert_eq!(map.len(), 5);
 
 
-    // Inexistent key (insert)
-    match map.entry::<J>() {
-        Entry::Occupied(_) => unreachable!(),
-        Entry::Vacant(view) => {
-            assert_eq!(*view.insert(J(1000)), J(1000));
+        // 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_clone() {
+        let mut map: Map<CloneAny> = Map::new();
+        let _ = map.insert(A(1));
+        let _ = map.insert(B(2));
+        let _ = map.insert(D(3));
+        let _ = map.insert(E(4));
+        let _ = map.insert(F(5));
+        let _ = map.insert(J(6));
+        let map2 = map.clone();
+        assert_eq!(map2.len(), 6);
+        assert_eq!(map2.get::<A>(), Some(&A(1)));
+        assert_eq!(map2.get::<B>(), Some(&B(2)));
+        assert_eq!(map2.get::<C>(), None);
+        assert_eq!(map2.get::<D>(), Some(&D(3)));
+        assert_eq!(map2.get::<E>(), Some(&E(4)));
+        assert_eq!(map2.get::<F>(), Some(&F(5)));
+        assert_eq!(map2.get::<J>(), Some(&J(6)));
+    }
+
+    #[test]
+    fn test_varieties() {
+        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>>();
     }
-    assert_eq!(map.get::<J>().unwrap(), &J(1000));
-    assert_eq!(map.len(), 6);
 }