multimap-0.8.3/.cargo_vcs_info.json0000644000000001120000000000000126650ustar { "git": { "sha1": "96ba7c3ec674777cf40efb86fd1315a3d9cf6b25" } } multimap-0.8.3/Cargo.toml0000644000000017630000000000000107000ustar # 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 = "multimap" version = "0.8.3" authors = ["Håvar Nøvik "] exclude = [".travis.yml", ".gitignore"] description = "A multimap implementation." documentation = "https://docs.rs/multimap/" readme = "README.md" license = "MIT/Apache-2.0" repository = "https://github.com/havarnov/multimap" [dependencies.serde] version = "~1.0" optional = true [dev-dependencies.serde_test] version = "~1.0" [features] default = ["serde_impl"] serde_impl = ["serde"] multimap-0.8.3/Cargo.toml.orig000064400000000000000000000007620000000000000143350ustar 00000000000000[package] name = "multimap" version = "0.8.3" description = "A multimap implementation." readme = "README.md" repository = "https://github.com/havarnov/multimap" license = "MIT/Apache-2.0" authors = ["Håvar Nøvik "] documentation = "https://docs.rs/multimap/" exclude = [ ".travis.yml", ".gitignore", ] [features] serde_impl = ["serde"] default = ["serde_impl"] [dependencies] serde = { version = "~1.0", optional = true } [dev-dependencies] serde_test = "~1.0" multimap-0.8.3/LICENSE-APACHE000064400000000000000000000251370000000000000133750ustar 00000000000000 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. multimap-0.8.3/LICENSE-MIT000064400000000000000000000020470000000000000131000ustar 00000000000000Copyright (c) 2016 multimap 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. multimap-0.8.3/README.md000064400000000000000000000033740000000000000127270ustar 00000000000000[![Travis Build Status](https://travis-ci.org/havarnov/multimap.svg?branch=master)](https://travis-ci.org/havarnov/multimap) [![crates.io](http://meritbadge.herokuapp.com/multimap)](https://crates.io/crates/multimap) [![docs.rs](https://docs.rs/multimap/badge.svg)](https://docs.rs/multimap/) # Multimap implementation for Rust This is a multimap implementation for Rust. Implemented as a thin wrapper around std::collections::HashMap. ## Example ````rust extern crate multimap; use multimap::MultiMap; fn main () { let mut map = MultiMap::new(); map.insert("key1", 42); map.insert("key1", 1337); map.insert("key2", 2332); assert_eq!(map["key1"], 42); assert_eq!(map.get("key1"), Some(&42)); assert_eq!(map.get_vec("key1"), Some(&vec![42, 1337])); } ```` ## Changelog ### 0.8.3 * multimap! marco fixes; allow trailing comma, naming hygiene and create with enough capacity for all elements. ### 0.8.2 * Added ```#![forbid(unsafe_code)]```. ### 0.8.1 * Fixed wrong link to documentation in Cargo.toml. ### 0.8.0 * Added ```MultiMap::insert_many``` * Added ```MultiMap::insert_many_from_slice``` ### 0.7.0 * Added possibility to replace the default hasher for the underlying ```HashMap```. * Fix build warning by removing an unnecessary ```mut```. ## License Licensed under either of * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. multimap-0.8.3/src/entry.rs000064400000000000000000000100720000000000000137370ustar 00000000000000// Copyright (c) 2016 multimap developers // // Licensed under the Apache License, Version 2.0 // or the MIT // license , at your // option. All files in the project carrying such notice may not be copied, // modified, or distributed except according to those terms. use std::collections::hash_map::OccupiedEntry as HashMapOccupiedEntry; use std::collections::hash_map::VacantEntry as HashMapVacantEntry; /// A view into a single occupied location in a MultiMap. pub struct OccupiedEntry<'a, K: 'a, V: 'a> { #[doc(hidden)] pub inner: HashMapOccupiedEntry<'a, K, Vec>, } /// A view into a single empty location in a MultiMap. pub struct VacantEntry<'a, K: 'a, V: 'a> { #[doc(hidden)] pub inner: HashMapVacantEntry<'a, K, Vec>, } /// A view into a single location in a map, which may be vacant or occupied. pub enum Entry<'a, K: 'a, V: 'a> { /// An occupied Entry. Occupied(OccupiedEntry<'a, K, V>), /// A vacant Entry. Vacant(VacantEntry<'a, K, V>), } impl<'a, K: 'a, V: 'a> OccupiedEntry<'a, K, V> { /// Gets a reference to the first item in value in the vector corresponding to entry. pub fn get(&self) -> &V { &self.inner.get()[0] } /// Gets a reference to the values (vector) corresponding to entry. pub fn get_vec(&self) -> &Vec { self.inner.get() } /// Gets a mut reference to the first item in value in the vector corresponding to entry. pub fn get_mut(&mut self) -> &mut V { &mut self.inner.get_mut()[0] } /// Gets a mut reference to the values (vector) corresponding to entry. pub fn get_vec_mut(&mut self) -> &mut Vec { self.inner.get_mut() } /// Converts the OccupiedEntry into a mutable reference to the first item in value in the entry /// with a lifetime bound to the map itself pub fn into_mut(self) -> &'a mut V { &mut self.inner.into_mut()[0] } /// Converts the OccupiedEntry into a mutable reference to the values (vector) in the entry /// with a lifetime bound to the map itself pub fn into_vec_mut(self) -> &'a mut Vec { self.inner.into_mut() } /// Inserts a new value onto the vector of the entry. pub fn insert(&mut self, value: V) { self.get_vec_mut().push(value); } /// Extends the existing vector with the specified values. pub fn insert_vec(&mut self, values: Vec) { self.get_vec_mut().extend(values); } /// Takes the values (vector) out of the entry, and returns it pub fn remove(self) -> Vec { self.inner.remove() } } impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> { /// Sets the first value in the vector of the entry with the VacantEntry's key, /// and returns a mutable reference to it. pub fn insert(self, value: V) -> &'a mut V { &mut self.inner.insert(vec![value])[0] } /// Sets values in the entry with the VacantEntry's key, /// and returns a mutable reference to it. pub fn insert_vec(self, values: Vec) -> &'a mut Vec { self.inner.insert(values) } } impl<'a, K: 'a, V: 'a> Entry<'a, K, 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. This will return a mutable reference to the /// first value in the vector corresponding to the specified key. pub fn or_insert(self, default: V) -> &'a mut V { match self { Entry::Occupied(entry) => entry.into_mut(), Entry::Vacant(entry) => entry.insert(default), } } /// Ensures a value is in the entry by inserting the default values if empty, and returns /// a mutable reference to the values (the corresponding vector to the specified key) in /// the entry. pub fn or_insert_vec(self, defaults: Vec) -> &'a mut Vec { match self { Entry::Occupied(entry) => entry.into_vec_mut(), Entry::Vacant(entry) => entry.insert_vec(defaults), } } } multimap-0.8.3/src/lib.rs000064400000000000000000001077050000000000000133560ustar 00000000000000#![forbid(unsafe_code)] // Copyright (c) 2016 multimap developers // // Licensed under the Apache License, Version 2.0 // or the MIT // license , at your // option. All files in the project carrying such notice may not be copied, // modified, or distributed except according to those terms. //! A MultiMap implementation which is just a wrapper around std::collections::HashMap. //! See HashMap's documentation for more details. //! //! Some of the methods are just thin wrappers, some methods does change a little semantics //! and some methods are new (doesn't have an equivalent in HashMap.) //! //! The MultiMap is generic for the key (K) and the value (V). Internally the values are //! stored in a generic Vector. //! //! # Examples //! //! ``` //! use multimap::MultiMap; //! //! // create a new MultiMap. An explicit type signature can be omitted because of the //! // type inference. //! let mut queries = MultiMap::new(); //! //! // insert some queries. //! queries.insert("urls", "http://rust-lang.org"); //! queries.insert("urls", "http://mozilla.org"); //! queries.insert("urls", "http://wikipedia.org"); //! queries.insert("id", "42"); //! queries.insert("name", "roger"); //! //! // check if there's any urls. //! println!("Are there any urls in the multimap? {:?}.", //! if queries.contains_key("urls") {"Yes"} else {"No"} ); //! //! // get the first item in a key's vector. //! assert_eq!(queries.get("urls"), Some(&"http://rust-lang.org")); //! //! // get all the urls. //! assert_eq!(queries.get_vec("urls"), //! Some(&vec!["http://rust-lang.org", "http://mozilla.org", "http://wikipedia.org"])); //! //! // iterate over all keys and the first value in the key's vector. //! for (key, value) in queries.iter() { //! println!("key: {:?}, val: {:?}", key, value); //! } //! //! // iterate over all keys and the key's vector. //! for (key, values) in queries.iter_all() { //! println!("key: {:?}, values: {:?}", key, values); //! } //! //! // the different methods for getting value(s) from the multimap. //! let mut map = MultiMap::new(); //! //! map.insert("key1", 42); //! map.insert("key1", 1337); //! //! assert_eq!(map["key1"], 42); //! assert_eq!(map.get("key1"), Some(&42)); //! assert_eq!(map.get_vec("key1"), Some(&vec![42, 1337])); //! ``` use std::borrow::Borrow; use std::collections::HashMap; use std::collections::hash_map::{Keys, IntoIter, RandomState}; use std::fmt::{self, Debug}; use std::iter::{Iterator, IntoIterator, FromIterator}; use std::hash::{Hash, BuildHasher}; use std::ops::Index; pub use std::collections::hash_map::Iter as IterAll; pub use std::collections::hash_map::IterMut as IterAllMut; pub use entry::{Entry, OccupiedEntry, VacantEntry}; mod entry; #[cfg(feature = "serde_impl")] pub mod serde; #[derive(Clone)] pub struct MultiMap { inner: HashMap, S>, } impl MultiMap where K: Eq + Hash { /// Creates an empty MultiMap /// /// # Examples /// /// ``` /// use multimap::MultiMap; /// /// let mut map: MultiMap<&str, isize> = MultiMap::new(); /// ``` pub fn new() -> MultiMap { MultiMap { inner: HashMap::new() } } /// Creates an empty multimap with the given initial capacity. /// /// # Examples /// /// ``` /// use multimap::MultiMap; /// /// let mut map: MultiMap<&str, isize> = MultiMap::with_capacity(20); /// ``` pub fn with_capacity(capacity: usize) -> MultiMap { MultiMap { inner: HashMap::with_capacity(capacity) } } } impl MultiMap where K: Eq + Hash, S: BuildHasher, { /// Creates an empty MultiMap which will use the given hash builder to hash keys. /// /// # Examples /// /// ``` /// use multimap::MultiMap; /// use std::collections::hash_map::RandomState; /// /// let s = RandomState::new(); /// let mut map: MultiMap<&str, isize> = MultiMap::with_hasher(s); /// ``` pub fn with_hasher(hash_builder: S) -> MultiMap { MultiMap { inner: HashMap::with_hasher(hash_builder) } } /// Creates an empty MultiMap with the given intial capacity and hash builder. /// /// # Examples /// /// ``` /// use multimap::MultiMap; /// use std::collections::hash_map::RandomState; /// /// let s = RandomState::new(); /// let mut map: MultiMap<&str, isize> = MultiMap::with_capacity_and_hasher(20, s); /// ``` pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> MultiMap { MultiMap { inner: HashMap::with_capacity_and_hasher(capacity, hash_builder) } } /// Inserts a key-value pair into the multimap. If the key does exist in /// the map then the value is pushed to that key's vector. If the key doesn't /// exist in the map a new vector with the given value is inserted. /// /// # Examples /// /// ``` /// use multimap::MultiMap; /// /// let mut map = MultiMap::new(); /// map.insert("key", 42); /// ``` pub fn insert(&mut self, k: K, v: V) { match self.entry(k) { Entry::Occupied(mut entry) => { entry.get_vec_mut().push(v); } Entry::Vacant(entry) => { entry.insert_vec(vec![v]); } } } /// Inserts multiple key-value pairs into the multimap. If the key does exist in /// the map then the values are extended into that key's vector. If the key /// doesn't exist in the map a new vector collected from the given values is inserted. /// /// This may be more efficient than inserting values independently. /// /// # Examples /// /// ``` /// use multimap::MultiMap; /// /// let mut map = MultiMap::<&str, &usize>::new(); /// map.insert_many("key", &[42, 43]); /// ``` pub fn insert_many>(&mut self, k: K, v: I) { match self.entry(k) { Entry::Occupied(mut entry) => { entry.get_vec_mut().extend(v); } Entry::Vacant(entry) => { entry.insert_vec(v.into_iter().collect::>()); } } } /// Inserts multiple key-value pairs into the multimap. If the key does exist in /// the map then the values are extended into that key's vector. If the key /// doesn't exist in the map a new vector collected from the given values is inserted. /// /// This may be more efficient than inserting values independently. /// /// # Examples /// /// ``` /// use multimap::MultiMap; /// /// let mut map = MultiMap::<&str, usize>::new(); /// map.insert_many_from_slice("key", &[42, 43]); /// ``` pub fn insert_many_from_slice(&mut self, k: K, v: &[V]) where V: Clone, { match self.entry(k) { Entry::Occupied(mut entry) => { entry.get_vec_mut().extend_from_slice(v); } Entry::Vacant(entry) => { entry.insert_vec(v.to_vec()); } } } /// 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. /// /// # Examples /// /// ``` /// use multimap::MultiMap; /// /// let mut map = MultiMap::new(); /// map.insert(1, 42); /// assert_eq!(map.contains_key(&1), true); /// assert_eq!(map.contains_key(&2), false); /// ``` pub fn contains_key(&self, k: &Q) -> bool where K: Borrow, Q: Eq + Hash { self.inner.contains_key(k) } /// Returns the number of elements in the map. /// /// # Examples /// /// ``` /// use multimap::MultiMap; /// /// let mut map = MultiMap::new(); /// map.insert(1, 42); /// map.insert(2, 1337); /// assert_eq!(map.len(), 2); /// ``` pub fn len(&self) -> usize { self.inner.len() } /// Removes a key from the map, returning the vector of values 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. /// /// # Examples /// /// ``` /// use multimap::MultiMap; /// /// let mut map = MultiMap::new(); /// map.insert(1, 42); /// map.insert(1, 1337); /// assert_eq!(map.remove(&1), Some(vec![42, 1337])); /// assert_eq!(map.remove(&1), None); /// ``` pub fn remove(&mut self, k: &Q) -> Option> where K: Borrow, Q: Eq + Hash { self.inner.remove(k) } /// Returns a reference to the first item in the vector 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. /// /// # Examples /// /// ``` /// use multimap::MultiMap; /// /// let mut map = MultiMap::new(); /// map.insert(1, 42); /// map.insert(1, 1337); /// assert_eq!(map.get(&1), Some(&42)); /// ``` pub fn get(&self, k: &Q) -> Option<&V> where K: Borrow, Q: Eq + Hash { self.inner.get(k).map(|v| &v[0]) } /// Returns a mutable reference to the first item in the vector 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. /// /// # Examples /// /// ``` /// use multimap::MultiMap; /// /// let mut map = MultiMap::new(); /// map.insert(1, 42); /// map.insert(1, 1337); /// if let Some(v) = map.get_mut(&1) { /// *v = 99; /// } /// assert_eq!(map[&1], 99); /// ``` pub fn get_mut(&mut self, k: &Q) -> Option<&mut V> where K: Borrow, Q: Eq + Hash { self.inner.get_mut(k).map(|v| v.get_mut(0).unwrap()) } /// Returns a reference to the vector 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. /// /// # Examples /// /// ``` /// use multimap::MultiMap; /// /// let mut map = MultiMap::new(); /// map.insert(1, 42); /// map.insert(1, 1337); /// assert_eq!(map.get_vec(&1), Some(&vec![42, 1337])); /// ``` pub fn get_vec(&self, k: &Q) -> Option<&Vec> where K: Borrow, Q: Eq + Hash { self.inner.get(k) } /// Returns a mutable reference to the vector 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. /// /// # Examples /// /// ``` /// use multimap::MultiMap; /// /// let mut map = MultiMap::new(); /// map.insert(1, 42); /// map.insert(1, 1337); /// if let Some(v) = map.get_vec_mut(&1) { /// (*v)[0] = 1991; /// (*v)[1] = 2332; /// } /// assert_eq!(map.get_vec(&1), Some(&vec![1991, 2332])); /// ``` pub fn get_vec_mut(&mut self, k: &Q) -> Option<&mut Vec> where K: Borrow, Q: Eq + Hash { self.inner.get_mut(k) } /// Returns true if the key is multi-valued. /// /// 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. /// /// # Examples /// /// ``` /// use multimap::MultiMap; /// /// let mut map = MultiMap::new(); /// map.insert(1, 42); /// map.insert(1, 1337); /// map.insert(2, 2332); /// /// assert_eq!(map.is_vec(&1), true); // key is multi-valued /// assert_eq!(map.is_vec(&2), false); // key is single-valued /// assert_eq!(map.is_vec(&3), false); // key not in map /// ``` pub fn is_vec(&self, k: &Q) -> bool where K: Borrow, Q: Eq + Hash { match self.get_vec(k) { Some(val) => { val.len() > 1 } None => false } } /// Returns the number of elements the map can hold without reallocating. /// /// # Examples /// /// ``` /// use multimap::MultiMap; /// /// let map: MultiMap = MultiMap::new(); /// assert!(map.capacity() >= 0); /// ``` pub fn capacity(&self) -> usize { self.inner.capacity() } /// Returns true if the map contains no elements. /// /// # Examples /// /// ``` /// use multimap::MultiMap; /// /// let mut map = MultiMap::new(); /// assert!(map.is_empty()); /// map.insert(1,42); /// assert!(!map.is_empty()); /// ``` pub fn is_empty(&self) -> bool { self.inner.is_empty() } /// Clears the map, removing all key-value pairs. /// Keeps the allocated memory for reuse. /// /// # Examples /// /// ``` /// use multimap::MultiMap; /// /// let mut map = MultiMap::new(); /// map.insert(1,42); /// map.clear(); /// assert!(map.is_empty()); /// ``` pub fn clear(&mut self) { self.inner.clear(); } /// An iterator visiting all keys in arbitrary order. /// Iterator element type is &'a K. /// /// # Examples /// /// ``` /// use multimap::MultiMap; /// /// let mut map = MultiMap::new(); /// map.insert(1,42); /// map.insert(2,1337); /// map.insert(4,1991); /// /// for key in map.keys() { /// println!("{:?}", key); /// } /// ``` pub fn keys<'a>(&'a self) -> Keys<'a, K, Vec> { self.inner.keys() } /// An iterator visiting all key-value pairs in arbitrary order. The iterator returns /// a reference to the key and the first element in the corresponding key's vector. /// Iterator element type is (&'a K, &'a V). /// /// # Examples /// /// ``` /// use multimap::MultiMap; /// /// let mut map = MultiMap::new(); /// map.insert(1,42); /// map.insert(1,1337); /// map.insert(3,2332); /// map.insert(4,1991); /// /// for (key, value) in map.iter() { /// println!("key: {:?}, val: {:?}", key, value); /// } /// ``` pub fn iter(&self) -> Iter { Iter { inner: self.inner.iter() } } /// An iterator visiting all key-value pairs in arbitrary order. The iterator returns /// a reference to the key and a mutable reference to the first element in the /// corresponding key's vector. Iterator element type is (&'a K, &'a mut V). /// /// # Examples /// /// ``` /// use multimap::MultiMap; /// /// let mut map = MultiMap::new(); /// map.insert(1,42); /// map.insert(1,1337); /// map.insert(3,2332); /// map.insert(4,1991); /// /// for (_, value) in map.iter_mut() { /// *value *= *value; /// } /// /// for (key, value) in map.iter() { /// println!("key: {:?}, val: {:?}", key, value); /// } /// ``` pub fn iter_mut(&mut self) -> IterMut { IterMut { inner: self.inner.iter_mut() } } /// An iterator visiting all key-value pairs in arbitrary order. The iterator returns /// a reference to the key and the corresponding key's vector. /// Iterator element type is (&'a K, &'a V). /// /// # Examples /// /// ``` /// use multimap::MultiMap; /// /// let mut map = MultiMap::new(); /// map.insert(1,42); /// map.insert(1,1337); /// map.insert(3,2332); /// map.insert(4,1991); /// /// for (key, values) in map.iter_all() { /// println!("key: {:?}, values: {:?}", key, values); /// } /// ``` pub fn iter_all(&self) -> IterAll> { self.inner.iter() } /// An iterator visiting all key-value pairs in arbitrary order. The iterator returns /// a reference to the key and the corresponding key's vector. /// Iterator element type is (&'a K, &'a V). /// /// # Examples /// /// ``` /// use multimap::MultiMap; /// /// let mut map = MultiMap::new(); /// map.insert(1,42); /// map.insert(1,1337); /// map.insert(3,2332); /// map.insert(4,1991); /// /// for (key, values) in map.iter_all_mut() { /// for value in values.iter_mut() { /// *value = 99; /// } /// } /// /// for (key, values) in map.iter_all() { /// println!("key: {:?}, values: {:?}", key, values); /// } /// ``` pub fn iter_all_mut(&mut self) -> IterAllMut> { self.inner.iter_mut() } /// Gets the specified key's corresponding entry in the map for in-place manipulation. /// It's possible to both manipulate the vector and the 'value' (the first value in the /// vector). /// /// # Examples /// /// ``` /// use multimap::MultiMap; /// /// let mut m = MultiMap::new(); /// m.insert(1, 42); /// /// { /// let mut v = m.entry(1).or_insert(43); /// assert_eq!(v, &42); /// *v = 44; /// } /// assert_eq!(m.entry(2).or_insert(666), &666); /// /// { /// let mut v = m.entry(1).or_insert_vec(vec![43]); /// assert_eq!(v, &vec![44]); /// v.push(50); /// } /// assert_eq!(m.entry(2).or_insert_vec(vec![666]), &vec![666]); /// /// assert_eq!(m.get_vec(&1), Some(&vec![44, 50])); /// ``` pub fn entry(&mut self, k: K) -> Entry { use std::collections::hash_map::Entry as HashMapEntry; match self.inner.entry(k) { HashMapEntry::Occupied(entry) => Entry::Occupied(OccupiedEntry { inner: entry }), HashMapEntry::Vacant(entry) => Entry::Vacant(VacantEntry { inner: entry }), } } /// Retains only the elements specified by the predicate. /// /// In other words, remove all pairs `(k, v)` such that `f(&k,&mut v)` returns `false`. /// /// # Examples /// /// ``` /// use multimap::MultiMap; /// /// let mut m = MultiMap::new(); /// m.insert(1, 42); /// m.insert(1, 99); /// m.insert(2, 42); /// m.retain(|&k, &v| { k == 1 && v == 42 }); /// assert_eq!(1, m.len()); /// assert_eq!(Some(&42), m.get(&1)); /// ``` pub fn retain(&mut self, mut f: F) where F: FnMut(&K, &V) -> bool { for (key, vector) in &mut self.inner { vector.retain(|ref value| f(key, value)); } self.inner.retain(|&_, ref v| !v.is_empty()); } } impl<'a, K, V, S, Q: ?Sized> Index<&'a Q> for MultiMap where K: Eq + Hash + Borrow, Q: Eq + Hash, S: BuildHasher, { type Output = V; fn index(&self, index: &Q) -> &V { self.inner .get(index) .map(|v| &v[0]) .expect("no entry found for key") } } impl Debug for MultiMap where K: Eq + Hash + Debug, V: Debug, S: BuildHasher { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_map().entries(self.iter_all()).finish() } } impl PartialEq for MultiMap where K: Eq + Hash, V: PartialEq, S: BuildHasher { fn eq(&self, other: &MultiMap) -> bool { if self.len() != other.len() { return false; } self.iter_all().all(|(key, value)| other.get_vec(key).map_or(false, |v| *value == *v)) } } impl Eq for MultiMap where K: Eq + Hash, V: Eq, S: BuildHasher { } impl Default for MultiMap where K: Eq + Hash, S: BuildHasher + Default { fn default() -> MultiMap { MultiMap { inner: Default::default() } } } impl FromIterator<(K, V)> for MultiMap where K: Eq + Hash, S: BuildHasher + Default { fn from_iter>(iterable: T) -> MultiMap { let iter = iterable.into_iter(); let hint = iter.size_hint().0; let mut multimap = MultiMap::with_capacity_and_hasher(hint, S::default()); for (k, v) in iter { multimap.insert(k, v); } multimap } } impl<'a, K, V, S> IntoIterator for &'a MultiMap where K: Eq + Hash, S: BuildHasher { type Item = (&'a K, &'a Vec); type IntoIter = IterAll<'a, K, Vec>; fn into_iter(self) -> IterAll<'a, K, Vec> { self.iter_all() } } impl<'a, K, V, S> IntoIterator for &'a mut MultiMap where K: Eq + Hash, S: BuildHasher { type Item = (&'a K, &'a mut Vec); type IntoIter = IterAllMut<'a, K, Vec>; fn into_iter(self) -> IterAllMut<'a, K, Vec> { self.inner.iter_mut() } } impl IntoIterator for MultiMap where K: Eq + Hash, S: BuildHasher { type Item = (K, Vec); type IntoIter = IntoIter>; fn into_iter(self) -> IntoIter> { self.inner.into_iter() } } impl Extend<(K, V)> for MultiMap where K: Eq + Hash, S: BuildHasher { fn extend>(&mut self, iter: T) { for (k, v) in iter { self.insert(k, v); } } } impl<'a, K, V, S> Extend<(&'a K, &'a V)> for MultiMap where K: Eq + Hash + Copy, V: Copy, S: BuildHasher { fn extend>(&mut self, iter: T) { self.extend(iter.into_iter().map(|(&key, &value)| (key, value))); } } impl Extend<(K, Vec)> for MultiMap where K: Eq + Hash, S: BuildHasher { fn extend)>>(&mut self, iter: T) { for (k, values) in iter { match self.entry(k) { Entry::Occupied(mut entry) => { entry.get_vec_mut().extend(values); } Entry::Vacant(entry) => { entry.insert_vec(values); } } } } } impl<'a, K, V, S> Extend<(&'a K, &'a Vec)> for MultiMap where K: Eq + Hash + Copy, V: Copy, S: BuildHasher { fn extend)>>(&mut self, iter: T) { self.extend(iter.into_iter().map(|(&key, values)| (key, values.to_owned()))); } } #[derive(Clone)] pub struct Iter<'a, K: 'a, V: 'a> { inner: IterAll<'a, K, Vec>, } impl<'a, K, V> Iterator for Iter<'a, K, V> { type Item = (&'a K, &'a V); fn next(&mut self) -> Option<(&'a K, &'a V)> { self.inner.next().map(|(k, v)| (k, &v[0])) } fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } } impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> { fn len(&self) -> usize { self.inner.len() } } pub struct IterMut<'a, K: 'a, V: 'a> { inner: IterAllMut<'a, K, Vec>, } impl<'a, K, V> Iterator for IterMut<'a, K, V> { type Item = (&'a K, &'a mut V); fn next(&mut self) -> Option<(&'a K, &'a mut V)> { self.inner.next().map(|(k, v)| (k, &mut v[0])) } fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } } impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> { fn len(&self) -> usize { self.inner.len() } } #[macro_export] /// Create a `MultiMap` from a list of key value pairs /// /// ## Example /// /// ``` /// # use multimap::MultiMap; /// #[macro_use] extern crate multimap; /// # fn main(){ /// /// let map = multimap!( /// "dog" => "husky", /// "dog" => "retreaver", /// "dog" => "shiba inu", /// "cat" => "cat" /// ); /// # } /// /// ``` macro_rules! multimap{ (@replace_with_unit $_t:tt) => { () }; (@count $($key:expr),*) => { <[()]>::len(&[$($crate::multimap! { @replace_with_unit $key }),*]) }; ($($key:expr => $value:expr),* $(,)?)=>{ { let mut map = $crate::MultiMap::with_capacity($crate::multimap! { @count $($key),* }); $( map.insert($key,$value); )* map } } } #[cfg(test)] mod tests { use std::collections::HashMap; use std::iter::FromIterator; use super::*; #[test] fn create() { let _: MultiMap = MultiMap { inner: HashMap::new() }; } #[test] fn new() { let _: MultiMap = MultiMap::new(); } #[test] fn with_capacity() { let _: MultiMap = MultiMap::with_capacity(20); } #[test] fn insert() { let mut m: MultiMap = MultiMap::new(); m.insert(1, 3); } #[test] fn insert_many() { let mut m: MultiMap = MultiMap::new(); m.insert_many(1, vec![3, 4]); assert_eq!(Some(&vec![3, 4]), m.get_vec(&1)); } #[test] fn insert_many_again() { let mut m: MultiMap = MultiMap::new(); m.insert(1, 2); m.insert_many(1, vec![3, 4]); assert_eq!(Some(&vec![2, 3, 4]), m.get_vec(&1)); } #[test] fn insert_many_from_slice() { let mut m: MultiMap = MultiMap::new(); m.insert_many_from_slice(1, &[3, 4]); assert_eq!(Some(&vec![3, 4]), m.get_vec(&1)); } #[test] fn insert_many_from_slice_again() { let mut m: MultiMap = MultiMap::new(); m.insert(1, 2); m.insert_many_from_slice(1, &[3, 4]); assert_eq!(Some(&vec![2, 3, 4]), m.get_vec(&1)); } #[test] fn insert_existing() { let mut m: MultiMap = MultiMap::new(); m.insert(1, 3); m.insert(1, 4); } #[test] #[should_panic] fn index_no_entry() { let m: MultiMap = MultiMap::new(); &m[&1]; } #[test] fn index() { let mut m: MultiMap = MultiMap::new(); m.insert(1, 42); let values = m[&1]; assert_eq!(values, 42); } #[test] fn contains_key_true() { let mut m: MultiMap = MultiMap::new(); m.insert(1, 42); assert!(m.contains_key(&1)); } #[test] fn contains_key_false() { let m: MultiMap = MultiMap::new(); assert_eq!(m.contains_key(&1), false); } #[test] fn len() { let mut m: MultiMap = MultiMap::new(); m.insert(1, 42); m.insert(2, 1337); m.insert(3, 99); assert_eq!(m.len(), 3); } #[test] fn remove_not_present() { let mut m: MultiMap = MultiMap::new(); let v = m.remove(&1); assert_eq!(v, None); } #[test] fn remove_present() { let mut m: MultiMap = MultiMap::new(); m.insert(1, 42); let v = m.remove(&1); assert_eq!(v, Some(vec![42])); } #[test] fn get_not_present() { let m: MultiMap = MultiMap::new(); assert_eq!(m.get(&1), None); } #[test] fn get_present() { let mut m: MultiMap = MultiMap::new(); m.insert(1, 42); assert_eq!(m.get(&1), Some(&42)); } #[test] fn get_vec_not_present() { let m: MultiMap = MultiMap::new(); assert_eq!(m.get_vec(&1), None); } #[test] fn get_vec_present() { let mut m: MultiMap = MultiMap::new(); m.insert(1, 42); m.insert(1, 1337); assert_eq!(m.get_vec(&1), Some(&vec![42, 1337])); } #[test] fn capacity() { let m: MultiMap = MultiMap::with_capacity(20); assert!(m.capacity() >= 20); } #[test] fn is_empty_true() { let m: MultiMap = MultiMap::new(); assert_eq!(m.is_empty(), true); } #[test] fn is_empty_false() { let mut m: MultiMap = MultiMap::new(); m.insert(1, 42); assert_eq!(m.is_empty(), false); } #[test] fn clear() { let mut m: MultiMap = MultiMap::new(); m.insert(1, 42); m.clear(); assert!(m.is_empty()); } #[test] fn get_mut() { let mut m: MultiMap = MultiMap::new(); m.insert(1, 42); if let Some(v) = m.get_mut(&1) { *v = 1337; } assert_eq!(m[&1], 1337) } #[test] fn get_vec_mut() { let mut m: MultiMap = MultiMap::new(); m.insert(1, 42); m.insert(1, 1337); if let Some(v) = m.get_vec_mut(&1) { (*v)[0] = 5; (*v)[1] = 10; } assert_eq!(m.get_vec(&1), Some(&vec![5, 10])) } #[test] fn keys() { let mut m: MultiMap = MultiMap::new(); m.insert(1, 42); m.insert(2, 42); m.insert(4, 42); m.insert(8, 42); let keys: Vec<_> = m.keys().cloned().collect(); assert_eq!(keys.len(), 4); assert!(keys.contains(&1)); assert!(keys.contains(&2)); assert!(keys.contains(&4)); assert!(keys.contains(&8)); } #[test] fn iter() { let mut m: MultiMap = MultiMap::new(); m.insert(1, 42); m.insert(1, 42); m.insert(4, 42); m.insert(8, 42); let mut iter = m.iter(); for _ in iter.by_ref().take(2) {} assert_eq!(iter.len(), 1); } #[test] fn intoiterator_for_reference_type() { let mut m: MultiMap = MultiMap::new(); m.insert(1, 42); m.insert(1, 43); m.insert(4, 42); m.insert(8, 42); let keys = vec![1, 4, 8]; for (key, value) in &m { assert!(keys.contains(key)); if key == &1 { assert_eq!(value, &vec![42, 43]); } else { assert_eq!(value, &vec![42]); } } } #[test] fn intoiterator_for_mutable_reference_type() { let mut m: MultiMap = MultiMap::new(); m.insert(1, 42); m.insert(1, 43); m.insert(4, 42); m.insert(8, 42); let keys = vec![1, 4, 8]; for (key, value) in &mut m { assert!(keys.contains(key)); if key == &1 { assert_eq!(value, &vec![42, 43]); value.push(666); } else { assert_eq!(value, &vec![42]); } } assert_eq!(m.get_vec(&1), Some(&vec![42, 43, 666])); } #[test] fn intoiterator_consuming() { let mut m: MultiMap = MultiMap::new(); m.insert(1, 42); m.insert(1, 43); m.insert(4, 42); m.insert(8, 42); let keys = vec![1, 4, 8]; for (key, value) in m { assert!(keys.contains(&key)); if key == 1 { assert_eq!(value, vec![42, 43]); } else { assert_eq!(value, vec![42]); } } } #[test] fn test_fmt_debug() { let mut map = MultiMap::new(); let empty: MultiMap = MultiMap::new(); map.insert(1, 2); map.insert(1, 5); map.insert(1, -1); map.insert(3, 4); let map_str = format!("{:?}", map); assert!(map_str == "{1: [2, 5, -1], 3: [4]}" || map_str == "{3: [4], 1: [2, 5, -1]}"); assert_eq!(format!("{:?}", empty), "{}"); } #[test] fn test_eq() { let mut m1 = MultiMap::new(); m1.insert(1, 2); m1.insert(2, 3); m1.insert(3, 4); let mut m2 = MultiMap::new(); m2.insert(1, 2); m2.insert(2, 3); assert!(m1 != m2); m2.insert(3, 4); assert_eq!(m1, m2); m2.insert(3, 4); assert!(m1 != m2); m1.insert(3, 4); assert_eq!(m1, m2); } #[test] fn test_default() { let _: MultiMap = Default::default(); } #[test] fn test_from_iterator() { let vals: Vec<(&str, i64)> = vec![("foo", 123), ("bar", 456), ("foo", 789)]; let multimap: MultiMap<&str, i64> = MultiMap::from_iter(vals); let foo_vals: &Vec = multimap.get_vec("foo").unwrap(); assert!(foo_vals.contains(&123)); assert!(foo_vals.contains(&789)); let bar_vals: &Vec = multimap.get_vec("bar").unwrap(); assert!(bar_vals.contains(&456)); } #[test] fn test_extend_consuming_hashmap() { let mut a = MultiMap::new(); a.insert(1, 42); let mut b = HashMap::new(); b.insert(1, 43); b.insert(2, 666); a.extend(b); assert_eq!(a.len(), 2); assert_eq!(a.get_vec(&1), Some(&vec![42, 43])); } #[test] fn test_extend_ref_hashmap() { let mut a = MultiMap::new(); a.insert(1, 42); let mut b = HashMap::new(); b.insert(1, 43); b.insert(2, 666); a.extend(&b); assert_eq!(a.len(), 2); assert_eq!(a.get_vec(&1), Some(&vec![42, 43])); assert_eq!(b.len(), 2); assert_eq!(b[&1], 43); } #[test] fn test_extend_consuming_multimap() { let mut a = MultiMap::new(); a.insert(1, 42); let mut b = MultiMap::new(); b.insert(1, 43); b.insert(1, 44); b.insert(2, 666); a.extend(b); assert_eq!(a.len(), 2); assert_eq!(a.get_vec(&1), Some(&vec![42, 43, 44])); } #[test] fn test_extend_ref_multimap() { let mut a = MultiMap::new(); a.insert(1, 42); let mut b = MultiMap::new(); b.insert(1, 43); b.insert(1, 44); b.insert(2, 666); a.extend(&b); assert_eq!(a.len(), 2); assert_eq!(a.get_vec(&1), Some(&vec![42, 43, 44])); assert_eq!(b.len(), 2); assert_eq!(b.get_vec(&1), Some(&vec![43, 44])); } #[test] fn test_entry() { let mut m = MultiMap::new(); m.insert(1, 42); { let v = m.entry(1).or_insert(43); assert_eq!(v, &42); *v = 44; } assert_eq!(m.entry(2).or_insert(666), &666); assert_eq!(m[&1], 44); assert_eq!(m[&2], 666); } #[test] fn test_entry_vec() { let mut m = MultiMap::new(); m.insert(1, 42); { let v = m.entry(1).or_insert_vec(vec![43]); assert_eq!(v, &vec![42]); *v.first_mut().unwrap() = 44; } assert_eq!(m.entry(2).or_insert_vec(vec![666]), &vec![666]); assert_eq!(m[&1], 44); assert_eq!(m[&2], 666); } #[test] fn test_is_vec() { let mut m = MultiMap::new(); m.insert(1, 42); m.insert(1, 1337); m.insert(2, 2332); assert!(m.is_vec(&1)); assert!(!m.is_vec(&2)); assert!(!m.is_vec(&3)); } #[test] fn test_macro(){ let mut manual_map = MultiMap::new(); manual_map.insert("key1", 42); assert_eq!(manual_map, multimap!("key1" => 42)); manual_map.insert("key1", 1337); manual_map.insert("key2", 2332); let macro_map = multimap!{ "key1" => 42, "key1" => 1337, "key2" => 2332 }; assert_eq!(manual_map, macro_map); } #[test] fn retain_removes_element() { let mut m = MultiMap::new(); m.insert(1, 42); m.insert(1, 99); m.retain(|&k, &v| { k == 1 && v == 42 }); assert_eq!(1, m.len()); assert_eq!(Some(&42), m.get(&1)); } #[test] fn retain_also_removes_empty_vector() { let mut m = MultiMap::new(); m.insert(1, 42); m.insert(1, 99); m.insert(2, 42); m.retain(|&k, &v| { k == 1 && v == 42 }); assert_eq!(1, m.len()); assert_eq!(Some(&42), m.get(&1)); } } multimap-0.8.3/src/serde.rs000064400000000000000000000065710000000000000137110ustar 00000000000000// Copyright (c) 2016 multimap developers // // Licensed under the Apache License, Version 2.0 // or the MIT // license , at your // option. All files in the project carrying such notice may not be copied, // modified, or distributed except according to those terms. //! Serde trait implementations for MultiMap extern crate serde; use std::fmt; use std::hash::{Hash, BuildHasher}; use std::marker::PhantomData; use self::serde::{Deserialize, Deserializer, Serialize, Serializer}; use self::serde::de::{MapAccess, Visitor}; use MultiMap; impl Serialize for MultiMap where K: Serialize + Eq + Hash, V: Serialize, BS: BuildHasher { fn serialize(&self, serializer: S) -> Result where S: Serializer { self.inner.serialize(serializer) } } impl MultiMapVisitor where K: Hash + Eq { fn new() -> Self { MultiMapVisitor { marker: PhantomData } } } struct MultiMapVisitor { marker: PhantomData> } impl<'a, K, V, S> Visitor<'a> for MultiMapVisitor where K: Deserialize<'a> + Eq + Hash, V: Deserialize<'a>, S: BuildHasher + Default { type Value = MultiMap; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("expected a map") } fn visit_map(self, mut visitor: M) -> Result where M: MapAccess<'a> { let mut values = MultiMap::with_capacity_and_hasher(visitor.size_hint().unwrap_or(0), S::default()); while let Some((key, value)) = visitor.next_entry()? { values.inner.insert(key, value); } Ok(values) } } impl<'a, K, V, S> Deserialize<'a> for MultiMap where K: Deserialize<'a> + Eq + Hash, V: Deserialize<'a>, S: BuildHasher + Default { fn deserialize(deserializer: D) -> Result where D: Deserializer<'a> { deserializer.deserialize_map(MultiMapVisitor::::new()) } } #[cfg(test)] mod tests { extern crate serde_test; use self::serde_test::{Token, assert_tokens}; use super::*; #[test] fn test_empty() { let map = MultiMap::::new(); assert_tokens(&map, &[ Token::Map { len: Some(0) }, Token::MapEnd, ]); } #[test] fn test_single() { let mut map = MultiMap::::new(); map.insert('x', 1); assert_tokens(&map, &[ Token::Map { len: Some(1) }, Token::Char('x'), Token::Seq { len: Some(1) }, Token::U8(1), Token::SeqEnd, Token::MapEnd, ]); } #[test] fn test_multiple() { let mut map = MultiMap::::new(); map.insert('x', 1); map.insert('x', 3); map.insert('x', 1); map.insert('x', 5); assert_tokens(&map, &[ Token::Map { len: Some(1) }, Token::Char('x'), Token::Seq { len: Some(4) }, Token::U8(1), Token::U8(3), Token::U8(1), Token::U8(5), Token::SeqEnd, Token::MapEnd, ]); } }