linked-hash-map-0.5.4/.cargo_vcs_info.json0000644000000001121377613407700140530ustar { "git": { "sha1": "0531e100ef052fd49b2f465abf96cd88aea84692" } } linked-hash-map-0.5.4/.gitignore000064400000000000000000000000221377613357400146120ustar 00000000000000target Cargo.lock linked-hash-map-0.5.4/Cargo.toml0000644000000025311377613407700120600ustar # 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 = "linked-hash-map" version = "0.5.4" authors = ["Stepan Koltsov ", "Andrew Paseltiner "] exclude = ["/.travis.yml", "/deploy-docs.sh"] description = "A HashMap wrapper that holds key-value pairs in insertion order" homepage = "https://github.com/contain-rs/linked-hash-map" documentation = "https://docs.rs/linked-hash-map" readme = "README.md" keywords = ["data-structures"] license = "MIT/Apache-2.0" repository = "https://github.com/contain-rs/linked-hash-map" [dependencies.clippy] version = "0.*" optional = true [dependencies.heapsize] version = "0.4" optional = true [dependencies.serde] version = "1.0" optional = true [dependencies.serde_test] version = "1.0" optional = true [features] heapsize_impl = ["heapsize"] nightly = [] serde_impl = ["serde", "serde_test"] linked-hash-map-0.5.4/Cargo.toml.orig000064400000000000000000000015061377613361100155110ustar 00000000000000[package] name = "linked-hash-map" version = "0.5.4" license = "MIT/Apache-2.0" description = "A HashMap wrapper that holds key-value pairs in insertion order" authors = [ "Stepan Koltsov ", "Andrew Paseltiner ", ] repository = "https://github.com/contain-rs/linked-hash-map" homepage = "https://github.com/contain-rs/linked-hash-map" documentation = "https://docs.rs/linked-hash-map" keywords = ["data-structures"] readme = "README.md" exclude = ["/.travis.yml", "/deploy-docs.sh"] [features] nightly = [] serde_impl = ["serde", "serde_test"] heapsize_impl = ["heapsize"] [dependencies] clippy = { version = "0.*", optional = true } serde = { version = "1.0", optional = true } serde_test = { version = "1.0", optional = true } heapsize = { version = "0.4", optional = true } linked-hash-map-0.5.4/LICENSE-APACHE000064400000000000000000000251421377613357400145600ustar 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. linked-hash-map-0.5.4/LICENSE-MIT000064400000000000000000000020571377613357400142700ustar 00000000000000Copyright (c) 2015 The Rust 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. linked-hash-map-0.5.4/README.md000064400000000000000000000007721377613357400141150ustar 00000000000000**WARNING: THIS PROJECT IS IN MAINTENANCE MODE, DUE TO INSUFFICIENT MAINTAINER RESOURCES** It works fine, but will generally no longer be improved. We are currently only accepting changes which: * keep this compiling with the latest versions of Rust or its dependencies. * have minimal review requirements, such as documentation changes (so not totally new APIs). ------ A HashMap wrapper that holds key-value pairs in insertion order. Documentation is available at https://docs.rs/linked-hash-map. linked-hash-map-0.5.4/src/heapsize.rs000064400000000000000000000023741377613357400156030ustar 00000000000000extern crate heapsize; use self::heapsize::{HeapSizeOf, heap_size_of}; use std::hash::{Hash, BuildHasher}; use {LinkedHashMap, KeyRef, Node}; impl HeapSizeOf for KeyRef { fn heap_size_of_children(&self) -> usize { 0 } } impl HeapSizeOf for Node where K: HeapSizeOf, V: HeapSizeOf { fn heap_size_of_children(&self) -> usize { self.key.heap_size_of_children() + self.value.heap_size_of_children() } } impl HeapSizeOf for LinkedHashMap where K: HeapSizeOf + Hash + Eq, V: HeapSizeOf, S: BuildHasher { fn heap_size_of_children(&self) -> usize { unsafe { let mut size = self.map.heap_size_of_children(); for &value in self.map.values() { size += (*value).heap_size_of_children(); size += heap_size_of(value as *const _ as *const _); } if !self.head.is_null() { size += heap_size_of(self.head as *const _ as *const _); } let mut free = self.free; while !free.is_null() { size += heap_size_of(free as *const _ as *const _); free = (*free).next } size } } } linked-hash-map-0.5.4/src/lib.rs000064400000000000000000001156111377613357400145400ustar 00000000000000// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! A `HashMap` wrapper that holds key-value pairs in insertion order. //! //! # Examples //! //! ``` //! use linked_hash_map::LinkedHashMap; //! //! let mut map = LinkedHashMap::new(); //! map.insert(2, 20); //! map.insert(1, 10); //! map.insert(3, 30); //! assert_eq!(map[&1], 10); //! assert_eq!(map[&2], 20); //! assert_eq!(map[&3], 30); //! //! let items: Vec<(i32, i32)> = map.iter().map(|t| (*t.0, *t.1)).collect(); //! assert_eq!(items, [(2, 20), (1, 10), (3, 30)]); //! ``` #![forbid(missing_docs)] #![cfg_attr(all(feature = "nightly", test), feature(test))] #![cfg_attr(feature = "clippy", feature(plugin))] #![cfg_attr(feature = "clippy", plugin(clippy))] #![cfg_attr(feature = "clippy", deny(clippy))] // Optional Serde support #[cfg(feature = "serde_impl")] pub mod serde; // Optional Heapsize support #[cfg(feature = "heapsize_impl")] mod heapsize; use std::borrow::Borrow; use std::cmp::Ordering; use std::collections::hash_map::{self, HashMap}; use std::fmt; use std::hash::{BuildHasher, Hash, Hasher}; use std::iter; use std::marker; use std::mem; use std::ops::{Index, IndexMut}; use std::ptr; struct KeyRef { k: *const K } struct Node { next: *mut Node, prev: *mut Node, key: K, value: V, } /// A linked hash map. pub struct LinkedHashMap { map: HashMap, *mut Node, S>, head: *mut Node, free: *mut Node, } impl Hash for KeyRef { fn hash(&self, state: &mut H) { unsafe { (*self.k).hash(state) } } } impl PartialEq for KeyRef { fn eq(&self, other: &Self) -> bool { unsafe{ (*self.k).eq(&*other.k) } } } impl Eq for KeyRef {} // This type exists only to support borrowing `KeyRef`s, which cannot be borrowed to `Q` directly // due to conflicting implementations of `Borrow`. The layout of `&Qey` must be identical to // `&Q` in order to support transmuting in the `Qey::from_ref` method. #[derive(Hash, PartialEq, Eq)] #[repr(transparent)] struct Qey(Q); impl Qey { fn from_ref(q: &Q) -> &Self { unsafe { mem::transmute(q) } } } impl Borrow> for KeyRef where K: Borrow { fn borrow(&self) -> &Qey { Qey::from_ref(unsafe { (*self.k).borrow() }) } } impl Node { fn new(k: K, v: V) -> Self { Node { key: k, value: v, next: ptr::null_mut(), prev: ptr::null_mut(), } } } // drop empty node without dropping its key and value unsafe fn drop_empty_node(the_box: *mut Node) { // Safety: // In this crate all `Node` is allocated via `Box` or `alloc`, and `Box` uses the // Global allocator for its allocation, // (https://doc.rust-lang.org/std/boxed/index.html#memory-layout) so we can safely // deallocate the pointer to `Node` by calling `dealloc` method let layout = std::alloc::Layout::new::>(); std::alloc::dealloc(the_box as *mut u8, layout); } impl LinkedHashMap { /// Creates a linked hash map. pub fn new() -> Self { Self::with_map(HashMap::new()) } /// Creates an empty linked hash map with the given initial capacity. pub fn with_capacity(capacity: usize) -> Self { Self::with_map(HashMap::with_capacity(capacity)) } } impl LinkedHashMap { #[inline] fn detach(&mut self, node: *mut Node) { unsafe { (*(*node).prev).next = (*node).next; (*(*node).next).prev = (*node).prev; } } #[inline] fn attach(&mut self, node: *mut Node) { unsafe { (*node).next = (*self.head).next; (*node).prev = self.head; (*self.head).next = node; (*(*node).next).prev = node; } } // Caller must check `!self.head.is_null()` unsafe fn drop_entries(&mut self) { let mut cur = (*self.head).next; while cur != self.head { let next = (*cur).next; Box::from_raw(cur); cur = next; } } fn clear_free_list(&mut self) { unsafe { let mut free = self.free; while ! free.is_null() { let next_free = (*free).next; drop_empty_node(free); free = next_free; } self.free = ptr::null_mut(); } } fn ensure_guard_node(&mut self) { if self.head.is_null() { // allocate the guard node if not present unsafe { let node_layout = std::alloc::Layout::new::>(); self.head = std::alloc::alloc(node_layout) as *mut Node; (*self.head).next = self.head; (*self.head).prev = self.head; } } } } impl LinkedHashMap { fn with_map(map: HashMap, *mut Node, S>) -> Self { LinkedHashMap { map: map, head: ptr::null_mut(), free: ptr::null_mut(), } } /// Creates an empty linked hash map with the given initial hash builder. pub fn with_hasher(hash_builder: S) -> Self { Self::with_map(HashMap::with_hasher(hash_builder)) } /// Creates an empty linked hash map with the given initial capacity and hash builder. pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Self { Self::with_map(HashMap::with_capacity_and_hasher(capacity, hash_builder)) } /// Reserves capacity for at least `additional` more elements to be inserted into the map. The /// map may reserve more space to avoid frequent allocations. /// /// # Panics /// /// Panics if the new allocation size overflows `usize.` pub fn reserve(&mut self, additional: usize) { self.map.reserve(additional); } /// Shrinks the capacity of the map 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. pub fn shrink_to_fit(&mut self) { self.map.shrink_to_fit(); self.clear_free_list(); } /// Gets the given key's corresponding entry in the map for in-place manipulation. /// /// # Examples /// /// ``` /// use linked_hash_map::LinkedHashMap; /// /// let mut letters = LinkedHashMap::new(); /// /// for ch in "a short treatise on fungi".chars() { /// let counter = letters.entry(ch).or_insert(0); /// *counter += 1; /// } /// /// assert_eq!(letters[&'s'], 2); /// assert_eq!(letters[&'t'], 3); /// assert_eq!(letters[&'u'], 1); /// assert_eq!(letters.get(&'y'), None); /// ``` pub fn entry(&mut self, k: K) -> Entry { let self_ptr: *mut Self = self; if let Some(entry) = self.map.get_mut(&KeyRef{k: &k}) { return Entry::Occupied(OccupiedEntry { entry: *entry, map: self_ptr, marker: marker::PhantomData, }); } Entry::Vacant(VacantEntry { key: k, map: self, }) } /// Returns an iterator visiting all entries in insertion order. /// Iterator element type is `OccupiedEntry`. Allows for removal /// as well as replacing the entry. /// /// # Examples /// ``` /// use linked_hash_map::LinkedHashMap; /// /// let mut map = LinkedHashMap::new(); /// map.insert("a", 10); /// map.insert("c", 30); /// map.insert("b", 20); /// /// { /// let mut iter = map.entries(); /// let mut entry = iter.next().unwrap(); /// assert_eq!(&"a", entry.key()); /// *entry.get_mut() = 17; /// } /// /// assert_eq!(&17, map.get(&"a").unwrap()); /// ``` pub fn entries(&mut self) -> Entries { let head = if ! self.head.is_null() { unsafe { (*self.head).prev } } else { ptr::null_mut() }; Entries { map: self, head: head, remaining: self.len(), marker: marker::PhantomData, } } /// Inserts a key-value pair into the map. If the key already existed, the old value is /// returned. /// /// # Examples /// /// ``` /// use linked_hash_map::LinkedHashMap; /// let mut map = LinkedHashMap::new(); /// /// map.insert(1, "a"); /// map.insert(2, "b"); /// assert_eq!(map[&1], "a"); /// assert_eq!(map[&2], "b"); /// ``` pub fn insert(&mut self, k: K, v: V) -> Option { self.ensure_guard_node(); let (node, old_val) = match self.map.get(&KeyRef{k: &k}) { Some(node) => { let old_val = unsafe { ptr::replace(&mut (**node).value, v) }; (*node, Some(old_val)) } None => { let node = if self.free.is_null() { Box::into_raw(Box::new(Node::new(k, v))) } else { // use a recycled box unsafe { let free = self.free; self.free = (*free).next; ptr::write(free, Node::new(k, v)); free } }; (node, None) } }; match old_val { Some(_) => { // Existing node, just update LRU position self.detach(node); self.attach(node); } None => { let keyref = unsafe { &(*node).key }; self.map.insert(KeyRef{k: keyref}, node); self.attach(node); } } old_val } /// Checks if the map contains the given key. pub fn contains_key(&self, k: &Q) -> bool where K: Borrow, Q: Eq + Hash { self.map.contains_key(Qey::from_ref(k)) } /// Returns the value corresponding to the key in the map. /// /// # Examples /// /// ``` /// use linked_hash_map::LinkedHashMap; /// let mut map = LinkedHashMap::new(); /// /// map.insert(1, "a"); /// map.insert(2, "b"); /// map.insert(2, "c"); /// map.insert(3, "d"); /// /// assert_eq!(map.get(&1), Some(&"a")); /// assert_eq!(map.get(&2), Some(&"c")); /// ``` pub fn get(&self, k: &Q) -> Option<&V> where K: Borrow, Q: Eq + Hash { self.map.get(Qey::from_ref(k)).map(|e| unsafe { &(**e).value }) } /// Returns the mutable reference corresponding to the key in the map. /// /// # Examples /// /// ``` /// use linked_hash_map::LinkedHashMap; /// let mut map = LinkedHashMap::new(); /// /// map.insert(1, "a"); /// map.insert(2, "b"); /// /// *map.get_mut(&1).unwrap() = "c"; /// assert_eq!(map.get(&1), Some(&"c")); /// ``` pub fn get_mut(&mut self, k: &Q) -> Option<&mut V> where K: Borrow, Q: Eq + Hash { self.map.get(Qey::from_ref(k)).map(|e| unsafe { &mut (**e).value }) } /// Returns the value corresponding to the key in the map. /// /// If value is found, it is moved to the end of the list. /// This operation can be used in implemenation of LRU cache. /// /// # Examples /// /// ``` /// use linked_hash_map::LinkedHashMap; /// let mut map = LinkedHashMap::new(); /// /// map.insert(1, "a"); /// map.insert(2, "b"); /// map.insert(3, "d"); /// /// assert_eq!(map.get_refresh(&2), Some(&mut "b")); /// /// assert_eq!((&2, &"b"), map.iter().rev().next().unwrap()); /// ``` pub fn get_refresh(&mut self, k: &Q) -> Option<&mut V> where K: Borrow, Q: Eq + Hash { let (value, node_ptr_opt) = match self.map.get(Qey::from_ref(k)) { None => (None, None), Some(node) => { (Some(unsafe { &mut (**node).value }), Some(*node)) } }; if let Some(node_ptr) = node_ptr_opt { self.detach(node_ptr); self.attach(node_ptr); } value } /// Removes and returns the value corresponding to the key from the map. /// /// # Examples /// /// ``` /// use linked_hash_map::LinkedHashMap; /// let mut map = LinkedHashMap::new(); /// /// map.insert(2, "a"); /// /// assert_eq!(map.remove(&1), None); /// assert_eq!(map.remove(&2), Some("a")); /// assert_eq!(map.remove(&2), None); /// assert_eq!(map.len(), 0); /// ``` pub fn remove(&mut self, k: &Q) -> Option where K: Borrow, Q: Eq + Hash { let removed = self.map.remove(Qey::from_ref(k)); removed.map(|node| { self.detach(node); unsafe { // add to free list (*node).next = self.free; self.free = node; // drop the key and return the value drop(ptr::read(&(*node).key)); ptr::read(&(*node).value) } }) } /// Returns the maximum number of key-value pairs the map can hold without reallocating. /// /// # Examples /// /// ``` /// use linked_hash_map::LinkedHashMap; /// let mut map: LinkedHashMap = LinkedHashMap::new(); /// let capacity = map.capacity(); /// ``` pub fn capacity(&self) -> usize { self.map.capacity() } /// Removes the first entry. /// /// Can be used in implementation of LRU cache. /// /// # Examples /// /// ``` /// use linked_hash_map::LinkedHashMap; /// let mut map = LinkedHashMap::new(); /// map.insert(1, 10); /// map.insert(2, 20); /// map.pop_front(); /// assert_eq!(map.get(&1), None); /// assert_eq!(map.get(&2), Some(&20)); /// ``` #[inline] pub fn pop_front(&mut self) -> Option<(K, V)> { if self.is_empty() { return None } let lru = unsafe { (*self.head).prev }; self.detach(lru); self.map .remove(&KeyRef{k: unsafe { &(*lru).key }}) .map(|e| { let e = *unsafe { Box::from_raw(e) }; (e.key, e.value) }) } /// Gets the first entry. /// /// # Examples /// /// ``` /// use linked_hash_map::LinkedHashMap; /// let mut map = LinkedHashMap::new(); /// map.insert(1, 10); /// map.insert(2, 20); /// assert_eq!(map.front(), Some((&1, &10))); /// ``` #[inline] pub fn front(&self) -> Option<(&K, &V)> { if self.is_empty() { return None } let lru = unsafe { (*self.head).prev }; self.map .get(&KeyRef{k: unsafe { &(*lru).key }}) .map(|e| unsafe { (&(**e).key, &(**e).value) }) } /// Removes the last entry. /// /// # Examples /// /// ``` /// use linked_hash_map::LinkedHashMap; /// let mut map = LinkedHashMap::new(); /// map.insert(1, 10); /// map.insert(2, 20); /// map.pop_back(); /// assert_eq!(map.get(&1), Some(&10)); /// assert_eq!(map.get(&2), None); /// ``` #[inline] pub fn pop_back(&mut self) -> Option<(K, V)> { if self.is_empty() { return None } let mru = unsafe { (*self.head).next }; self.detach(mru); self.map .remove(&KeyRef{k: unsafe { &(*mru).key }}) .map(|e| { let e = *unsafe { Box::from_raw(e) }; (e.key, e.value) }) } /// Gets the last entry. /// /// # Examples /// /// ``` /// use linked_hash_map::LinkedHashMap; /// let mut map = LinkedHashMap::new(); /// map.insert(1, 10); /// map.insert(2, 20); /// assert_eq!(map.back(), Some((&2, &20))); /// ``` #[inline] pub fn back(&mut self) -> Option<(&K, &V)> { if self.is_empty() { return None } let mru = unsafe { (*self.head).next }; self.map .get(&KeyRef{k: unsafe { &(*mru).key }}) .map(|e| unsafe { (&(**e).key, &(**e).value) }) } /// Returns the number of key-value pairs in the map. pub fn len(&self) -> usize { self.map.len() } /// Returns whether the map is currently empty. pub fn is_empty(&self) -> bool { self.len() == 0 } /// Returns a reference to the map's hasher. pub fn hasher(&self) -> &S { self.map.hasher() } /// Clears the map of all key-value pairs. pub fn clear(&mut self) { self.map.clear(); // update the guard node if present if ! self.head.is_null() { unsafe { self.drop_entries(); (*self.head).prev = self.head; (*self.head).next = self.head; } } } /// Returns a double-ended iterator visiting all key-value pairs in order of insertion. /// Iterator element type is `(&'a K, &'a V)` /// /// # Examples /// ``` /// use linked_hash_map::LinkedHashMap; /// /// let mut map = LinkedHashMap::new(); /// map.insert("a", 10); /// map.insert("c", 30); /// map.insert("b", 20); /// /// let mut iter = map.iter(); /// assert_eq!((&"a", &10), iter.next().unwrap()); /// assert_eq!((&"c", &30), iter.next().unwrap()); /// assert_eq!((&"b", &20), iter.next().unwrap()); /// assert_eq!(None, iter.next()); /// ``` pub fn iter(&self) -> Iter { let head = if self.head.is_null() { ptr::null_mut() } else { unsafe { (*self.head).prev } }; Iter { head: head, tail: self.head, remaining: self.len(), marker: marker::PhantomData, } } /// Returns a double-ended iterator visiting all key-value pairs in order of insertion. /// Iterator element type is `(&'a K, &'a mut V)` /// # Examples /// ``` /// use linked_hash_map::LinkedHashMap; /// /// let mut map = LinkedHashMap::new(); /// map.insert("a", 10); /// map.insert("c", 30); /// map.insert("b", 20); /// /// { /// let mut iter = map.iter_mut(); /// let mut entry = iter.next().unwrap(); /// assert_eq!(&"a", entry.0); /// *entry.1 = 17; /// } /// /// assert_eq!(&17, map.get(&"a").unwrap()); /// ``` pub fn iter_mut(&mut self) -> IterMut { let head = if self.head.is_null() { ptr::null_mut() } else { unsafe { (*self.head).prev } }; IterMut { head: head, tail: self.head, remaining: self.len(), marker: marker::PhantomData, } } /// Returns a double-ended iterator visiting all key in order of insertion. /// /// # Examples /// ``` /// use linked_hash_map::LinkedHashMap; /// /// let mut map = LinkedHashMap::new(); /// map.insert('a', 10); /// map.insert('c', 30); /// map.insert('b', 20); /// /// let mut keys = map.keys(); /// assert_eq!(&'a', keys.next().unwrap()); /// assert_eq!(&'c', keys.next().unwrap()); /// assert_eq!(&'b', keys.next().unwrap()); /// assert_eq!(None, keys.next()); /// ``` pub fn keys(&self) -> Keys { Keys { inner: self.iter() } } /// Returns a double-ended iterator visiting all values in order of insertion. /// /// # Examples /// ``` /// use linked_hash_map::LinkedHashMap; /// /// let mut map = LinkedHashMap::new(); /// map.insert('a', 10); /// map.insert('c', 30); /// map.insert('b', 20); /// /// let mut values = map.values(); /// assert_eq!(&10, values.next().unwrap()); /// assert_eq!(&30, values.next().unwrap()); /// assert_eq!(&20, values.next().unwrap()); /// assert_eq!(None, values.next()); /// ``` pub fn values(&self) -> Values { Values { inner: self.iter() } } } impl<'a, K, V, S, Q: ?Sized> Index<&'a Q> for LinkedHashMap where K: Hash + Eq + Borrow, S: BuildHasher, Q: Eq + Hash { type Output = V; fn index(&self, index: &'a Q) -> &V { self.get(index).expect("no entry found for key") } } impl<'a, K, V, S, Q: ?Sized> IndexMut<&'a Q> for LinkedHashMap where K: Hash + Eq + Borrow, S: BuildHasher, Q: Eq + Hash { fn index_mut(&mut self, index: &'a Q) -> &mut V { self.get_mut(index).expect("no entry found for key") } } impl Clone for LinkedHashMap { fn clone(&self) -> Self { let mut map = Self::with_hasher(self.map.hasher().clone()); map.extend(self.iter().map(|(k, v)| (k.clone(), v.clone()))); map } } impl Default for LinkedHashMap { fn default() -> Self { Self::with_hasher(S::default()) } } impl Extend<(K, V)> for LinkedHashMap { fn extend>(&mut self, iter: I) { for (k, v) in iter { self.insert(k, v); } } } impl<'a, K, V, S> Extend<(&'a K, &'a V)> for LinkedHashMap where K: 'a + Hash + Eq + Copy, V: 'a + Copy, S: BuildHasher, { fn extend>(&mut self, iter: I) { for (&k, &v) in iter { self.insert(k, v); } } } impl iter::FromIterator<(K, V)> for LinkedHashMap { fn from_iter>(iter: I) -> Self { let iter = iter.into_iter(); let mut map = Self::with_capacity_and_hasher(iter.size_hint().0, S::default()); map.extend(iter); map } } impl fmt::Debug for LinkedHashMap { /// Returns a string that lists the key-value pairs in insertion order. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_map().entries(self).finish() } } impl PartialEq for LinkedHashMap { fn eq(&self, other: &Self) -> bool { self.len() == other.len() && self.iter().eq(other) } } impl Eq for LinkedHashMap {} impl PartialOrd for LinkedHashMap { fn partial_cmp(&self, other: &Self) -> Option { self.iter().partial_cmp(other) } fn lt(&self, other: &Self) -> bool { self.iter().lt(other) } fn le(&self, other: &Self) -> bool { self.iter().le(other) } fn ge(&self, other: &Self) -> bool { self.iter().ge(other) } fn gt(&self, other: &Self) -> bool { self.iter().gt(other) } } impl Ord for LinkedHashMap { fn cmp(&self, other: &Self) -> Ordering { self.iter().cmp(other) } } impl Hash for LinkedHashMap { fn hash(&self, h: &mut H) { for e in self.iter() { e.hash(h); } } } unsafe impl Send for LinkedHashMap {} unsafe impl Sync for LinkedHashMap {} impl Drop for LinkedHashMap { fn drop(&mut self) { if !self.head.is_null() { unsafe { self.drop_entries(); drop_empty_node(self.head); } } self.clear_free_list(); } } /// An insertion-order iterator over a `LinkedHashMap`'s entries, with immutable references to the /// values. pub struct Iter<'a, K: 'a, V: 'a> { head: *const Node, tail: *const Node, remaining: usize, marker: marker::PhantomData<(&'a K, &'a V)>, } /// An insertion-order iterator over a `LinkedHashMap`'s entries, with mutable references to the /// values. pub struct IterMut<'a, K: 'a, V: 'a> { head: *mut Node, tail: *mut Node, remaining: usize, marker: marker::PhantomData<(&'a K, &'a mut V)>, } /// A consuming insertion-order iterator over a `LinkedHashMap`'s entries. pub struct IntoIter { head: *mut Node, tail: *mut Node, remaining: usize, marker: marker::PhantomData<(K, V)>, } /// An insertion-order iterator over a `LinkedHashMap`'s entries represented as /// an `OccupiedEntry`. pub struct Entries<'a, K: 'a, V: 'a, S: 'a = hash_map::RandomState> { map: *mut LinkedHashMap, head: *mut Node, remaining: usize, marker: marker::PhantomData<(&'a K, &'a mut V, &'a S)>, } unsafe impl<'a, K, V> Send for Iter<'a, K, V> where K: Send, V: Send {} unsafe impl<'a, K, V> Send for IterMut<'a, K, V> where K: Send, V: Send {} unsafe impl Send for IntoIter where K: Send, V: Send {} unsafe impl<'a, K, V, S> Send for Entries<'a, K, V, S> where K: Send, V: Send, S: Send {} unsafe impl<'a, K, V> Sync for Iter<'a, K, V> where K: Sync, V: Sync {} unsafe impl<'a, K, V> Sync for IterMut<'a, K, V> where K: Sync, V: Sync {} unsafe impl Sync for IntoIter where K: Sync, V: Sync {} unsafe impl<'a, K, V, S> Sync for Entries<'a, K, V, S> where K: Sync, V: Sync, S: Sync {} impl<'a, K, V> Clone for Iter<'a, K, V> { fn clone(&self) -> Self { Iter { ..*self } } } impl Clone for IntoIter where K: Clone, V: Clone { fn clone(&self) -> Self { if self.remaining == 0 { return IntoIter { ..*self } } fn clone_node(e: *mut Node) -> *mut Node where K: Clone, V: Clone, { Box::into_raw(Box::new(Node::new( unsafe { (*e).key.clone() }, unsafe { (*e).value.clone() } ))) } let mut cur = self.head; let head = clone_node(cur); let mut tail = head; for _ in 1..self.remaining { unsafe { (*tail).prev = clone_node((*cur).prev); (*(*tail).prev).next = tail; tail = (*tail).prev; cur = (*cur).prev; } } IntoIter { head: head, tail: tail, remaining: self.remaining, marker: marker::PhantomData, } } } 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)> { if self.head == self.tail { None } else { self.remaining -= 1; unsafe { let r = Some((&(*self.head).key, &(*self.head).value)); self.head = (*self.head).prev; r } } } fn size_hint(&self) -> (usize, Option) { (self.remaining, Some(self.remaining)) } } 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)> { if self.head == self.tail { None } else { self.remaining -= 1; unsafe { let r = Some((&(*self.head).key, &mut (*self.head).value)); self.head = (*self.head).prev; r } } } fn size_hint(&self) -> (usize, Option) { (self.remaining, Some(self.remaining)) } } impl Iterator for IntoIter { type Item = (K, V); fn next(&mut self) -> Option<(K, V)> { if self.remaining == 0 { return None } self.remaining -= 1; unsafe { let prev = (*self.head).prev; let e = *Box::from_raw(self.head); self.head = prev; Some((e.key, e.value)) } } fn size_hint(&self) -> (usize, Option) { (self.remaining, Some(self.remaining)) } } impl<'a, K, V, S: BuildHasher> Iterator for Entries<'a, K, V, S> { type Item = OccupiedEntry<'a, K, V, S>; fn next(&mut self) -> Option> { if self.remaining == 0 { None } else { self.remaining -= 1; unsafe { let r = Some(OccupiedEntry { map: self.map, entry: self.head, marker: marker::PhantomData, }); self.head = (*self.head).prev; r } } } fn size_hint(&self) -> (usize, Option) { (self.remaining, Some(self.remaining)) } } impl<'a, K, V> DoubleEndedIterator for Iter<'a, K, V> { fn next_back(&mut self) -> Option<(&'a K, &'a V)> { if self.head == self.tail { None } else { self.remaining -= 1; unsafe { self.tail = (*self.tail).next; Some((&(*self.tail).key, &(*self.tail).value)) } } } } impl<'a, K, V> DoubleEndedIterator for IterMut<'a, K, V> { fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> { if self.head == self.tail { None } else { self.remaining -= 1; unsafe { self.tail = (*self.tail).next; Some((&(*self.tail).key, &mut (*self.tail).value)) } } } } impl DoubleEndedIterator for IntoIter { fn next_back(&mut self) -> Option<(K, V)> { if self.remaining == 0 { return None } self.remaining -= 1; unsafe { let next = (*self.tail).next; let e = *Box::from_raw(self.tail); self.tail = next; Some((e.key, e.value)) } } } impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> { fn len(&self) -> usize { self.remaining } } impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> { fn len(&self) -> usize { self.remaining } } impl ExactSizeIterator for IntoIter { fn len(&self) -> usize { self.remaining } } impl Drop for IntoIter { fn drop(&mut self) { for _ in 0..self.remaining { unsafe { let next = (*self.tail).next; Box::from_raw(self.tail); self.tail = next; } } } } /// An insertion-order iterator over a `LinkedHashMap`'s keys. pub struct Keys<'a, K: 'a, V: 'a> { inner: Iter<'a, K, V>, } impl<'a, K, V> Clone for Keys<'a, K, V> { fn clone(&self) -> Self { Keys { inner: self.inner.clone() } } } impl<'a, K, V> Iterator for Keys<'a, K, V> { type Item = &'a K; #[inline] fn next(&mut self) -> Option<&'a K> { self.inner.next().map(|e| e.0) } #[inline] fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } } impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> { #[inline] fn next_back(&mut self) -> Option<&'a K> { self.inner.next_back().map(|e| e.0) } } impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> { fn len(&self) -> usize { self.inner.len() } } /// An insertion-order iterator over a `LinkedHashMap`'s values. pub struct Values<'a, K: 'a, V: 'a> { inner: Iter<'a, K, V>, } impl<'a, K, V> Clone for Values<'a, K, V> { fn clone(&self) -> Self { Values { inner: self.inner.clone() } } } impl<'a, K, V> Iterator for Values<'a, K, V> { type Item = &'a V; #[inline] fn next(&mut self) -> Option<&'a V> { self.inner.next().map(|e| e.1) } #[inline] fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } } impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> { #[inline] fn next_back(&mut self) -> Option<&'a V> { self.inner.next_back().map(|e| e.1) } } impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> { fn len(&self) -> usize { self.inner.len() } } impl<'a, K: Hash + Eq, V, S: BuildHasher> IntoIterator for &'a LinkedHashMap { type Item = (&'a K, &'a V); type IntoIter = Iter<'a, K, V>; fn into_iter(self) -> Iter<'a, K, V> { self.iter() } } impl<'a, K: Hash + Eq, V, S: BuildHasher> IntoIterator for &'a mut LinkedHashMap { type Item = (&'a K, &'a mut V); type IntoIter = IterMut<'a, K, V>; fn into_iter(self) -> IterMut<'a, K, V> { self.iter_mut() } } impl IntoIterator for LinkedHashMap { type Item = (K, V); type IntoIter = IntoIter; fn into_iter(mut self) -> IntoIter { let (head, tail) = if !self.head.is_null() { unsafe { ((*self.head).prev, (*self.head).next) } } else { (ptr::null_mut(), ptr::null_mut()) }; let len = self.len(); if !self.head.is_null() { unsafe { drop_empty_node(self.head) } } self.clear_free_list(); // drop the HashMap but not the LinkedHashMap unsafe { ptr::drop_in_place(&mut self.map); } mem::forget(self); IntoIter { head: head, tail: tail, remaining: len, marker: marker::PhantomData, } } } /// A view into a single location in a map, which may be vacant or occupied. pub enum Entry<'a, K: 'a, V: 'a, S: 'a = hash_map::RandomState> { /// An occupied Entry. Occupied(OccupiedEntry<'a, K, V, S>), /// A vacant Entry. Vacant(VacantEntry<'a, K, V, S>), } /// A view into a single occupied location in a `LinkedHashMap`. pub struct OccupiedEntry<'a, K: 'a, V: 'a, S: 'a = hash_map::RandomState> { entry: *mut Node, map: *mut LinkedHashMap, marker: marker::PhantomData<&'a K>, } /// A view into a single empty location in a `LinkedHashMap`. pub struct VacantEntry<'a, K: 'a, V: 'a, S: 'a = hash_map::RandomState> { key: K, map: &'a mut LinkedHashMap, } impl<'a, K: Hash + Eq, V, S: BuildHasher> Entry<'a, K, V, S> { /// Returns the entry key /// /// # Examples /// /// ``` /// use linked_hash_map::LinkedHashMap; /// /// let mut map = LinkedHashMap::::new(); /// /// assert_eq!("hello", map.entry("hello".to_string()).key()); /// ``` pub fn key(&self) -> &K { match *self { Entry::Occupied(ref e) => e.key(), Entry::Vacant(ref e) => e.key(), } } /// Ensures a value is in the entry by inserting the default if empty, and returns /// a mutable reference to the value in the entry. pub fn or_insert(self, default: V) -> &'a mut V { match self { Entry::Occupied(entry) => entry.into_mut(), Entry::Vacant(entry) => entry.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. pub fn or_insert_with V>(self, default: F) -> &'a mut V { match self { Entry::Occupied(entry) => entry.into_mut(), Entry::Vacant(entry) => entry.insert(default()), } } } impl<'a, K: Hash + Eq, V, S: BuildHasher> OccupiedEntry<'a, K, V, S> { /// Gets a reference to the entry key /// /// # Examples /// /// ``` /// use linked_hash_map::LinkedHashMap; /// /// let mut map = LinkedHashMap::new(); /// /// map.insert("foo".to_string(), 1); /// assert_eq!("foo", map.entry("foo".to_string()).key()); /// ``` pub fn key(&self) -> &K { unsafe { &(*self.entry).key } } /// Gets a reference to the value in the entry. pub fn get(&self) -> &V { unsafe { &(*self.entry).value } } /// Gets a mutable reference to the value in the entry. pub fn get_mut(&mut self) -> &mut V { unsafe { &mut (*self.entry).value } } /// Converts the OccupiedEntry into a mutable reference to the value in the entry /// with a lifetime bound to the map itself pub fn into_mut(self) -> &'a mut V { unsafe { &mut (*self.entry).value } } /// Sets the value of the entry, and returns the entry's old value pub fn insert(&mut self, value: V) -> V { unsafe { (*self.map).ensure_guard_node(); let old_val = mem::replace(&mut (*self.entry).value, value); let node_ptr: *mut Node = self.entry; // Existing node, just update LRU position (*self.map).detach(node_ptr); (*self.map).attach(node_ptr); old_val } } /// Takes the value out of the entry, and returns it pub fn remove(self) -> V { unsafe { (*self.map).remove(&(*self.entry).key) }.unwrap() } } impl<'a, K: 'a + Hash + Eq, V: 'a, S: BuildHasher> VacantEntry<'a, K, V, S> { /// Gets a reference to the entry key /// /// # Examples /// /// ``` /// use linked_hash_map::LinkedHashMap; /// /// let mut map = LinkedHashMap::::new(); /// /// assert_eq!("foo", map.entry("foo".to_string()).key()); /// ``` pub fn key(&self) -> &K { &self.key } /// Sets the value of the entry with the VacantEntry's key, /// and returns a mutable reference to it pub fn insert(self, value: V) -> &'a mut V { self.map.ensure_guard_node(); let node = if self.map.free.is_null() { Box::into_raw(Box::new(Node::new(self.key, value))) } else { // use a recycled box unsafe { let free = self.map.free; self.map.free = (*free).next; ptr::write(free, Node::new(self.key, value)); free } }; let keyref = unsafe { &(*node).key }; self.map.attach(node); let ret = self.map.map.entry(KeyRef{k: keyref}).or_insert(node); unsafe { &mut (**ret).value } } } #[cfg(all(feature = "nightly", test))] mod bench { extern crate test; use super::LinkedHashMap; #[bench] fn not_recycled_cycling(b: &mut test::Bencher) { let mut hash_map = LinkedHashMap::with_capacity(1000); for i in 0usize..1000 { hash_map.insert(i, i); } b.iter(|| { for i in 0usize..1000 { hash_map.remove(&i); } hash_map.clear_free_list(); for i in 0usize..1000 { hash_map.insert(i, i); } }) } #[bench] fn recycled_cycling(b: &mut test::Bencher) { let mut hash_map = LinkedHashMap::with_capacity(1000); for i in 0usize..1000 { hash_map.insert(i, i); } b.iter(|| { for i in 0usize..1000 { hash_map.remove(&i); } for i in 0usize..1000 { hash_map.insert(i, i); } }) } } linked-hash-map-0.5.4/src/serde.rs000064400000000000000000000046611377613357400150760ustar 00000000000000//! An optional implementation of serialization/deserialization. extern crate serde; use std::fmt::{Formatter, Result as FmtResult}; use std::marker::PhantomData; use std::hash::{BuildHasher, Hash}; use super::LinkedHashMap; use self::serde::{Serialize, Serializer, Deserialize, Deserializer}; use self::serde::ser::SerializeMap; use self::serde::de::{Visitor, MapAccess, Error}; impl Serialize for LinkedHashMap where K: Serialize + Eq + Hash, V: Serialize, S: BuildHasher { #[inline] fn serialize(&self, serializer:T) -> Result where T: Serializer, { let mut map_serializer = try!(serializer.serialize_map(Some(self.len()))); for (k, v) in self { try!(map_serializer.serialize_key(k)); try!(map_serializer.serialize_value(v)); } map_serializer.end() } } #[derive(Debug)] /// `serde::de::Visitor` for a linked hash map. pub struct LinkedHashMapVisitor { marker: PhantomData>, } impl LinkedHashMapVisitor { /// Creates a new visitor for a linked hash map. pub fn new() -> Self { LinkedHashMapVisitor { marker: PhantomData, } } } impl Default for LinkedHashMapVisitor { fn default() -> Self { LinkedHashMapVisitor::new() } } impl<'de, K, V> Visitor<'de> for LinkedHashMapVisitor where K: Deserialize<'de> + Eq + Hash, V: Deserialize<'de>, { type Value = LinkedHashMap; fn expecting(&self, formatter: &mut Formatter) -> FmtResult { write!(formatter, "a map") } #[inline] fn visit_unit(self) -> Result where E: Error, { Ok(LinkedHashMap::new()) } #[inline] fn visit_map(self, mut map: M) -> Result where M: MapAccess<'de>, { let mut values = LinkedHashMap::with_capacity(map.size_hint().unwrap_or(0)); while let Some((key, value)) = map.next_entry()? { values.insert(key, value); } Ok(values) } } impl<'de, K, V> Deserialize<'de> for LinkedHashMap where K: Deserialize<'de> + Eq + Hash, V: Deserialize<'de>, { fn deserialize(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_map(LinkedHashMapVisitor::new()) } } linked-hash-map-0.5.4/tests/heapsize.rs000064400000000000000000000010761377613357400161540ustar 00000000000000#![cfg(feature = "heapsize_impl")] extern crate heapsize; extern crate linked_hash_map; use linked_hash_map::LinkedHashMap; use heapsize::HeapSizeOf; #[test] fn empty() { assert_eq!(LinkedHashMap::::new().heap_size_of_children(), 0); } #[test] fn nonempty() { let mut map = LinkedHashMap::new(); map.insert("hello".to_string(), "world".to_string()); map.insert("hola".to_string(), "mundo".to_string()); map.insert("bonjour".to_string(), "monde".to_string()); map.remove("hello"); assert!(map.heap_size_of_children() != 0); } linked-hash-map-0.5.4/tests/serde.rs000064400000000000000000000013731377613357400154460ustar 00000000000000#![cfg(feature = "serde_impl")] extern crate linked_hash_map; use linked_hash_map::LinkedHashMap; extern crate serde_test; use serde_test::{Token, assert_tokens}; #[test] fn test_ser_de_empty() { let map = LinkedHashMap::::new(); assert_tokens(&map, &[ Token::Map { len: Some(0) }, Token::MapEnd, ]); } #[test] fn test_ser_de() { let mut map = LinkedHashMap::new(); map.insert('b', 20); map.insert('a', 10); map.insert('c', 30); assert_tokens(&map, &[ Token::Map { len: Some(3) }, Token::Char('b'), Token::I32(20), Token::Char('a'), Token::I32(10), Token::Char('c'), Token::I32(30), Token::MapEnd, ]); } linked-hash-map-0.5.4/tests/test.rs000064400000000000000000000254671377613357400153350ustar 00000000000000extern crate linked_hash_map; use linked_hash_map::{LinkedHashMap, Entry}; fn assert_opt_eq(opt: Option<&V>, v: V) { assert!(opt.is_some()); assert!(opt.unwrap() == &v); } #[test] fn test_insert_and_get() { let mut map = LinkedHashMap::new(); map.insert(1, 10); map.insert(2, 20); assert_opt_eq(map.get(&1), 10); assert_opt_eq(map.get(&2), 20); assert_eq!(map.len(), 2); } #[test] fn test_index() { let mut map = LinkedHashMap::new(); map.insert(1, 10); map.insert(2, 20); assert_eq!(10, map[&1]); map[&2] = 22; assert_eq!(22, map[&2]); } #[test] fn test_insert_update() { let mut map = LinkedHashMap::new(); map.insert("1".to_string(), vec![10, 10]); map.insert("1".to_string(), vec![10, 19]); assert_opt_eq(map.get(&"1".to_string()), vec![10, 19]); assert_eq!(map.len(), 1); } #[test] fn test_entry_insert_vacant() { let mut map = LinkedHashMap::new(); match map.entry("1".to_string()) { Entry::Vacant(e) => { assert_eq!(*e.insert(vec![10, 10]), vec![10, 10]); } _ => panic!("fail"), } assert!(map.contains_key("1")); assert_eq!(map["1"], vec![10, 10]); match map.entry("1".to_string()) { Entry::Occupied(mut e) => { assert_eq!(*e.get(), vec![10, 10]); assert_eq!(e.insert(vec![10, 16]), vec![10, 10]); } _ => panic!("fail"), } assert!(map.contains_key("1")); assert_eq!(map["1"], vec![10, 16]); match map.entry("1".to_string()) { Entry::Occupied(e) => { assert_eq!(e.remove(), vec![10, 16]); } _ => panic!("fail"), } } #[test] fn test_entries_replacing() { let mut map = LinkedHashMap::new(); map.insert("a", 10); { let mut iter = map.entries(); let mut entry = iter.next().unwrap(); assert_eq!(entry.insert(20), 10); assert!(iter.next().is_none()); } assert_eq!(map["a"], 20); } #[test] fn test_entries_remove() { let mut map = LinkedHashMap::new(); map.insert("a", 10); map.insert("b", 20); map.insert("c", 30); map.insert("d", 40); // remove middle { let mut iter = map.entries(); iter.next().unwrap(); let b = iter.next().unwrap(); assert_eq!(*b.key(), "b"); assert_eq!(b.remove(), 20); assert_eq!(*iter.next().unwrap().key(), "c"); } assert_eq!(map.len(), 3); assert_eq!(map["a"], 10); assert_eq!(map["c"], 30); assert_eq!(map["d"], 40); // remove first { let mut iter = map.entries(); let a = iter.next().unwrap(); assert_eq!(*a.key(), "a"); assert_eq!(a.remove(), 10); } assert_eq!(map.len(), 2); assert_eq!(map["c"], 30); assert_eq!(map["d"], 40); // remove last { let mut iter = map.entries(); iter.next().unwrap(); let d = iter.next().unwrap(); assert_eq!(*d.key(), "d"); assert_eq!(d.remove(), 40); assert!(iter.next().is_none()); } assert_eq!(map.len(), 1); assert_eq!(map["c"], 30); // remove only { let mut iter = map.entries(); let c = iter.next().unwrap(); assert_eq!(*c.key(), "c"); assert_eq!(c.remove(), 30); } assert!(map.is_empty()); } #[test] fn entries_insert() { let mut map = LinkedHashMap::new(); map.insert(0, 0); map.insert(1, 1); let mut iter = map.entries(); iter.next().unwrap().insert(0); iter.next().unwrap(); // 1 assert!(iter.next().is_none()); } #[test] fn test_debug() { let mut map = LinkedHashMap::new(); assert_eq!(format!("{:?}", map), "{}"); map.insert(1, 10); map.insert(2, 20); map.insert(3, 30); assert_eq!(format!("{:?}", map), "{1: 10, 2: 20, 3: 30}"); map.insert(2, 22); assert_eq!(format!("{:?}", map), "{1: 10, 3: 30, 2: 22}"); map.get(&3); assert_eq!(format!("{:?}", map), "{1: 10, 3: 30, 2: 22}"); map.get_refresh(&mut 3); assert_eq!(format!("{:?}", map), "{1: 10, 2: 22, 3: 30}"); map.clear(); assert_eq!(format!("{:?}", map), "{}"); } #[test] fn test_remove() { let mut map = LinkedHashMap::new(); map.insert(1, 10); map.insert(2, 20); map.insert(3, 30); map.insert(4, 40); map.insert(5, 50); map.remove(&3); map.remove(&4); assert!(map.get(&3).is_none()); assert!(map.get(&4).is_none()); map.insert(6, 60); map.insert(7, 70); map.insert(8, 80); assert_opt_eq(map.get(&6), 60); assert_opt_eq(map.get(&7), 70); assert_opt_eq(map.get(&8), 80); } #[test] fn test_pop() { let mut map = LinkedHashMap::new(); map.insert(1, 10); map.insert(2, 20); map.insert(3, 30); map.insert(4, 40); map.insert(5, 50); assert_eq!(map.pop_front(), Some((1, 10))); assert!(map.get(&1).is_none()); assert_eq!(map.pop_back(), Some((5, 50))); assert!(map.get(&5).is_none()); map.insert(6, 60); map.insert(7, 70); map.insert(8, 80); assert_eq!(map.pop_front(), Some((2, 20))); assert!(map.get(&2).is_none()); assert_eq!(map.pop_back(), Some((8, 80))); assert!(map.get(&8).is_none()); map.insert(3, 30); assert_eq!(map.pop_front(), Some((4, 40))); assert!(map.get(&4).is_none()); assert_eq!(map.pop_back(), Some((3, 30))); assert!(map.get(&3).is_none()); } #[test] fn test_clear() { let mut map = LinkedHashMap::new(); map.insert(1, 10); map.insert(2, 20); map.clear(); assert!(map.get(&1).is_none()); assert!(map.get(&2).is_none()); assert_eq!(format!("{:?}", map), "{}"); } #[test] fn test_iter() { let mut map = LinkedHashMap::new(); // empty iter assert_eq!(None, map.iter().next()); map.insert("a", 10); map.insert("b", 20); map.insert("c", 30); // regular iter let mut iter = map.iter(); assert_eq!((&"a", &10), iter.next().unwrap()); assert_eq!((&"b", &20), iter.next().unwrap()); assert_eq!((&"c", &30), iter.next().unwrap()); assert_eq!(None, iter.next()); assert_eq!(None, iter.next()); // reversed iter let mut rev_iter = map.iter().rev(); assert_eq!((&"c", &30), rev_iter.next().unwrap()); assert_eq!((&"b", &20), rev_iter.next().unwrap()); assert_eq!((&"a", &10), rev_iter.next().unwrap()); assert_eq!(None, rev_iter.next()); assert_eq!(None, rev_iter.next()); // mixed let mut mixed_iter = map.iter(); assert_eq!((&"a", &10), mixed_iter.next().unwrap()); assert_eq!((&"c", &30), mixed_iter.next_back().unwrap()); assert_eq!((&"b", &20), mixed_iter.next().unwrap()); assert_eq!(None, mixed_iter.next()); assert_eq!(None, mixed_iter.next_back()); } #[test] fn test_iter_mut() { let mut map = LinkedHashMap::new(); map.insert("a", 10); map.insert("c", 30); map.insert("b", 20); { let mut iter = map.iter_mut(); let entry = iter.next().unwrap(); assert_eq!(&"a", entry.0); *entry.1 = 17; // reverse iterator let mut iter = iter.rev(); let entry = iter.next().unwrap(); assert_eq!(&"b", entry.0); *entry.1 = 23; let entry = iter.next().unwrap(); assert_eq!(&"c", entry.0); assert_eq!(None, iter.next()); assert_eq!(None, iter.next()); } assert_eq!(17, map[&"a"]); assert_eq!(23, map[&"b"]); } #[test] fn test_consuming_iter() { let map = { let mut map = LinkedHashMap::new(); map.insert("a", 10); map.insert("c", 30); map.insert("b", 20); map }; let mut iter = map.into_iter(); assert_eq!(Some(("a", 10)), iter.next()); let clone = iter.clone(); for iter in &mut [iter, clone] { assert_eq!(Some(("b", 20)), iter.next_back()); assert_eq!(1, iter.len()); assert_eq!(Some(("c", 30)), iter.next()); assert_eq!(None, iter.next()); } } #[test] fn test_consuming_iter_empty() { let map = LinkedHashMap::<&str, i32>::new(); let mut iter = map.into_iter(); assert_eq!(None, iter.next()); let mut clone = iter.clone(); assert_eq!(None, clone.next()); } #[test] fn test_consuming_iter_with_free_list() { let mut map = LinkedHashMap::new(); map.insert("a", 10); map.insert("c", 30); map.insert("b", 20); map.remove("a"); map.remove("b"); let mut iter = map.into_iter(); assert_eq!(Some(("c", 30)), iter.next()); assert_eq!(None, iter.next()); } #[test] fn test_into_iter_drop() { struct Counter<'a>(&'a mut usize); impl<'a> Drop for Counter<'a> { fn drop(&mut self) { *self.0 += 1; } } let mut a = 0; let mut b = 0; let mut c = 0; { let mut map = LinkedHashMap::new(); map.insert("a", Counter(&mut a)); map.insert("b", Counter(&mut b)); map.insert("c", Counter(&mut c)); let mut iter = map.into_iter(); iter.next(); iter.next_back(); } assert_eq!(a, 1); assert_eq!(b, 1); assert_eq!(c, 1); } #[test] fn test_borrow() { #[derive(PartialEq, Eq, Hash)] struct Foo(Bar); #[derive(PartialEq, Eq, Hash)] struct Bar(i32); impl ::std::borrow::Borrow for Foo { fn borrow(&self) -> &Bar { &self.0 } } let mut map = LinkedHashMap::new(); map.insert(Foo(Bar(1)), "a"); map.insert(Foo(Bar(2)), "b"); assert!(map.contains_key(&Bar(1))); assert!(map.contains_key(&Bar(2))); assert!(map.contains_key(&Foo(Bar(1)))); assert!(map.contains_key(&Foo(Bar(2)))); assert_eq!(map.get(&Bar(1)), Some(&"a")); assert_eq!(map.get(&Bar(2)), Some(&"b")); assert_eq!(map.get(&Foo(Bar(1))), Some(&"a")); assert_eq!(map.get(&Foo(Bar(2))), Some(&"b")); assert_eq!(map.get_refresh(&Bar(1)), Some(&mut "a")); assert_eq!(map.get_refresh(&Bar(2)), Some(&mut "b")); assert_eq!(map.get_refresh(&Foo(Bar(1))), Some(&mut "a")); assert_eq!(map.get_refresh(&Foo(Bar(2))), Some(&mut "b")); assert_eq!(map.get_mut(&Bar(1)), Some(&mut "a")); assert_eq!(map.get_mut(&Bar(2)), Some(&mut "b")); assert_eq!(map.get_mut(&Foo(Bar(1))), Some(&mut "a")); assert_eq!(map.get_mut(&Foo(Bar(2))), Some(&mut "b")); assert_eq!(map[&Bar(1)], "a"); assert_eq!(map[&Bar(2)], "b"); assert_eq!(map[&Foo(Bar(1))], "a"); assert_eq!(map[&Foo(Bar(2))], "b"); assert_eq!(map.remove(&Bar(1)), Some("a")); assert_eq!(map.remove(&Bar(2)), Some("b")); assert_eq!(map.remove(&Foo(Bar(1))), None); assert_eq!(map.remove(&Foo(Bar(2))), None); } #[test] fn test_send_sync() { fn is_send_sync() {} is_send_sync::>(); is_send_sync::>(); is_send_sync::>(); is_send_sync::>(); is_send_sync::>(); is_send_sync::>(); }