anymap-0.12.1/.gitignore00006440000000000000000000000035130026734460013241 0ustar0000000000000000TAGS doc/ target/ Cargo.lock anymap-0.12.1/.travis.yml00006440000000000000000000001105130026734460013361 0ustar0000000000000000language: rust rust: - nightly - beta - stable env: global: - secure: nR+DJRUQ9v03nNZMpMu1tGKLKBAqdQsTIAr8ffdl+DUEh3b2jvQ+vLLNFLPjsloqhoOXo7cWO7qVpiE4ZOq2lNDURQjdiZGFjh/Y5+xKy2BqFdV7qQ1JoBzsMyx28tQTYz0mtBsACiCYKKb+ddNX5hpwrsjp8cS7htZktA5kbiU= script: - if [[ "$(rustc --version)" =~ -(dev|nightly) ]]; then cargo test --features bench; else ! cargo test --features bench; fi - cargo test - cargo doc after_script: - ln -s target/doc doc - curl -v http://www.rust-ci.org/artifacts/put?t=$RUSTCI_TOKEN > ./upload-docs - cat ./upload-docs - sh ./upload-docs anymap-0.12.1/Cargo.toml00006440000000000000000000001541130404026370013176 0ustar0000000000000000# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "anymap" version = "0.12.1" authors = ["Chris Morgan "] description = "A safe and convenient store for one value of each type" readme = "README.md" keywords = ["container", "data-structure", "map"] license = "MIT/Apache-2.0" repository = "https://github.com/chris-morgan/anymap" [features] bench = [] anymap-0.12.1/Cargo.toml.orig00006440000000000000000000000735130404026370014141 0ustar0000000000000000[package] name = "anymap" version = "0.12.1" authors = ["Chris Morgan "] description = "A safe and convenient store for one value of each type" #documentation = "http://www.rust-ci.org/chris-morgan/anymap/doc/anymap/index.html" #homepage = "https://github.com/chris-morgan/anymap" repository = "https://github.com/chris-morgan/anymap" readme = "README.md" keywords = ["container", "data-structure", "map"] license = "MIT/Apache-2.0" [features] bench = [] anymap-0.12.1/COPYRIGHT00006440000000000000000000000237130026734460012550 0ustar0000000000000000This project is dual-licensed under the terms of the MIT and Apache (version 2.0) licenses. Copyright (c) 2014 Chris Morgan and the Teepee project developers anymap-0.12.1/LICENSE-APACHE00006440000000000000000000025137130026734460013207 0ustar0000000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. anymap-0.12.1/LICENSE-MIT00006440000000000000000000002102130026734460012702 0ustar0000000000000000Copyright (c) 2014 Chris Morgan and the Teepee project developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. anymap-0.12.1/README.md00006440000000000000000000004141130026734460012532 0ustar0000000000000000``AnyMap``, a safe and convenient store for one value of each type ================================================================== [![Build Status](https://travis-ci.org/chris-morgan/anymap.svg?branch=master)](https://travis-ci.org/chris-morgan/anymap) If you’re familiar with Go and Go web frameworks, you may have come across the common “environment” pattern for storing data related to the request. It’s typically something like ``map[string]interface{}`` and is accessed with arbitrary strings which may clash and type assertions which are a little unwieldy and must be used very carefully. (Personally I would consider that it is just *asking* for things to blow up in your face.) In a language like Go, lacking in generics, this is the best that can be done; such a thing cannot possibly be made safe without generics. As another example of such an interface, JavaScript objects are exactly the same—a mapping of string keys to arbitrary values. (There it is actually *more* dangerous, because methods and fields/attributes/properties are on the same plane.) Fortunately, we can do better than these things in Rust. Our type system is quite equal to easy, robust expression of such problems. The ``AnyMap`` type is a friendly wrapper around a ``HashMap>``, exposing a nice, easy typed interface, perfectly safe and absolutely robust. What this means is that in an ``AnyMap`` you may store zero or one values for every type. Instructions ------------ Cargo all the way: it is `anymap` on crates.io. For users of the nightly instead of the beta of rustc there are a couple of things behind the `unstable` feature like a `drain` method on the `RawAnyMap` and a more efficient hashing technique which makes lookup in the map a tad faster. Author ------ [Chris Morgan](http://chrismorgan.info/) ([chris-morgan](https://github.com/chris-morgan)) is the primary author and maintainer of AnyMap. License ------- This library is distributed under similar terms to Rust: dual licensed under the MIT license and the Apache license (version 2.0). See LICENSE-APACHE, LICENSE-MIT, and COPYRIGHT for details. anymap-0.12.1/src/any.rs00006440000000000000000000012235130026734460013202 0ustar0000000000000000//! The different types of `Any` for use in a map. //! //! This stuff is all based on `std::any`, but goes a little further, with `CloneAny` being a //! cloneable `Any` and with the `Send` and `Sync` bounds possible on both `Any` and `CloneAny`. use std::fmt; use std::any::Any as StdAny; #[doc(hidden)] pub trait CloneToAny { /// Clone `self` into a new `Box` object. fn clone_to_any(&self) -> Box; /// Clone `self` into a new `Box` object. fn clone_to_any_send(&self) -> Box where Self: Send; /// Clone `self` into a new `Box` object. fn clone_to_any_sync(&self) -> Box where Self: Sync; /// Clone `self` into a new `Box` object. fn clone_to_any_send_sync(&self) -> Box where Self: Send + Sync; } impl CloneToAny for T { #[inline] fn clone_to_any(&self) -> Box { Box::new(self.clone()) } #[inline] fn clone_to_any_send(&self) -> Box where Self: Send { Box::new(self.clone()) } #[inline] fn clone_to_any_sync(&self) -> Box where Self: Sync { Box::new(self.clone()) } #[inline] fn clone_to_any_send_sync(&self) -> Box where Self: Send + Sync { Box::new(self.clone()) } } macro_rules! define { (CloneAny) => { /// A type to emulate dynamic typing. /// /// Every type with no non-`'static` references implements `Any`. define!(CloneAny remainder); }; (Any) => { /// A type to emulate dynamic typing with cloning. /// /// Every type with no non-`'static` references that implements `Clone` implements `Any`. define!(Any remainder); }; ($t:ident remainder) => { /// See the [`std::any` documentation](https://doc.rust-lang.org/std/any/index.html) for /// more details on `Any` in general. /// /// This trait is not `std::any::Any` but rather a type extending that for this library’s /// purposes so that it can be combined with marker traits like /// Send and /// Sync. /// define!($t trait); }; (CloneAny trait) => { /// See also [`Any`](trait.Any.html) for a version without the `Clone` requirement. pub trait CloneAny: Any + CloneToAny { } impl CloneAny for T { } }; (Any trait) => { /// See also [`CloneAny`](trait.CloneAny.html) for a cloneable version of this trait. pub trait Any: StdAny { } impl Any for T { } }; } macro_rules! impl_clone { ($t:ty, $method:ident) => { impl Clone for Box<$t> { #[inline] fn clone(&self) -> Box<$t> { (**self).$method() } } } } #[allow(missing_docs)] // Bogus warning (it’s not public outside the crate), ☹ pub trait UncheckedAnyExt: Any { unsafe fn downcast_ref_unchecked(&self) -> &T; unsafe fn downcast_mut_unchecked(&mut self) -> &mut T; unsafe fn downcast_unchecked(self: Box) -> Box; } #[doc(hidden)] /// A trait for the conversion of an object into a boxed trait object. pub trait IntoBox: Any { /// Convert self into the appropriate boxed form. fn into_box(self) -> Box; } macro_rules! implement { ($base:ident, $(+ $bounds:ident)*) => { impl fmt::Debug for $base $(+ $bounds)* { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.pad(stringify!($base $(+ $bounds)*)) } } impl UncheckedAnyExt for $base $(+ $bounds)* { #[inline] unsafe fn downcast_ref_unchecked(&self) -> &T { &*(self as *const Self as *const T) } #[inline] unsafe fn downcast_mut_unchecked(&mut self) -> &mut T { &mut *(self as *mut Self as *mut T) } #[inline] unsafe fn downcast_unchecked(self: Box) -> Box { Box::from_raw(Box::into_raw(self) as *mut T) } } impl IntoBox<$base $(+ $bounds)*> for T { #[inline] fn into_box(self) -> Box<$base $(+ $bounds)*> { Box::new(self) } } } } define!(Any); implement!(Any,); implement!(Any, + Send); implement!(Any, + Sync); implement!(Any, + Send + Sync); implement!(CloneAny,); implement!(CloneAny, + Send); implement!(CloneAny, + Sync); implement!(CloneAny, + Send + Sync); define!(CloneAny); impl_clone!(CloneAny, clone_to_any); impl_clone!((CloneAny + Send), clone_to_any_send); impl_clone!((CloneAny + Sync), clone_to_any_sync); impl_clone!((CloneAny + Send + Sync), clone_to_any_send_sync); anymap-0.12.1/src/lib.rs00006440000000000000000000043170130026734460013163 0ustar0000000000000000//! This crate provides the `AnyMap` type, a safe and convenient store for one value of each type. #![cfg_attr(all(feature = "bench", test), feature(test))] #![warn(missing_docs, unused_results)] #[cfg(all(feature = "bench", test))] extern crate test; use std::any::TypeId; use std::marker::PhantomData; use raw::RawMap; use any::{UncheckedAnyExt, IntoBox, Any}; macro_rules! impl_common_methods { ( field: $t:ident.$field:ident; new() => $new:expr; with_capacity($with_capacity_arg:ident) => $with_capacity:expr; ) => { impl $t { /// Create an empty collection. #[inline] pub fn new() -> $t { $t { $field: $new, } } /// Creates an empty collection with the given initial capacity. #[inline] pub fn with_capacity($with_capacity_arg: usize) -> $t { $t { $field: $with_capacity, } } /// Returns the number of elements the collection can hold without reallocating. #[inline] pub fn capacity(&self) -> usize { self.$field.capacity() } /// Reserves capacity for at least `additional` more elements to be inserted /// in the collection. 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.$field.reserve(additional) } /// 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.$field.shrink_to_fit() } /// Returns the number of items in the collection. #[inline] pub fn len(&self) -> usize { self.$field.len() } /// Returns true if there are no items in the collection. #[inline] pub fn is_empty(&self) -> bool { self.$field.is_empty() } /// Removes all items from the collection. Keeps the allocated memory for reuse. #[inline] pub fn clear(&mut self) { self.$field.clear() } } } } 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`) to add those bounds. /// /// ```rust /// # use anymap::AnyMap; /// let mut data = AnyMap::new(); /// assert_eq!(data.get(), None::<&i32>); /// data.insert(42i32); /// assert_eq!(data.get(), Some(&42i32)); /// data.remove::(); /// assert_eq!(data.get::(), None); /// /// #[derive(Clone, PartialEq, Debug)] /// struct Foo { /// str: String, /// } /// /// assert_eq!(data.get::(), None); /// 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, "foot"); /// ``` /// /// Values containing non-static references are not permitted. #[derive(Debug)] 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 { #[inline] 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: Map.raw; new() => RawMap::new(); with_capacity(capacity) => RawMap::with_capacity(capacity); } impl Map { /// Returns a reference to the value stored in the collection for the type `T`, if it exists. #[inline] 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. #[inline] pub fn get_mut>(&mut self) -> Option<&mut T> { self.raw.get_mut(&TypeId::of::()) .map(|any| unsafe { any.downcast_mut_unchecked::() }) } /// 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>(&mut self, value: T) -> Option { unsafe { 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. #[inline] 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 { self.raw.contains_key(&TypeId::of::()) } /// Gets the entry for the given type in the collection for in-place manipulation #[inline] pub fn entry>(&mut self) -> Entry { match self.raw.entry(TypeId::of::()) { raw::Entry::Occupied(e) => Entry::Occupied(OccupiedEntry { inner: e, type_: PhantomData, }), raw::Entry::Vacant(e) => Entry::Vacant(VacantEntry { inner: e, type_: PhantomData, }), } } } impl AsRef> for Map { #[inline] fn as_ref(&self) -> &RawMap { &self.raw } } impl AsMut> for Map { #[inline] fn as_mut(&mut self) -> &mut RawMap { &mut self.raw } } impl Into> for Map { #[inline] fn into(self) -> RawMap { self.raw } } /// 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 `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 `Map`, which may be vacant or occupied. pub enum Entry<'a, A: ?Sized + UncheckedAnyExt, V: 'a> { /// An occupied Entry Occupied(OccupiedEntry<'a, A, V>), /// A vacant Entry Vacant(VacantEntry<'a, A, V>), } impl<'a, A: ?Sized + UncheckedAnyExt, V: IntoBox> 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(), Entry::Vacant(inner) => inner.insert(default), } } /// 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 V>(self, default: F) -> &'a mut V { match self { Entry::Occupied(inner) => inner.into_mut(), Entry::Vacant(inner) => inner.insert(default()), } } } impl<'a, A: ?Sized + UncheckedAnyExt, V: IntoBox> 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() } } } 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 #[inline] pub fn insert(self, value: V) -> &'a mut V { unsafe { self.inner.insert(value.into_box()).downcast_mut_unchecked() } } } #[cfg(all(feature = "bench", test))] mod bench { use AnyMap; use test::Bencher; use test::black_box; #[bench] fn insertion(b: &mut Bencher) { b.iter(|| { let mut data = AnyMap::new(); for _ in 0..100 { let _ = data.insert(42); } }) } #[bench] fn get_missing(b: &mut Bencher) { b.iter(|| { let data = AnyMap::new(); for _ in 0..100 { assert_eq!(data.get(), None::<&i32>); } }) } #[bench] fn get_present(b: &mut 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)); } }) } macro_rules! big_benchmarks { ($name:ident, $($T:ident)*) => ( #[bench] fn $name(b: &mut Bencher) { $( struct $T(&'static str); )* b.iter(|| { let mut data = AnyMap::new(); $( let _ = black_box(data.insert($T(stringify!($T)))); )* $( let _ = black_box(data.get::<$T>()); )* }) } ); } // Caution: if the macro does too much (e.g. assertions) this goes from being slow to being // *really* slow (like add a minute for each assertion on it) and memory-hungry (like, adding // several hundred megabytes to the peak for each assertion). big_benchmarks! { insert_and_get_on_260_types, A0 B0 C0 D0 E0 F0 G0 H0 I0 J0 K0 L0 M0 N0 O0 P0 Q0 R0 S0 T0 U0 V0 W0 X0 Y0 Z0 A1 B1 C1 D1 E1 F1 G1 H1 I1 J1 K1 L1 M1 N1 O1 P1 Q1 R1 S1 T1 U1 V1 W1 X1 Y1 Z1 A2 B2 C2 D2 E2 F2 G2 H2 I2 J2 K2 L2 M2 N2 O2 P2 Q2 R2 S2 T2 U2 V2 W2 X2 Y2 Z2 A3 B3 C3 D3 E3 F3 G3 H3 I3 J3 K3 L3 M3 N3 O3 P3 Q3 R3 S3 T3 U3 V3 W3 X3 Y3 Z3 A4 B4 C4 D4 E4 F4 G4 H4 I4 J4 K4 L4 M4 N4 O4 P4 Q4 R4 S4 T4 U4 V4 W4 X4 Y4 Z4 A5 B5 C5 D5 E5 F5 G5 H5 I5 J5 K5 L5 M5 N5 O5 P5 Q5 R5 S5 T5 U5 V5 W5 X5 Y5 Z5 A6 B6 C6 D6 E6 F6 G6 H6 I6 J6 K6 L6 M6 N6 O6 P6 Q6 R6 S6 T6 U6 V6 W6 X6 Y6 Z6 A7 B7 C7 D7 E7 F7 G7 H7 I7 J7 K7 L7 M7 N7 O7 P7 Q7 R7 S7 T7 U7 V7 W7 X7 Y7 Z7 A8 B8 C8 D8 E8 F8 G8 H8 I8 J8 K8 L8 M8 N8 O8 P8 Q8 R8 S8 T8 U8 V8 W8 X8 Y8 Z8 A9 B9 C9 D9 E9 F9 G9 H9 I9 J9 K9 L9 M9 N9 O9 P9 Q9 R9 S9 T9 U9 V9 W9 X9 Y9 Z9 } big_benchmarks! { insert_and_get_on_26_types, A B C D E F G H I J K L M N O P Q R S T U V W X Y Z } } #[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); 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::() { 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::().unwrap(), &A(100)); assert_eq!(map.len(), 6); // Existing key (update) match map.entry::() { 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); // Existing key (remove) match map.entry::() { Entry::Vacant(_) => unreachable!(), Entry::Occupied(view) => { assert_eq!(view.remove(), C(30)); } } assert_eq!(map.get::(), None); assert_eq!(map.len(), 5); // Inexistent key (insert) match map.entry::() { Entry::Occupied(_) => unreachable!(), Entry::Vacant(view) => { assert_eq!(*view.insert(J(1000)), J(1000)); } } assert_eq!(map.get::().unwrap(), &J(1000)); assert_eq!(map.len(), 6); // Entry.or_insert on existing key map.entry::().or_insert(B(71)).0 += 1; assert_eq!(map.get::().unwrap(), &B(201)); assert_eq!(map.len(), 6); // Entry.or_insert on nonexisting key map.entry::().or_insert(C(300)).0 += 1; assert_eq!(map.get::().unwrap(), &C(301)); assert_eq!(map.len(), 7); } } } test_entry!(test_entry_any, AnyMap); test_entry!(test_entry_cloneany, Map); #[test] fn test_clone() { let mut map: Map = 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::(), Some(&A(1))); assert_eq!(map2.get::(), Some(&B(2))); assert_eq!(map2.get::(), None); assert_eq!(map2.get::(), Some(&D(3))); assert_eq!(map2.get::(), Some(&E(4))); 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::>(); } } anymap-0.12.1/src/raw.rs00006440000000000000000000030101130026750150013166 0ustar0000000000000000//! The raw form of a `Map`, allowing untyped access. //! //! All relevant details are in the `RawMap` struct. use std::any::TypeId; use std::borrow::Borrow; use std::collections::hash_map::{self, HashMap}; use std::hash::Hash; use std::hash::{Hasher, BuildHasherDefault}; #[cfg(test)] use std::mem; use std::ops::{Index, IndexMut}; use std::ptr; use any::{Any, UncheckedAnyExt}; #[derive(Default)] struct TypeIdHasher { value: u64, } impl Hasher for TypeIdHasher { #[inline] fn write(&mut self, bytes: &[u8]) { // This expects to receive one and exactly one 64-bit value debug_assert!(bytes.len() == 8); unsafe { ptr::copy_nonoverlapping(&bytes[0] as *const u8 as *const u64, &mut self.value, 1) } } #[inline] fn finish(&self) -> u64 { self.value } } #[test] fn type_id_hasher() { fn verify_hashing_with(type_id: TypeId) { let mut hasher = TypeIdHasher::default(); type_id.hash(&mut hasher); assert_eq!(hasher.finish(), unsafe { mem::transmute::(type_id) }); } // Pick a variety of types, just to demonstrate it’s all sane. Normal, zero-sized, unsized, &c. verify_hashing_with(TypeId::of::()); verify_hashing_with(TypeId::of::<()>()); verify_hashing_with(TypeId::of::()); verify_hashing_with(TypeId::of::<&str>()); verify_hashing_with(TypeId::of::>()); } /// The raw, underlying form of a `Map`. /// /// At its essence, this is a wrapper around `HashMap>`, with the portions that /// would be memory-unsafe removed or marked unsafe. Normal people are expected to use the safe /// `Map` interface instead, but there is the occasional use for this such as iteration over the /// contents of an `Map`. However, because you will then be dealing with `Any` trait objects, it /// doesn’t tend to be so very useful. Still, if you need it, it’s here. #[derive(Debug)] pub struct RawMap { inner: HashMap, BuildHasherDefault>, } // #[derive(Clone)] would want A to implement Clone, but in reality it’s only Box that can. impl Clone for RawMap where Box: Clone { #[inline] fn clone(&self) -> RawMap { RawMap { inner: self.inner.clone(), } } } impl Default for RawMap { #[inline] fn default() -> RawMap { RawMap::new() } } impl_common_methods! { field: RawMap.inner; new() => HashMap::with_hasher(Default::default()); with_capacity(capacity) => HashMap::with_capacity_and_hasher(capacity, Default::default()); } /// `RawMap` iterator. #[derive(Clone)] pub struct Iter<'a, A: ?Sized + UncheckedAnyExt> { inner: hash_map::Iter<'a, TypeId, Box>, } impl<'a, A: ?Sized + UncheckedAnyExt> Iterator for Iter<'a, A> { type Item = &'a A; #[inline] fn next(&mut self) -> Option<&'a A> { self.inner.next().map(|x| &**x.1) } #[inline] fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } } impl<'a, A: ?Sized + UncheckedAnyExt> ExactSizeIterator for Iter<'a, A> { #[inline] fn len(&self) -> usize { self.inner.len() } } /// `RawMap` mutable iterator. pub struct IterMut<'a, A: ?Sized + UncheckedAnyExt> { inner: hash_map::IterMut<'a, TypeId, Box>, } impl<'a, A: ?Sized + UncheckedAnyExt> Iterator for IterMut<'a, A> { type Item = &'a mut A; #[inline] fn next(&mut self) -> Option<&'a mut A> { self.inner.next().map(|x| &mut **x.1) } #[inline] fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } } impl<'a, A: ?Sized + UncheckedAnyExt> ExactSizeIterator for IterMut<'a, A> { #[inline] fn len(&self) -> usize { self.inner.len() } } /// `RawMap` move iterator. pub struct IntoIter { inner: hash_map::IntoIter>, } impl Iterator for IntoIter { type Item = Box; #[inline] fn next(&mut self) -> Option> { self.inner.next().map(|x| x.1) } #[inline] fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } } impl ExactSizeIterator for IntoIter { #[inline] fn len(&self) -> usize { self.inner.len() } } /// `RawMap` drain iterator. pub struct Drain<'a, A: ?Sized + UncheckedAnyExt> { inner: hash_map::Drain<'a, TypeId, Box>, } impl<'a, A: ?Sized + UncheckedAnyExt> Iterator for Drain<'a, A> { type Item = Box; #[inline] fn next(&mut self) -> Option> { self.inner.next().map(|x| x.1) } #[inline] fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } } impl<'a, A: ?Sized + UncheckedAnyExt> ExactSizeIterator for Drain<'a, A> { #[inline] fn len(&self) -> usize { self.inner.len() } } impl RawMap { /// An iterator visiting all entries in arbitrary order. /// /// Iterator element type is `&Any`. #[inline] pub fn iter(&self) -> Iter { Iter { inner: self.inner.iter(), } } /// An iterator visiting all entries in arbitrary order. /// /// Iterator element type is `&mut Any`. #[inline] pub fn iter_mut(&mut self) -> IterMut { IterMut { inner: self.inner.iter_mut(), } } /// 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.inner.drain(), } } /// Gets the entry for the given type in the collection for in-place manipulation. #[inline] pub fn entry(&mut self, key: TypeId) -> Entry { match self.inner.entry(key) { hash_map::Entry::Occupied(e) => Entry::Occupied(OccupiedEntry { inner: e, }), hash_map::Entry::Vacant(e) => Entry::Vacant(VacantEntry { inner: e, }), } } /// Returns a reference to the value corresponding to the key. /// /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed /// form *must* match those for the key type. #[inline] pub fn get(&self, k: &Q) -> Option<&A> where TypeId: Borrow, Q: Hash + Eq { self.inner.get(k).map(|x| &**x) } /// Returns true if the map contains a value for the specified key. /// /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed /// form *must* match those for the key type. #[inline] pub fn contains_key(&self, k: &Q) -> bool where TypeId: Borrow, Q: Hash + Eq { self.inner.contains_key(k) } /// Returns a mutable reference to the value corresponding to the key. /// /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed /// form *must* match those for the key type. #[inline] pub fn get_mut(&mut self, k: &Q) -> Option<&mut A> where TypeId: Borrow, Q: Hash + Eq { self.inner.get_mut(k).map(|x| &mut **x) } /// Inserts a key-value pair from the map. If the key already had a value present in the map, /// that value is returned. Otherwise, None is returned. /// /// It is the caller’s responsibility to ensure that the key corresponds with the type ID of /// the value. If they do not, memory safety may be violated. #[inline] pub unsafe fn insert(&mut self, key: TypeId, value: Box) -> Option> { self.inner.insert(key, value) } /// Removes a key from the map, returning the value at the key if the key was previously in the /// map. /// /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed /// form *must* match those for the key type. #[inline] pub fn remove(&mut self, k: &Q) -> Option> where TypeId: Borrow, Q: Hash + Eq { self.inner.remove(k) } } impl Index for RawMap where TypeId: Borrow, Q: Eq + Hash { type Output = A; #[inline] fn index(&self, index: Q) -> &A { self.get(&index).expect("no entry found for key") } } impl IndexMut for RawMap where TypeId: Borrow, Q: Eq + Hash { #[inline] fn index_mut(&mut self, index: Q) -> &mut A { self.get_mut(&index).expect("no entry found for key") } } impl IntoIterator for RawMap { type Item = Box; type IntoIter = IntoIter; #[inline] fn into_iter(self) -> IntoIter { IntoIter { inner: self.inner.into_iter(), } } } /// A view into a single occupied location in a `RawMap`. pub struct OccupiedEntry<'a, A: ?Sized + UncheckedAnyExt> { inner: hash_map::OccupiedEntry<'a, TypeId, Box>, } /// A view into a single empty location in a `RawMap`. pub struct VacantEntry<'a, A: ?Sized + UncheckedAnyExt> { inner: hash_map::VacantEntry<'a, TypeId, Box>, } /// A view into a single location in a `RawMap`, which may be vacant or occupied. pub enum Entry<'a, A: ?Sized + UncheckedAnyExt> { /// An occupied Entry Occupied(OccupiedEntry<'a, A>), /// A vacant Entry Vacant(VacantEntry<'a, A>), } impl<'a, A: ?Sized + UncheckedAnyExt> Entry<'a, A> { /// Ensures a value is in the entry by inserting the default if empty, and returns /// a mutable reference to the value in the entry. /// /// It is the caller’s responsibility to ensure that the key of the entry corresponds with /// the type ID of `value`. If they do not, memory safety may be violated. #[inline] pub unsafe fn or_insert(self, default: Box) -> &'a mut A { match self { Entry::Occupied(inner) => inner.into_mut(), Entry::Vacant(inner) => inner.insert(default), } } /// 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. /// /// It is the caller’s responsibility to ensure that the key of the entry corresponds with /// the type ID of `value`. If they do not, memory safety may be violated. #[inline] pub unsafe fn or_insert_with Box>(self, default: F) -> &'a mut A { match self { Entry::Occupied(inner) => inner.into_mut(), Entry::Vacant(inner) => inner.insert(default()), } } } impl<'a, A: ?Sized + UncheckedAnyExt> OccupiedEntry<'a, A> { /// Gets a reference to the value in the entry. #[inline] pub fn get(&self) -> &A { &**self.inner.get() } /// Gets a mutable reference to the value in the entry. #[inline] pub fn get_mut(&mut self) -> &mut A { &mut **self.inner.get_mut() } /// 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 A { &mut **self.inner.into_mut() } /// Sets the value of the entry, and returns the entry's old value. /// /// It is the caller’s responsibility to ensure that the key of the entry corresponds with /// the type ID of `value`. If they do not, memory safety may be violated. #[inline] pub unsafe fn insert(&mut self, value: Box) -> Box { self.inner.insert(value) } /// Takes the value out of the entry, and returns it. #[inline] pub fn remove(self) -> Box { self.inner.remove() } } impl<'a, A: ?Sized + UncheckedAnyExt> VacantEntry<'a, A> { /// Sets the value of the entry with the VacantEntry's key, /// and returns a mutable reference to it /// /// It is the caller’s responsibility to ensure that the key of the entry corresponds with /// the type ID of `value`. If they do not, memory safety may be violated. #[inline] pub unsafe fn insert(self, value: Box) -> &'a mut A { &mut **self.inner.insert(value) } }