X-Git-Url: https://git.chrismorgan.info/anymap/blobdiff_plain/7c9bd44916a760d84684e7afcadaa946b8db5bc5..deb7daf170b608a1d7965c702d340249bfe22bbd:/src/lib.rs diff --git a/src/lib.rs b/src/lib.rs index 043578f..a6f0e46 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,7 @@ //! This crate provides the `AnyMap` type, a safe and convenient store for one value of each type. -#![feature(default_type_params)] +#![feature(core, std_misc, hash)] +#![cfg_attr(test, feature(test))] #![warn(unused_qualifications, non_upper_case_globals, variant_size_differences, unused_typecasts, missing_docs, unused_results)] @@ -8,43 +9,42 @@ #[cfg(test)] extern crate test; -use std::any::Any; -use std::intrinsics::{forget, TypeId}; +use std::any::{Any, TypeId}; +use std::mem::forget; use std::collections::HashMap; use std::collections::hash_map; -use std::hash::{Hash, Hasher, Writer}; -use std::mem::{transmute, transmute_copy}; +use std::hash::Hasher; +use std::collections::hash_state::HashState; +use std::mem::transmute; use std::raw::TraitObject; +use std::marker::PhantomData; -pub use Entry::{Vacant, Occupied}; +struct TypeIdHasher { + value: u64, +} -struct TypeIdHasher; +struct TypeIdState; -struct TypeIdState { - value: u64, +impl HashState for TypeIdState { + type Hasher = TypeIdHasher; + + fn hasher(&self) -> TypeIdHasher { + TypeIdHasher { value: 0 } + } } -impl Writer for TypeIdState { +impl Hasher for TypeIdHasher { #[inline(always)] fn write(&mut self, bytes: &[u8]) { // This expects to receive one and exactly one 64-bit value debug_assert!(bytes.len() == 8); unsafe { - std::ptr::copy_nonoverlapping_memory(&mut self.value, - transmute(&bytes[0]), - 1) + std::ptr::copy_nonoverlapping(&mut self.value, transmute(&bytes[0]), 1) } } -} -impl Hasher for TypeIdHasher { - fn hash>(&self, value: &T) -> u64 { - let mut state = TypeIdState { - value: 0, - }; - value.hash(&mut state); - state.value - } + #[inline(always)] + fn finish(&self) -> u64 { self.value } } /// An extension of `AnyRefExt` allowing unchecked downcasting of trait objects to `&T`. @@ -54,11 +54,11 @@ trait UncheckedAnyRefExt<'a> { unsafe fn downcast_ref_unchecked(self) -> &'a T; } -impl<'a> UncheckedAnyRefExt<'a> for &'a (Any + 'a) { +impl<'a> UncheckedAnyRefExt<'a> for &'a Any { #[inline] unsafe fn downcast_ref_unchecked(self) -> &'a T { // Get the raw representation of the trait object - let to: TraitObject = transmute_copy(&self); + let to: TraitObject = transmute(self); // Extract the data pointer transmute(to.data) @@ -72,11 +72,11 @@ trait UncheckedAnyMutRefExt<'a> { unsafe fn downcast_mut_unchecked(self) -> &'a mut T; } -impl<'a> UncheckedAnyMutRefExt<'a> for &'a mut (Any + 'a) { +impl<'a> UncheckedAnyMutRefExt<'a> for &'a mut Any { #[inline] unsafe fn downcast_mut_unchecked(self) -> &'a mut T { // Get the raw representation of the trait object - let to: TraitObject = transmute_copy(&self); + let to: TraitObject = transmute(self); // Extract the data pointer transmute(to.data) @@ -104,122 +104,204 @@ impl UncheckedBoxAny for Box { } } -/// A map containing zero or one values for any given type and allowing convenient, +/// A collection containing zero or one values for any given type and allowing convenient, /// type-safe access to those values. /// /// ```rust /// # use anymap::AnyMap; /// let mut data = AnyMap::new(); -/// assert_eq!(data.get(), None::<&int>); -/// data.insert(42i); -/// assert_eq!(data.get(), Some(&42i)); -/// data.remove::(); -/// assert_eq!(data.get::(), None); +/// assert_eq!(data.get(), None::<&i32>); +/// data.insert(42i32); +/// assert_eq!(data.get(), Some(&42i32)); +/// data.remove::(); +/// assert_eq!(data.get::(), None); /// -/// #[deriving(PartialEq, Show)] +/// #[derive(PartialEq, Debug)] /// struct Foo { /// str: String, /// } /// /// assert_eq!(data.get::(), None); -/// data.insert(Foo { str: "foo".to_string() }); -/// assert_eq!(data.get(), Some(&Foo { str: "foo".to_string() })); +/// data.insert(Foo { str: format!("foo") }); +/// assert_eq!(data.get(), Some(&Foo { str: format!("foo") })); /// data.get_mut::().map(|foo| foo.str.push('t')); -/// assert_eq!(data.get::().unwrap().str.as_slice(), "foot"); +/// assert_eq!(&*data.get::().unwrap().str, "foot"); /// ``` /// /// Values containing non-static references are not permitted. pub struct AnyMap { - data: HashMap, TypeIdHasher>, + data: HashMap, TypeIdState>, } impl AnyMap { /// Construct a new `AnyMap`. + #[inline] pub fn new() -> AnyMap { AnyMap { - data: HashMap::with_hasher(TypeIdHasher), + data: HashMap::with_hash_state(TypeIdState), } } -} -impl AnyMap { - /// Deprecated: Renamed to `get`. - #[deprecated = "Renamed to `get`"] - pub fn find(&self) -> Option<&T> { - self.get::() + /// Creates an empty AnyMap with the given initial capacity. + #[inline] + pub fn with_capcity(capacity: usize) -> AnyMap { + AnyMap { + data: HashMap::with_capacity_and_hash_state(capacity, TypeIdState), + } + } + + /// Returns the number of elements the collection can hold without reallocating. + #[inline] + pub fn capacity(&self) -> usize { + self.data.capacity() + } + + /// Reserves capacity for at least `additional` more elements to be inserted + /// in the `AnyMap`. The collection may reserve more space to avoid + /// frequent reallocations. + /// + /// # Panics + /// + /// Panics if the new allocation size overflows `usize`. + #[inline] + pub fn reserve(&mut self, additional: usize) { + self.data.reserve(additional) } - /// Deprecated: Renamed to `get_mut`. - #[deprecated = "Renamed to `get_mut`"] - pub fn find_mut(&mut self) -> Option<&mut T> { - self.get_mut::() + /// Shrinks the capacity of the collection as much as possible. It will drop + /// down as much as possible while maintaining the internal rules + /// and possibly leaving some space in accordance with the resize policy. + #[inline] + pub fn shrink_to_fit(&mut self) { + self.data.shrink_to_fit() + } + + /// An iterator visiting all items in the collection in arbitrary order. + /// Iterator element type is `&Any`. + /// + /// This is probably not a great deal of use. + #[inline] + pub fn iter(&self) -> Iter { + Iter { + inner: self.data.iter(), + } + } + + /// An iterator visiting all items in the collection in arbitrary order. + /// Iterator element type is `&mut Any`. + /// + /// This is probably not a great deal of use. + #[inline] + pub fn iter_mut(&mut self) -> IterMut { + IterMut { + inner: self.data.iter_mut(), + } + } + + /// An iterator visiting all items in the collection in arbitrary order. + /// Creates a consuming iterator, that is, one that moves each item + /// out of the map in arbitrary order. The map cannot be used after + /// calling this. + /// + /// Iterator element type is `Box`. + #[inline] + pub fn into_iter(self) -> IntoIter { + IntoIter { + inner: self.data.into_iter(), + } } - /// Retrieve the value stored in the map for the type `T`, if it exists. + /// Returns a reference to the value stored in the collection for the type `T`, if it exists. pub fn get(&self) -> Option<&T> { self.data.get(&TypeId::of::()) .map(|any| unsafe { any.downcast_ref_unchecked::() }) } - /// Retrieve a mutable reference to the value stored in the map for the type `T`, if it exists. + /// 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> { self.data.get_mut(&TypeId::of::()) .map(|any| unsafe { any.downcast_mut_unchecked::() }) } - /// Set the value contained in the map for the type `T`. - /// If there is a previous value stored, it will be returned. + /// 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 { - self.data.insert(TypeId::of::(), box value as Box) + self.data.insert(TypeId::of::(), Box::new(value) as Box) .map(|any| *unsafe { any.downcast_unchecked::() }) } - /// Remove and return the value for the type `T` if it existed. + /// 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 { self.data.remove(&TypeId::of::()) .map(|any| *unsafe { any.downcast_unchecked::() }) } - /// Does a value of type `T` exist? + /// Returns true if the collection contains a value of type `T`. pub fn contains(&self) -> bool { self.data.contains_key(&TypeId::of::()) } - /// Gets the given key's corresponding entry in the map for in-place manipulation + /// Gets the entry for the given type in the collection for in-place manipulation pub fn entry(&mut self) -> Entry { match self.data.entry(TypeId::of::()) { - hash_map::Occupied(e) => Occupied(OccupiedEntry { entry: e }), - hash_map::Vacant(e) => Vacant(VacantEntry { entry: e }), + hash_map::Entry::Occupied(e) => Entry::Occupied(OccupiedEntry { + entry: e, + type_: PhantomData, + }), + hash_map::Entry::Vacant(e) => Entry::Vacant(VacantEntry { + entry: e, + type_: PhantomData, + }), } } /// Returns the number of items in the collection. - pub fn len(&self) -> uint { + #[inline] + pub fn len(&self) -> usize { self.data.len() } /// Returns true if there are no items in the collection. + #[inline] pub fn is_empty(&self) -> bool { self.data.is_empty() } - /// Removes all items from the collection. + /// Clears the map, returning all items as an iterator. + /// + /// Iterator element type is `Box`. + /// + /// Keeps the allocated memory for reuse. + #[inline] + pub fn drain(&mut self) -> Drain { + Drain { + inner: self.data.drain(), + } + } + + /// Removes all items from the collection. Keeps the allocated memory for reuse. + #[inline] pub fn clear(&mut self) { self.data.clear(); } } -/// A view into a single occupied location in a HashMap +/// A view into a single occupied location in an AnyMap pub struct OccupiedEntry<'a, V: 'a> { entry: hash_map::OccupiedEntry<'a, TypeId, Box>, + type_: PhantomData, } -/// A view into a single empty location in a HashMap +/// A view into a single empty location in an AnyMap pub struct VacantEntry<'a, V: 'a> { entry: hash_map::VacantEntry<'a, TypeId, Box>, + type_: PhantomData, } -/// A view into a single location in a map, which may be vacant or occupied +/// A view into a single location in an AnyMap, which may be vacant or occupied pub enum Entry<'a, V: 'a> { /// An occupied Entry Occupied(OccupiedEntry<'a, V>), @@ -227,6 +309,16 @@ pub enum Entry<'a, V: 'a> { Vacant(VacantEntry<'a, V>), } +impl<'a, V: 'static + Clone> Entry<'a, V> { + /// Returns a mutable reference to the entry if occupied, or the VacantEntry if vacant + pub fn get(self) -> Result<&'a mut V, VacantEntry<'a, V>> { + match self { + Entry::Occupied(entry) => Ok(entry.into_mut()), + Entry::Vacant(entry) => Err(entry), + } + } +} + impl<'a, V: 'static> OccupiedEntry<'a, V> { /// Gets a reference to the value in the entry pub fn get(&self) -> &V { @@ -239,36 +331,105 @@ impl<'a, V: 'static> OccupiedEntry<'a, V> { } /// Converts the OccupiedEntry into a mutable reference to the value in the entry - /// with a lifetime bound to the map itself + /// with a lifetime bound to the collection itself pub fn into_mut(self) -> &'a mut V { unsafe { self.entry.into_mut().downcast_mut_unchecked() } } /// Sets the value of the entry, and returns the entry's old value - pub fn set(&mut self, value: V) -> V { - unsafe { *self.entry.set(box value as Box).downcast_unchecked() } + pub fn insert(&mut self, value: V) -> V { + unsafe { *self.entry.insert(Box::new(value) as Box).downcast_unchecked() } } /// Takes the value out of the entry, and returns it - pub fn take(self) -> V { - unsafe { *self.entry.take().downcast_unchecked() } + pub fn remove(self) -> V { + unsafe { *self.entry.remove().downcast_unchecked() } } } impl<'a, V: 'static> VacantEntry<'a, V> { /// Sets the value of the entry with the VacantEntry's key, /// and returns a mutable reference to it - pub fn set(self, value: V) -> &'a mut V { - unsafe { self.entry.set(box value as Box).downcast_mut_unchecked() } + pub fn insert(self, value: V) -> &'a mut V { + unsafe { self.entry.insert(Box::new(value) as Box).downcast_mut_unchecked() } + } +} + +/// `AnyMap` iterator. +#[derive(Clone)] +pub struct Iter<'a> { + inner: hash_map::Iter<'a, TypeId, Box>, +} + +/// `AnyMap` mutable references iterator. +pub struct IterMut<'a> { + inner: hash_map::IterMut<'a, TypeId, Box>, +} + +/// `AnyMap` draining iterator. +pub struct Drain<'a> { + inner: hash_map::Drain<'a, TypeId, Box>, +} + +/// `AnyMap` move iterator. +pub struct IntoIter { + inner: hash_map::IntoIter>, +} + +impl<'a> Iterator for Iter<'a> { + type Item = &'a Any; + + #[inline] + fn next(&mut self) -> Option<&'a Any> { + self.inner.next().map(|item| &**item.1) + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } +} + +impl<'a> Iterator for IterMut<'a> { + type Item = &'a mut Any; + + #[inline] + fn next(&mut self) -> Option<&'a mut Any> { + self.inner.next().map(|item| &mut **item.1) + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } +} + +impl<'a> Iterator for Drain<'a> { + type Item = Box; + + #[inline] + fn next(&mut self) -> Option> { + self.inner.next().map(|item| item.1) + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } +} + +impl Iterator for IntoIter { + type Item = Box; + + #[inline] + fn next(&mut self) -> Option> { + self.inner.next().map(|item| item.1) } + + #[inline] + fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } } #[bench] fn bench_insertion(b: &mut ::test::Bencher) { b.iter(|| { let mut data = AnyMap::new(); - for _ in range(0u, 100) { - let _ = data.insert(42i); + for _ in range(0, 100) { + let _ = data.insert(42i32); } }) } @@ -277,8 +438,8 @@ fn bench_insertion(b: &mut ::test::Bencher) { fn bench_get_missing(b: &mut ::test::Bencher) { b.iter(|| { let data = AnyMap::new(); - for _ in range(0u, 100) { - assert_eq!(data.get(), None::<&int>); + for _ in range(0, 100) { + assert_eq!(data.get(), None::<&i32>); } }) } @@ -287,23 +448,23 @@ fn bench_get_missing(b: &mut ::test::Bencher) { fn bench_get_present(b: &mut ::test::Bencher) { b.iter(|| { let mut data = AnyMap::new(); - let _ = data.insert(42i); + let _ = data.insert(42i32); // These inner loops are a feeble attempt to drown the other factors. - for _ in range(0u, 100) { - assert_eq!(data.get(), Some(&42i)); + for _ in range(0, 100) { + assert_eq!(data.get(), Some(&42i32)); } }) } #[test] fn test_entry() { - #[deriving(Show, PartialEq)] struct A(int); - #[deriving(Show, PartialEq)] struct B(int); - #[deriving(Show, PartialEq)] struct C(int); - #[deriving(Show, PartialEq)] struct D(int); - #[deriving(Show, PartialEq)] struct E(int); - #[deriving(Show, PartialEq)] struct F(int); - #[deriving(Show, PartialEq)] struct J(int); + #[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); @@ -315,10 +476,10 @@ fn test_entry() { // Existing key (insert) match map.entry::() { - Vacant(_) => unreachable!(), - Occupied(mut view) => { + Entry::Vacant(_) => unreachable!(), + Entry::Occupied(mut view) => { assert_eq!(view.get(), &A(10)); - assert_eq!(view.set(A(100)), A(10)); + assert_eq!(view.insert(A(100)), A(10)); } } assert_eq!(map.get::().unwrap(), &A(100)); @@ -327,8 +488,8 @@ fn test_entry() { // Existing key (update) match map.entry::() { - Vacant(_) => unreachable!(), - Occupied(mut view) => { + Entry::Vacant(_) => unreachable!(), + Entry::Occupied(mut view) => { let v = view.get_mut(); let new_v = B(v.0 * 10); *v = new_v; @@ -338,11 +499,11 @@ fn test_entry() { assert_eq!(map.len(), 6); - // Existing key (take) + // Existing key (remove) match map.entry::() { - Vacant(_) => unreachable!(), - Occupied(view) => { - assert_eq!(view.take(), C(30)); + Entry::Vacant(_) => unreachable!(), + Entry::Occupied(view) => { + assert_eq!(view.remove(), C(30)); } } assert_eq!(map.get::(), None); @@ -351,9 +512,9 @@ fn test_entry() { // Inexistent key (insert) match map.entry::() { - Occupied(_) => unreachable!(), - Vacant(view) => { - assert_eq!(*view.set(J(1000)), J(1000)); + Entry::Occupied(_) => unreachable!(), + Entry::Vacant(view) => { + assert_eq!(*view.insert(J(1000)), J(1000)); } } assert_eq!(map.get::().unwrap(), &J(1000));