X-Git-Url: https://git.chrismorgan.info/anymap/blobdiff_plain/c6480a91723804547a8cc99a2066f64436008abe..0ad7c307eb377a8149dd0cb519caca1380b4bd6f:/src/lib.rs diff --git a/src/lib.rs b/src/lib.rs index e38670b..b5ae44a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,6 @@ //! This crate provides the `AnyMap` type, a safe and convenient store for one value of each type. -#![feature(core, std_misc, convert)] +#![cfg_attr(feature = "unstable", feature(core, std_misc))] #![cfg_attr(test, feature(test))] #![warn(missing_docs, unused_results)] @@ -10,8 +10,8 @@ extern crate test; use std::any::TypeId; use std::marker::PhantomData; -use raw::{RawAnyMap, Any}; -use unchecked_any::UncheckedAnyExt; +use raw::RawMap; +use any::{UncheckedAnyExt, IntoBox, Any}; macro_rules! impl_common_methods { ( @@ -19,10 +19,10 @@ macro_rules! impl_common_methods { new() => $new:expr; with_capacity($with_capacity_arg:ident) => $with_capacity:expr; ) => { - impl $t { + impl $t { /// Create an empty collection. #[inline] - pub fn new() -> $t { + pub fn new() -> $t { $t { $field: $new, } @@ -30,7 +30,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 { $t { $field: $with_capacity, } @@ -83,14 +83,18 @@ macro_rules! impl_common_methods { } } -mod unchecked_any; +pub mod any; pub mod raw; -#[cfg(feature = "clone")] -mod with_clone; /// 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`) to add those bounds. +/// /// ```rust /// # use anymap::AnyMap; /// let mut data = AnyMap::new(); @@ -114,27 +118,42 @@ mod with_clone; /// /// Values containing non-static references are not permitted. #[derive(Debug)] -#[cfg_attr(feature = "clone", derive(Clone))] -pub struct AnyMap { - raw: RawAnyMap, +pub struct Map { + raw: RawMap, +} + +// #[derive(Clone)] would want A to implement Clone, but in reality it’s only Box that can. +impl Clone for Map where Box: Clone { + fn clone(&self) -> Map { + 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`? `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; + 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 Map { /// Returns a reference to the value stored in the collection for the type `T`, if it exists. - pub fn get(&self) -> Option<&T> { + pub fn get>(&self) -> Option<&T> { self.raw.get(&TypeId::of::()) .map(|any| unsafe { any.downcast_ref_unchecked::() }) } /// Returns a mutable reference to the value stored in the collection for the type `T`, /// if it exists. - pub fn get_mut(&mut self) -> Option<&mut T> { + pub fn get_mut>(&mut self) -> Option<&mut T> { self.raw.get_mut(&TypeId::of::()) .map(|any| unsafe { any.downcast_mut_unchecked::() }) } @@ -142,28 +161,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(&mut self, value: T) -> Option { + pub fn insert>(&mut self, value: T) -> Option { unsafe { - self.raw.insert(TypeId::of::(), Box::new(value)) + self.raw.insert(TypeId::of::(), value.into_box()) .map(|any| *any.downcast_unchecked::()) } } /// Removes the `T` value from the collection, /// returning it if there was one or `None` if there was not. - pub fn remove(&mut self) -> Option { + pub fn remove>(&mut self) -> Option { self.raw.remove(&TypeId::of::()) .map(|any| *unsafe { any.downcast_unchecked::() }) } /// Returns true if the collection contains a value of type `T`. #[inline] - pub fn contains(&self) -> bool { + pub fn contains>(&self) -> bool { self.raw.contains_key(&TypeId::of::()) } /// Gets the entry for the given type in the collection for in-place manipulation - pub fn entry(&mut self) -> Entry { + pub fn entry>(&mut self) -> Entry { match self.raw.entry(TypeId::of::()) { raw::Entry::Occupied(e) => Entry::Occupied(OccupiedEntry { inner: e, @@ -177,45 +196,45 @@ impl AnyMap { } } -impl AsRef for AnyMap { - fn as_ref(&self) -> &RawAnyMap { +impl AsRef> for Map { + fn as_ref(&self) -> &RawMap { &self.raw } } -impl AsMut for AnyMap { - fn as_mut(&mut self) -> &mut RawAnyMap { +impl AsMut> for Map { + fn as_mut(&mut self) -> &mut RawMap { &mut self.raw } } -impl Into for AnyMap { - fn into(self) -> RawAnyMap { +impl Into> for Map { + fn into(self) -> RawMap { self.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, } -/// 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, } -/// 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 + 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 { @@ -235,7 +254,7 @@ impl<'a, V: Any + Clone> Entry<'a, V> { } } -impl<'a, V: Any> OccupiedEntry<'a, V> { +impl<'a, A: ?Sized + UncheckedAnyExt, V: IntoBox> 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() } @@ -254,7 +273,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 @@ -263,11 +282,11 @@ impl<'a, V: Any> OccupiedEntry<'a, V> { } } -impl<'a, V: Any> VacantEntry<'a, V> { +impl<'a, A: ?Sized + UncheckedAnyExt, V: IntoBox> 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() } } } @@ -305,7 +324,8 @@ fn bench_get_present(b: &mut ::test::Bencher) { #[cfg(test)] mod tests { - use {AnyMap, Entry}; + use {Map, AnyMap, Entry}; + use any::{Any, CloneAny}; #[derive(Clone, Debug, PartialEq)] struct A(i32); #[derive(Clone, Debug, PartialEq)] struct B(i32); @@ -346,7 +366,7 @@ mod tests { *v = new_v; } } - assert_eq!(map.get().unwrap(), &B(200)); + assert_eq!(map.get::().unwrap(), &B(200)); assert_eq!(map.len(), 6); @@ -382,10 +402,9 @@ mod tests { assert_eq!(map.len(), 7); } - #[cfg(feature = "clone")] #[test] fn test_clone() { - let mut map = AnyMap::new(); + let mut map: Map = Map::new(); let _ = map.insert(A(1)); let _ = map.insert(B(2)); let _ = map.insert(D(3)); @@ -402,4 +421,32 @@ mod tests { assert_eq!(map2.get::(), Some(&F(5))); assert_eq!(map2.get::(), Some(&J(6))); } + + #[test] + fn test_varieties() { + fn assert_send() { } + fn assert_sync() { } + fn assert_clone() { } + fn assert_debug() { } + assert_send::>(); + assert_send::>(); + assert_sync::>(); + assert_sync::>(); + assert_debug::>(); + assert_debug::>(); + assert_debug::>(); + assert_debug::>(); + assert_send::>(); + assert_send::>(); + assert_sync::>(); + assert_sync::>(); + assert_clone::>(); + assert_clone::>(); + assert_clone::>(); + assert_clone::>(); + assert_debug::>(); + assert_debug::>(); + assert_debug::>(); + assert_debug::>(); + } }