linear-map-1.2.0/.gitignore01006440000766000002400000000022125311320240013732 0ustar0000000000000000target Cargo.lock linear-map-1.2.0/.travis.yml01006440000766000002400000000757131361562530014106 0ustar0000000000000000language: rust sudo: false matrix: include: - rust: stable env: FEATURES="serde_impl" - rust: nightly env: FEATURES="serde_impl nightly" script: - cargo build --features "$FEATURES" - cargo test --features "$FEATURES" - cargo doc --no-deps after_success: | [ "$TRAVIS_RUST_VERSION" = nightly ] && [ "$TRAVIS_BRANCH" = master ] && [ "$TRAVIS_PULL_REQUEST" = false ] && bash deploy-docs.sh notifications: webhooks: http://huon.me:54857/travis linear-map-1.2.0/benches/bench.rs01006440000766000002400000005254131361562530015026 0ustar0000000000000000#![feature(test)] extern crate linear_map; extern crate test; use linear_map::LinearMap; const SMALL: u32 = 10; const MEDIUM: u32 = 100; const BIG: u32 = 1000; fn insert(b: &mut test::Bencher, num: u32) { b.iter(|| { let mut map = LinearMap::new(); for i in 0..num { map.insert(i, i); } }) } fn remove_insert(b: &mut test::Bencher, num: u32) { b.iter(|| { let mut map = LinearMap::new(); for i in 0..num { map.insert(i, i); } for i in 0..num { map.remove(&i); } }) } fn remove_rev_insert(b: &mut test::Bencher, num: u32) { b.iter(|| { let mut map = LinearMap::new(); for i in 0..num { map.insert(i, i); } for i in 0..num { map.remove(&(num - i - 1)); } }) } fn get_middle(b: &mut test::Bencher, num: u32) { let mut map = LinearMap::new(); for i in 0..num { map.insert(i, i); } let middle = num / 2; b.iter(|| { test::black_box(map.get(&middle)); test::black_box(map.get_mut(&middle)); }) } fn get_none(b: &mut test::Bencher, num: u32) { let mut map = LinearMap::new(); for i in 0..num { map.insert(i, i); } let none = num + 1; b.iter(|| { test::black_box(map.get(&none)); test::black_box(map.get_mut(&none)); }) } #[bench] fn bench_insert_small (b: &mut test::Bencher) { insert(b, SMALL); } #[bench] fn bench_insert_medium(b: &mut test::Bencher) { insert(b, MEDIUM); } #[bench] fn bench_insert_big (b: &mut test::Bencher) { insert(b, BIG); } #[bench] fn bench_remove_insert_small (b: &mut test::Bencher) { remove_insert(b, SMALL); } #[bench] fn bench_remove_insert_medium(b: &mut test::Bencher) { remove_insert(b, MEDIUM); } #[bench] fn bench_remove_insert_big (b: &mut test::Bencher) { remove_insert(b, BIG); } #[bench] fn bench_remove_rev_insert_small (b: &mut test::Bencher) { remove_rev_insert(b, SMALL); } #[bench] fn bench_remove_rev_insert_medium(b: &mut test::Bencher) { remove_rev_insert(b, MEDIUM); } #[bench] fn bench_remove_rev_insert_big (b: &mut test::Bencher) { remove_rev_insert(b, BIG); } #[bench] fn bench_get_middle_small (b: &mut test::Bencher) { get_middle(b, SMALL); } #[bench] fn bench_get_middle_medium(b: &mut test::Bencher) { get_middle(b, MEDIUM); } #[bench] fn bench_get_middle_big (b: &mut test::Bencher) { get_middle(b, BIG); } #[bench] fn bench_get_none_small (b: &mut test::Bencher) { get_none(b, SMALL); } #[bench] fn bench_get_none_medium(b: &mut test::Bencher) { get_none(b, MEDIUM); } #[bench] fn bench_get_none_big (b: &mut test::Bencher) { get_none(b, BIG); } linear-map-1.2.0/Cargo.toml.orig01006440000766000002400000001201131361562650014650 0ustar0000000000000000[package] name = "linear-map" version = "1.2.0" license = "MIT/Apache-2.0" description = "A map implemented by searching linearly in a vector." authors = [ "Andrew Paseltiner ", "Tobias Bucher ", ] repository = "https://github.com/contain-rs/linear-map" documentation = "https://contain-rs.github.io/linear-map/linear_map" keywords = ["data-structures"] readme = "README.md" [features] nightly = [] serde_impl = ["serde", "serde_test"] [dependencies] serde = { version = "1.0", optional = true } serde_test = { version = "1.0", optional = true } [lib] test = false bench = false linear-map-1.2.0/Cargo.toml0000644000000022030010073 0ustar00# 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 = "linear-map" version = "1.2.0" authors = ["Andrew Paseltiner ", "Tobias Bucher "] description = "A map implemented by searching linearly in a vector." documentation = "https://contain-rs.github.io/linear-map/linear_map" readme = "README.md" keywords = ["data-structures"] license = "MIT/Apache-2.0" repository = "https://github.com/contain-rs/linear-map" [lib] test = false bench = false [dependencies.serde] version = "1.0" optional = true [dependencies.serde_test] version = "1.0" optional = true [features] nightly = [] serde_impl = ["serde", "serde_test"] linear-map-1.2.0/deploy-docs.sh01007550000766000002400000000650125311320240014532 0ustar0000000000000000#!/bin/bash set -o errexit -o nounset rev=$(git rev-parse --short HEAD) cd target/doc git init git config user.email 'FlashCat@users.noreply.github.com' git config user.name 'FlashCat' git remote add upstream "https://${GH_TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git" git fetch upstream gh-pages git reset upstream/gh-pages touch . git add -A . git commit -m "rebuild pages at ${rev}" git push -q upstream HEAD:gh-pages linear-map-1.2.0/LICENSE-APACHE01006440000766000002400000025142125311320240013700 0ustar0000000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. linear-map-1.2.0/LICENSE-MIT01006440000766000002400000002057125311320240013410 0ustar0000000000000000Copyright (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. linear-map-1.2.0/README.md01006440000766000002400000000210131361562530013234 0ustar0000000000000000A map implemented by searching linearly in a vector. Documentation is available at https://contain-rs.github.io/linear-map/linear_map. linear-map-1.2.0/src/lib.rs01006440000766000002400000046752131361562530013705 0ustar0000000000000000//! A map implemented by searching linearly in a vector. //! //! See the [`LinearMap`](struct.LinearMap.html) type for details. #![deny(missing_docs)] // Optional Serde support #[cfg(feature = "serde_impl")] pub mod serde; pub mod set; use std::borrow::Borrow; use std::fmt::{self, Debug}; use std::iter; use std::mem; use std::ops; use std::slice; use std::vec; use self::Entry::{Occupied, Vacant}; /// A map implemented by searching linearly in a vector. /// /// `LinearMap`'s keys are compared using the [`Eq`][eq] trait. All search operations /// (`contains_key`, `get`, `get_mut`, `insert`, and `remove`) run in `O(n)` time, making this /// implementation suitable only for small numbers of keys. The ordering of the keys in the /// underlying vector is arbitrary. /// /// It is a logic error for a key to be modified in such a way that the key's equality, as /// determined by the [`Eq`][eq] trait, changes while it is in the map. This is normally only /// possible through [`Cell`][cell], [`RefCell`][ref_cell], global state, I/O, or unsafe code. /// /// [cell]: https://doc.rust-lang.org/nightly/std/cell/struct.Cell.html /// [eq]: https://doc.rust-lang.org/nightly/std/cmp/trait.Eq.html /// [ref_cell]: https://doc.rust-lang.org/nightly/std/cell/struct.RefCell.html /// /// # Example /// /// ``` /// use linear_map::LinearMap; /// /// // type inference lets us omit an explicit type signature (which /// // would be `LinearMap<&str, &str>` in this example). /// let mut book_reviews = LinearMap::new(); /// /// // review some books. /// book_reviews.insert("Adventures of Huckleberry Finn", "My favorite book."); /// book_reviews.insert("Grimms' Fairy Tales", "Masterpiece."); /// book_reviews.insert("Pride and Prejudice", "Very enjoyable."); /// book_reviews.insert("The Adventures of Sherlock Holmes", "Eye lyked it alot."); /// /// // check for a specific one. /// if !book_reviews.contains_key("Les Misérables") { /// println!("We've got {} reviews, but Les Misérables ain't one.", /// book_reviews.len()); /// } /// /// // oops, this review has a lot of spelling mistakes. let's delete it. /// book_reviews.remove("The Adventures of Sherlock Holmes"); /// /// // look up the values associated with some keys. /// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"]; /// for book in &to_find { /// match book_reviews.get(book) { /// Some(review) => println!("{}: {}", book, review), /// None => println!("{} is unreviewed.", book) /// } /// } /// /// // iterate over everything. /// for (book, review) in &book_reviews { /// println!("{}: \"{}\"", book, review); /// } /// ``` pub struct LinearMap { storage: Vec<(K, V)>, } impl LinearMap { /// Creates an empty map. This method does not allocate. pub fn new() -> Self { LinearMap { storage: vec![] } } /// Creates an empty map with the given initial capacity. pub fn with_capacity(capacity: usize) -> Self { LinearMap { storage: Vec::with_capacity(capacity) } } /// Returns the number of elements the map can hold without reallocating. pub fn capacity(&self) -> usize { self.storage.capacity() } /// Reserves capacity for at least `additional` more to be inserted in the /// map. The collection may reserve more space to avoid frequent /// reallocations. /// /// # Panics /// /// Panics if the new allocation size overflows `usize`. pub fn reserve(&mut self, additional: usize) { self.storage.reserve(additional); } /// Reserves the minimum capacity for exactly `additional` more elemnnts to /// be inserted in the map. /// /// Note that the allocator may give the collection more space than it /// requests. Therefore capacity cannot be relied upon to be precisely /// minimal. Prefer `reserve` if future insertions are expected. /// /// # Panics /// /// Panics if the new capacity overflows `usize`. pub fn reserve_exact(&mut self, additional: usize) { self.storage.reserve_exact(additional); } /// Shrinks the capacity of the map as much as possible. /// /// It will drop down as close as possible to the current length but the /// allocator may still inform the map that there is more space than /// necessary. Therefore capacity cannot be relid upon to be minimal. pub fn shrink_to_fit(&mut self) { self.storage.shrink_to_fit(); } /// Returns the number of elements in the map. pub fn len(&self) -> usize { self.storage.len() } /// Returns true if the map contains no elements. pub fn is_empty(&self) -> bool { self.storage.is_empty() } /// Clears the map, removing all elements. Keeps the allocated memory for /// reuse. pub fn clear(&mut self) { self.storage.clear(); } /// Scan through the map and keep those key-value pairs where the /// closure returns `true`. /// /// The order the elements are visited is not specified. pub fn retain(&mut self, mut keep_fn: F) where F: FnMut(&K, &mut V) -> bool { let mut del = 0; { let v = &mut *self.storage; for i in 0..v.len() { if !keep_fn(&v[i].0, &mut v[i].1) { del += 1; } else if del > 0 { v.swap(i - del, i); } } } if del > 0 { let len = self.storage.len(); self.storage.truncate(len - del); } } /// Removes all key-value pairs from the map and returns an iterator that yields them in /// arbitrary order. /// /// All key-value pairs are removed even if the iterator is not exhausted. However, the /// behavior of this method is unspecified if the iterator is leaked. /// /// The iterator's item type is `(K, V)`. pub fn drain(&mut self) -> Drain { Drain { iter: self.storage.drain(..) } } /// Returns an iterator yielding references to the map's keys and their corresponding values in /// arbitrary order. /// /// The iterator's item type is `(&K, &V)`. pub fn iter(&self) -> Iter { Iter { iter: self.storage.iter() } } /// Returns an iterator yielding references to the map's keys and mutable references to their /// corresponding values in arbitrary order. /// /// The iterator's item type is `(&K, &mut V)`. pub fn iter_mut(&mut self) -> IterMut { IterMut { iter: self.storage.iter_mut() } } /// Returns an iterator yielding references to the map's keys in arbitrary order. /// /// The iterator's item type is `&K`. pub fn keys(&self) -> Keys { Keys { iter: self.iter() } } /// Returns an iterator yielding references to the map's values in arbitrary order. /// /// The iterator's item type is `&V`. pub fn values(&self) -> Values { Values { iter: self.iter() } } /// Returns a reference to the value in the map whose key is equal to the given key. /// /// Returns `None` if the map contains no such key. /// /// The given key may be any borrowed form of the map's key type, but `Eq` on the borrowed form /// *must* match that of the key type. pub fn get(&self, key: &Q) -> Option<&V> where K: Borrow { for (k, v) in self { if key == k.borrow() { return Some(v); } } None } /// Returns a mutable reference to the value in the map whose key is equal to the given key. /// /// Returns `None` if the map contains no such key. /// /// The given key may be any borrowed form of the map's key type, but `Eq` on the borrowed form /// *must* match that of the key type. pub fn get_mut(&mut self, key: &Q) -> Option<&mut V> where K: Borrow { for (k, v) in self { if key == k.borrow() { return Some(v); } } None } /// Checks if the map contains a key that is equal to the given key. /// /// The given key may be any borrowed form of the map's key type, but `Eq` on the borrowed form /// *must* match that of the key type. pub fn contains_key(&self, key: &Q) -> bool where K: Borrow { self.get(key).is_some() } /// Inserts a key-value pair into the map. /// /// Returns `None` if the map did not contain a key that is equal to the given key. /// /// If the map did contain such a key, its corresponding value is replaced with the given /// value, and the old value is returned. The key is not updated, though. This matters for /// values that can be `==` without being identical. See the [standard library's documentation] /// [std] for more details. /// /// [std]: https://doc.rust-lang.org/nightly/std/collections/index.html#insert-and-complex-keys pub fn insert(&mut self, key: K, value: V) -> Option { match self.entry(key) { Occupied(mut e) => Some(e.insert(value)), Vacant(e) => { e.insert(value); None } } } /// Removes the key in the map that is equal to the given key and returns its corresponding /// value. /// /// Returns `None` if the map contained no such key. /// /// The given key may be any borrowed form of the map's key type, but `Eq` on the borrowed form /// *must* match that of the key type. pub fn remove(&mut self, key: &Q) -> Option where K: Borrow { for i in 0..self.storage.len() { if self.storage[i].0.borrow() == key { return Some(self.storage.swap_remove(i).1); } } None } /// Returns the given key's corresponding entry in the map for in-place manipulation. pub fn entry(&mut self, key: K) -> Entry { match self.storage.iter().position(|&(ref k, _)| key == *k) { None => Vacant(VacantEntry { map: self, key: key }), Some(index) => Occupied(OccupiedEntry { map: self, index: index }) } } } impl Clone for LinearMap { fn clone(&self) -> Self { LinearMap { storage: self.storage.clone() } } fn clone_from(&mut self, other: &Self) { self.storage.clone_from(&other.storage); } } impl Debug for LinearMap { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_map().entries(self).finish() } } impl Default for LinearMap { fn default() -> Self { Self::new() } } impl Extend<(K, V)> for LinearMap { fn extend>(&mut self, key_values: I) { for (key, value) in key_values { self.insert(key, value); } } } impl iter::FromIterator<(K, V)> for LinearMap { fn from_iter>(key_values: I) -> Self { let mut map = Self::new(); map.extend(key_values); map } } impl<'a, K: Eq + Borrow, V, Q: ?Sized + Eq> ops::Index<&'a Q> for LinearMap { type Output = V; fn index(&self, key: &'a Q) -> &V { self.get(key).expect("key not found") } } impl PartialEq for LinearMap { fn eq(&self, other: &Self) -> bool { if self.len() != other.len() { return false; } for (key, value) in self { if other.get(key) != Some(value) { return false; } } true } } impl Eq for LinearMap {} impl Into> for LinearMap { fn into(self) -> Vec<(K, V)> { self.storage } } /// Creates a `LinearMap` from a list of key-value pairs. /// /// The created `LinearMap` has a capacity set to the number of entries provided. /// /// # Example /// /// ``` /// #[macro_use] extern crate linear_map; /// # fn main() { /// /// let map = linear_map!{ /// "a" => 1, /// "b" => 2, /// }; /// assert_eq!(map["a"], 1); /// assert_eq!(map["b"], 2); /// assert_eq!(map.get("c"), None); /// # } /// ``` #[macro_export] macro_rules! linear_map { ($($key:expr => $value:expr,)+) => { linear_map!($($key => $value),+) }; ($($key:expr => $value:expr),*) => { { let _cap = <[&str]>::len(&[$(stringify!($key)),*]); let mut _map = $crate::LinearMap::with_capacity(_cap); $( _map.insert($key, $value); )* _map } }; } /// A view into a single occupied location in a `LinearMap`. /// /// See [`LinearMap::entry`](struct.LinearMap.html#method.entry) for details. pub struct OccupiedEntry<'a, K: 'a, V: 'a> { map: &'a mut LinearMap, index: usize, } /// A view into a single vacant location in a `LinearMap`. /// /// See [`LinearMap::entry`](struct.LinearMap.html#method.entry) for details. pub struct VacantEntry<'a, K: 'a, V: 'a> { map: &'a mut LinearMap, key: K, } /// A view into a single entry in a `LinearMap`. /// /// See [`LinearMap::entry`](struct.LinearMap.html#method.entry) for details. 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, V> Entry<'a, K, V> { /// Ensures that the entry is occupied by inserting the given value if it is vacant. /// /// Returns a mutable reference to the entry's value. pub fn or_insert(self, default: V) -> &'a mut V { match self { Occupied(entry) => entry.into_mut(), Vacant(entry) => entry.insert(default) } } /// Ensures that the entry is occupied by inserting the the result of the given function if it /// is vacant. /// /// Returns a mutable reference to the entry's value. pub fn or_insert_with V>(self, default: F) -> &'a mut V { match self { Occupied(entry) => entry.into_mut(), Vacant(entry) => entry.insert(default()) } } } impl<'a, K, V> OccupiedEntry<'a, K, V> { /// Returns a reference to the entry's value. pub fn get(&self) -> &V { &self.map.storage[self.index].1 } /// Returns a mutable reference to the entry's value. pub fn get_mut(&mut self) -> &mut V { &mut self.map.storage[self.index].1 } /// Returns a mutable reference to the entry's value with the same lifetime as the map. pub fn into_mut(self) -> &'a mut V { &mut self.map.storage[self.index].1 } /// Replaces the entry's value with the given one and returns the previous value. pub fn insert(&mut self, value: V) -> V { mem::replace(self.get_mut(), value) } /// Removes the entry from the map and returns its value. pub fn remove(self) -> V { self.map.storage.swap_remove(self.index).1 } } impl<'a, K, V> VacantEntry<'a, K, V> { /// Inserts the entry into the map with the given value. /// /// Returns a mutable reference to the entry's value with the same lifetime as the map. pub fn insert(self, value: V) -> &'a mut V { self.map.storage.push((self.key, value)); &mut self.map.storage.last_mut().unwrap().1 } } /// A consuming iterator over a `LinearMap`. /// /// The iterator's order is arbitrary. /// /// Acquire through [`IntoIterator`](struct.LinearMap.html#method.into_iter). pub struct IntoIter { iter: vec::IntoIter<(K, V)>, } impl Iterator for IntoIter { type Item = (K, V); fn next(&mut self) -> Option<(K, V)> { self.iter.next() } fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() } } impl DoubleEndedIterator for IntoIter { fn next_back(&mut self) -> Option<(K, V)> { self.iter.next_back() } } impl ExactSizeIterator for IntoIter { fn len(&self) -> usize { self.iter.len() } } /// A draining iterator over a `LinearMap`. /// /// See [`LinearMap::drain`](struct.LinearMap.html#method.drain) for details. pub struct Drain<'a, K: 'a, V: 'a> { iter: vec::Drain<'a, (K, V)>, } /// An iterator yielding references to a `LinearMap`'s keys and their corresponding values. /// /// See [`LinearMap::iter`](struct.LinearMap.html#method.iter) for details. pub struct Iter<'a, K: 'a, V: 'a> { iter: slice::Iter<'a, (K, V)>, } /// An iterator yielding references to a `LinearMap`'s keys and mutable references to their /// corresponding values. /// /// See [`LinearMap::iter_mut`](struct.LinearMap.html#method.iter_mut) for details. pub struct IterMut<'a, K: 'a, V: 'a> { iter: slice::IterMut<'a, (K, V)>, } /// An iterator yielding references to a `LinearMap`'s keys in arbitrary order. /// /// See [`LinearMap::keys`](struct.LinearMap.html#method.keys) for details. pub struct Keys<'a, K: 'a, V: 'a> { iter: Iter<'a, K, V>, } /// An iterator yielding references to a `LinearMap`'s values in arbitrary order. /// /// See [`LinearMap::values`](struct.LinearMap.html#method.values) for details. pub struct Values<'a, K: 'a, V: 'a> { iter: Iter<'a, K, V>, } macro_rules! impl_iter {($typ:ty, $item:ty, $map:expr) => { impl<'a, K, V> Iterator for $typ { type Item = $item; fn next(&mut self) -> Option { self.iter.next().map($map) } fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() } } impl<'a, K, V> DoubleEndedIterator for $typ { fn next_back(&mut self) -> Option { self.iter.next_back().map($map) } } impl<'a, K, V> ExactSizeIterator for $typ { fn len(&self) -> usize { self.iter.len() } } }} impl_iter!{Drain<'a,K,V>, (K,V), |e| e } impl_iter!{Iter<'a,K,V>, (&'a K, &'a V), |e| (&e.0, &e.1) } impl_iter!{IterMut<'a,K,V>, (&'a K, &'a mut V), |e| (&e.0, &mut e.1) } impl_iter!{Keys<'a,K,V>, &'a K, |e| e.0 } impl_iter!{Values<'a,K,V>, &'a V, |e| e.1 } impl<'a, K, V> Clone for Iter<'a, K, V> { fn clone(&self) -> Self { Iter { iter: self.iter.clone() } } } impl<'a, K, V> Clone for Keys<'a, K, V> { fn clone(&self) -> Self { Keys { iter: self.iter.clone() } } } impl<'a, K, V> Clone for Values<'a, K, V> { fn clone(&self) -> Self { Values { iter: self.iter.clone() } } } impl IntoIterator for LinearMap { type Item = (K, V); type IntoIter = IntoIter; fn into_iter(self) -> IntoIter { IntoIter { iter: self.storage.into_iter() } } } impl<'a, K: Eq, V> IntoIterator for &'a LinearMap { 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: Eq, V> IntoIterator for &'a mut LinearMap { type Item = (&'a K, &'a mut V); type IntoIter = IterMut<'a, K, V>; fn into_iter(self) -> IterMut<'a, K, V> { self.iter_mut() } } #[allow(dead_code)] fn assert_covariance() { fn a<'a, K, V>(x: LinearMap<&'static K, &'static V>) -> LinearMap<&'a K, &'a V> { x } fn b<'a, K, V>(x: IntoIter<&'static K, &'static V>) -> IntoIter<&'a K, &'a V> { x } fn c<'i, 'a, K, V>(x: Iter<'i, &'static K, &'static V>) -> Iter<'i, &'a K, &'a V> { x } fn d<'i, 'a, K, V>(x: Keys<'i, &'static K, &'static V>) -> Keys<'i, &'a K, &'a V> { x } fn e<'i, 'a, K, V>(x: Values<'i, &'static K, &'static V>) -> Values<'i, &'a K, &'a V> { x } } linear-map-1.2.0/src/serde.rs01006440000766000002400000007770131361562530014236 0ustar0000000000000000//! An optional implementation of serialization/deserialization. Reference //! implementations used: //! //! - [Serialize][1]. //! - [Deserialize][2]. //! //! [1]: https://github.com/serde-rs/serde/blob/97856462467db2e90cf368e407c7ebcc726a01a9/serde/src/ser/impls.rs#L601-L611 //! [2]: https://github.com/serde-rs/serde/blob/97856462467db2e90cf368e407c7ebcc726a01a9/serde/src/de/impls.rs#L694-L746 extern crate serde; use super::LinearMap; use super::set::LinearSet; use self::serde::{Serialize, Serializer, Deserialize, Deserializer}; use self::serde::de::{Visitor, MapAccess, SeqAccess, Error}; use self::serde::ser::{SerializeMap, SerializeSeq}; use std::marker::PhantomData; use std::fmt; impl Serialize for LinearMap where K: Serialize + Eq, V: Serialize, { #[inline] fn serialize(&self, serializer: S) -> Result where S: Serializer, { let mut state = try!(serializer.serialize_map(Some(self.len()))); for (k, v) in self { try!(state.serialize_entry(k, v)); } state.end() } } #[allow(missing_docs)] pub struct LinearMapVisitor { marker: PhantomData>, } impl LinearMapVisitor { #[allow(missing_docs)] pub fn new() -> Self { LinearMapVisitor { marker: PhantomData, } } } impl<'de, K, V> Visitor<'de> for LinearMapVisitor where K: Deserialize<'de> + Eq, V: Deserialize<'de>, { type Value = LinearMap; fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "a LinearMap") } #[inline] fn visit_unit(self) -> Result where E: Error, { Ok(LinearMap::new()) } #[inline] fn visit_map(self, mut visitor: Visitor) -> Result where Visitor: MapAccess<'de> { let mut values = LinearMap::with_capacity(visitor.size_hint().unwrap_or(0)); while let Some((key, value)) = try!(visitor.next_entry()) { values.insert(key, value); } Ok(values) } } impl<'de, K, V> Deserialize<'de> for LinearMap where K: Deserialize<'de> + Eq, V: Deserialize<'de>, { fn deserialize(deserializer: D) -> Result, D::Error> where D: Deserializer<'de> { deserializer.deserialize_map(LinearMapVisitor::new()) } } impl Serialize for LinearSet where K: Serialize + Eq { #[inline] fn serialize(&self, serializer: S) -> Result where S: Serializer, { let mut state = try!(serializer.serialize_seq(Some(self.len()))); for k in self { try!(state.serialize_element(k)); } state.end() } } #[allow(missing_docs)] pub struct LinearSetVisitor { marker: PhantomData>, } impl LinearSetVisitor{ #[allow(missing_docs)] pub fn new() -> Self { LinearSetVisitor { marker: PhantomData, } } } impl<'de, K> Visitor<'de> for LinearSetVisitor where K: Deserialize<'de> + Eq, { type Value = LinearSet; fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "a LinearSet") } #[inline] fn visit_unit(self) -> Result where E: Error, { Ok(LinearSet::new()) } #[inline] fn visit_seq(self, mut visitor: Visitor) -> Result where Visitor: SeqAccess<'de> { let mut values = LinearSet::with_capacity(visitor.size_hint().unwrap_or(0)); while let Some(key) = try!(visitor.next_element()) { values.insert(key); } Ok(values) } } impl<'de, K> Deserialize<'de> for LinearSet where K: Deserialize<'de> + Eq, { fn deserialize(deserializer: D) -> Result, D::Error> where D: Deserializer<'de> { deserializer.deserialize_seq(LinearSetVisitor::new()) } } linear-map-1.2.0/src/set.rs01006440000766000002400000055750131361562530013730 0ustar0000000000000000//! A set implemented by searching linearly in a vector. //! //! See the [`LinearSet`](struct.LinearSet.html) type for details. use std::borrow::Borrow; use std::fmt; use std::iter::{Chain, FromIterator}; use std::ops::{BitOr, BitAnd, BitXor, Sub}; use super::{LinearMap, Keys}; /// An implementation of a set using the underlying representation of a /// LinearMap where the value is (). /// /// # Examples /// /// ``` /// use linear_map::set::LinearSet;; /// // Type inference lets us omit an explicit type signature (which /// // would be `LinearSet<&str>` in this example). /// let mut books = LinearSet::new(); /// /// // Add some books. /// books.insert("A Dance With Dragons"); /// books.insert("To Kill a Mockingbird"); /// books.insert("The Odyssey"); /// books.insert("The Great Gatsby"); /// /// // Check for a specific one. /// if !books.contains("The Winds of Winter") { /// println!("We have {} books, but The Winds of Winter ain't one.", /// books.len()); /// } /// /// // Remove a book. /// books.remove("The Odyssey"); /// /// // Iterate over everything. /// for book in &books { /// println!("{}", book); /// } /// ``` /// /// The easiest way to use `LinearSet` with a custom type is to derive /// `Eq`. We must also derive `PartialEq`, this will in the /// future be implied by `Eq`. /// /// ``` /// use linear_map::set::LinearSet;; /// #[derive(Eq, PartialEq, Debug)] /// struct Viking<'a> { /// name: &'a str, /// power: usize, /// } /// /// let mut vikings = LinearSet::new(); /// /// vikings.insert(Viking { name: "Einar", power: 9 }); /// vikings.insert(Viking { name: "Einar", power: 9 }); /// vikings.insert(Viking { name: "Olaf", power: 4 }); /// vikings.insert(Viking { name: "Harald", power: 8 }); /// /// // Use derived implementation to print the vikings. /// for x in &vikings { /// println!("{:?}", x); /// } /// ``` #[derive(Clone)] pub struct LinearSet { map: LinearMap } impl LinearSet { /// Creates an empty LinearSet. /// /// # Examples /// /// ``` /// use linear_map::set::LinearSet;; /// let mut set: LinearSet = LinearSet::new(); /// ``` #[inline] pub fn new() -> LinearSet { LinearSet { map: LinearMap::new() } } /// Creates an empty LinearSet with space for at least `n` elements in /// the map. /// /// # Examples /// /// ``` /// use linear_map::set::LinearSet;; /// let mut set: LinearSet = LinearSet::with_capacity(10); /// ``` #[inline] pub fn with_capacity(capacity: usize) -> LinearSet { LinearSet { map: LinearMap::with_capacity(capacity) } } } impl LinearSet where T: Eq { /// Returns the number of elements the set can hold without reallocating. /// /// # Examples /// /// ``` /// use linear_map::set::LinearSet;; /// let set: LinearSet = LinearSet::with_capacity(100); /// assert!(set.capacity() >= 100); /// ``` #[inline] pub fn capacity(&self) -> usize { self.map.capacity() } /// Reserves capacity for at least `additional` more elements to be inserted /// in the `LinearSet`. The collection may reserve more space to avoid /// frequent reallocations. /// /// # Panics /// /// Panics if the new allocation size overflows `usize`. /// /// # Examples /// /// ``` /// use linear_map::set::LinearSet;; /// let mut set: LinearSet = LinearSet::new(); /// set.reserve(10); /// ``` pub fn reserve(&mut self, additional: usize) { self.map.reserve(additional) } /// Shrinks the capacity of the set 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. /// /// # Examples /// /// ``` /// use linear_map::set::LinearSet;; /// /// let mut set = LinearSet::with_capacity(100); /// set.insert(1); /// set.insert(2); /// assert!(set.capacity() >= 100); /// set.shrink_to_fit(); /// assert!(set.capacity() >= 2); /// ``` pub fn shrink_to_fit(&mut self) { self.map.shrink_to_fit() } /// An iterator visiting all elements in arbitrary order. /// Iterator element type is &'a T. /// /// # Examples /// /// ``` /// use linear_map::set::LinearSet;; /// let mut set = LinearSet::new(); /// set.insert("a"); /// set.insert("b"); /// /// // Will print in an arbitrary order. /// for x in set.iter() { /// println!("{}", x); /// } /// ``` pub fn iter(&self) -> Iter { Iter { iter: self.map.keys() } } /// Visit the values representing the difference. /// /// # Examples /// /// ``` /// use linear_map::set::LinearSet;; /// let a: LinearSet<_> = [1, 2, 3].iter().cloned().collect(); /// let b: LinearSet<_> = [4, 2, 3, 4].iter().cloned().collect(); /// /// // Can be seen as `a - b`. /// for x in a.difference(&b) { /// println!("{}", x); // Print 1 /// } /// /// let diff: LinearSet<_> = a.difference(&b).cloned().collect(); /// assert_eq!(diff, [1].iter().cloned().collect()); /// /// // Note that difference is not symmetric, /// // and `b - a` means something else: /// let diff: LinearSet<_> = b.difference(&a).cloned().collect(); /// assert_eq!(diff, [4].iter().cloned().collect()); /// ``` pub fn difference<'a>(&'a self, other: &'a LinearSet) -> Difference<'a, T> { Difference { iter: self.iter(), other: other, } } /// Visit the values representing the symmetric difference. /// /// # Examples /// /// ``` /// use linear_map::set::LinearSet;; /// let a: LinearSet<_> = [1, 2, 3].iter().cloned().collect(); /// let b: LinearSet<_> = [4, 2, 3, 4].iter().cloned().collect(); /// /// // Print 1, 4 in arbitrary order. /// for x in a.symmetric_difference(&b) { /// println!("{}", x); /// } /// /// let diff1: LinearSet<_> = a.symmetric_difference(&b).cloned().collect(); /// let diff2: LinearSet<_> = b.symmetric_difference(&a).cloned().collect(); /// /// assert_eq!(diff1, diff2); /// assert_eq!(diff1, [1, 4].iter().cloned().collect()); /// ``` pub fn symmetric_difference<'a>(&'a self, other: &'a LinearSet) -> SymmetricDifference<'a, T> { SymmetricDifference { iter: self.difference(other).chain(other.difference(self)) } } /// Visit the values representing the intersection. /// /// # Examples /// /// ``` /// use linear_map::set::LinearSet;; /// let a: LinearSet<_> = [1, 2, 3].iter().cloned().collect(); /// let b: LinearSet<_> = [4, 2, 3, 4].iter().cloned().collect(); /// /// // Print 2, 3 in arbitrary order. /// for x in a.intersection(&b) { /// println!("{}", x); /// } /// /// let intersection: LinearSet<_> = a.intersection(&b).cloned().collect(); /// assert_eq!(intersection, [2, 3].iter().cloned().collect()); /// ``` pub fn intersection<'a>(&'a self, other: &'a LinearSet) -> Intersection<'a, T> { Intersection { iter: self.iter(), other: other, } } /// Visit the values representing the union. /// /// # Examples /// /// ``` /// use linear_map::set::LinearSet;; /// let a: LinearSet<_> = [1, 2, 3].iter().cloned().collect(); /// let b: LinearSet<_> = [4, 2, 3, 4].iter().cloned().collect(); /// /// // Print 1, 2, 3, 4 in arbitrary order. /// for x in a.union(&b) { /// println!("{}", x); /// } /// /// let union: LinearSet<_> = a.union(&b).cloned().collect(); /// assert_eq!(union, [1, 2, 3, 4].iter().cloned().collect()); /// ``` pub fn union<'a>(&'a self, other: &'a LinearSet) -> Union<'a, T> { Union { iter: self.iter().chain(other.difference(self)) } } /// Returns the number of elements in the set. /// /// # Examples /// /// ``` /// use linear_map::set::LinearSet;; /// /// let mut v = LinearSet::new(); /// assert_eq!(v.len(), 0); /// v.insert(1); /// assert_eq!(v.len(), 1); /// ``` pub fn len(&self) -> usize { self.map.len() } /// Returns true if the set contains no elements. /// /// # Examples /// /// ``` /// use linear_map::set::LinearSet;; /// /// let mut v = LinearSet::new(); /// assert!(v.is_empty()); /// v.insert(1); /// assert!(!v.is_empty()); /// ``` pub fn is_empty(&self) -> bool { self.map.is_empty() } /// Clears the set, returning all elements in an iterator. #[inline] pub fn drain(&mut self) -> Drain { Drain { iter: self.map.drain() } } /// Clears the set, removing all values. /// /// # Examples /// /// ``` /// use linear_map::set::LinearSet;; /// /// let mut v = LinearSet::new(); /// v.insert(1); /// v.clear(); /// assert!(v.is_empty()); /// ``` pub fn clear(&mut self) { self.map.clear() } /// Retains only the elements specified by the predicate. /// /// In other words, remove all elements `e` such that `f(&e)` returns `false`. /// pub fn retain(&mut self, mut f: F) where F: FnMut(&T) -> bool { self.map.retain(|k, _| f(k)); } /// Returns `true` if the set contains a value. /// /// The value may be any borrowed form of the set's value type, but /// `Eq` on the borrowed form *must* match those for /// the value type. /// /// # Examples /// /// ``` /// use linear_map::set::LinearSet;; /// /// let set: LinearSet<_> = [1, 2, 3].iter().cloned().collect(); /// assert_eq!(set.contains(&1), true); /// assert_eq!(set.contains(&4), false); /// ``` pub fn contains(&self, value: &Q) -> bool where T: Borrow, Q: Eq { self.map.contains_key(value) } /// Returns `true` if the set has no elements in common with `other`. /// This is equivalent to checking for an empty intersection. /// /// # Examples /// /// ``` /// use linear_map::set::LinearSet;; /// /// let a: LinearSet<_> = [1, 2, 3].iter().cloned().collect(); /// let mut b = LinearSet::new(); /// /// assert_eq!(a.is_disjoint(&b), true); /// b.insert(4); /// assert_eq!(a.is_disjoint(&b), true); /// b.insert(1); /// assert_eq!(a.is_disjoint(&b), false); /// ``` pub fn is_disjoint(&self, other: &LinearSet) -> bool { self.iter().all(|v| !other.contains(v)) } /// Returns `true` if the set is a subset of another. /// /// # Examples /// /// ``` /// use linear_map::set::LinearSet;; /// /// let sup: LinearSet<_> = [1, 2, 3].iter().cloned().collect(); /// let mut set = LinearSet::new(); /// /// assert_eq!(set.is_subset(&sup), true); /// set.insert(2); /// assert_eq!(set.is_subset(&sup), true); /// set.insert(4); /// assert_eq!(set.is_subset(&sup), false); /// ``` pub fn is_subset(&self, other: &LinearSet) -> bool { self.iter().all(|v| other.contains(v)) } /// Returns `true` if the set is a superset of another. /// /// # Examples /// /// ``` /// use linear_map::set::LinearSet;; /// /// let sub: LinearSet<_> = [1, 2].iter().cloned().collect(); /// let mut set = LinearSet::new(); /// /// assert_eq!(set.is_superset(&sub), false); /// /// set.insert(0); /// set.insert(1); /// assert_eq!(set.is_superset(&sub), false); /// /// set.insert(2); /// assert_eq!(set.is_superset(&sub), true); /// ``` #[inline] pub fn is_superset(&self, other: &LinearSet) -> bool { other.is_subset(self) } /// Adds a value to the set. /// /// If the set did not have a value present, `true` is returned. /// /// If the set did have this key present, `false` is returned. /// /// # Examples /// /// ``` /// use linear_map::set::LinearSet;; /// /// let mut set = LinearSet::new(); /// /// assert_eq!(set.insert(2), true); /// assert_eq!(set.insert(2), false); /// assert_eq!(set.len(), 1); /// ``` pub fn insert(&mut self, value: T) -> bool { self.map.insert(value, ()).is_none() } /// Removes a value from the set. Returns `true` if the value was /// present in the set. /// /// The value may be any borrowed form of the set's value type, but /// `Eq` on the borrowed form *must* match those for /// the value type. /// /// # Examples /// /// ``` /// use linear_map::set::LinearSet;; /// /// let mut set = LinearSet::new(); /// /// set.insert(2); /// assert_eq!(set.remove(&2), true); /// assert_eq!(set.remove(&2), false); /// ``` pub fn remove(&mut self, value: &Q) -> bool where T: Borrow, Q: Eq { self.map.remove(value).is_some() } } impl PartialEq for LinearSet where T: Eq { fn eq(&self, other: &LinearSet) -> bool { if self.len() != other.len() { return false; } self.iter().all(|key| other.contains(key)) } } impl Eq for LinearSet where T: Eq {} impl fmt::Debug for LinearSet where T: Eq + fmt::Debug { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_set().entries(self.iter()).finish() } } impl FromIterator for LinearSet where T: Eq { fn from_iter>(iter: I) -> LinearSet { let iterator = iter.into_iter(); let lower = iterator.size_hint().0; let mut set = LinearSet::with_capacity(lower); set.extend(iterator); set } } impl Extend for LinearSet where T: Eq { fn extend>(&mut self, iter: I) { for k in iter { self.insert(k); } } } impl<'a, T> Extend<&'a T> for LinearSet where T: 'a + Eq + Copy { fn extend>(&mut self, iter: I) { self.extend(iter.into_iter().cloned()); } } impl Default for LinearSet where T: Eq { fn default() -> LinearSet { LinearSet::new() } } impl Into> for LinearSet { fn into(self) -> Vec { unsafe { use std::mem; mem::transmute(self) } } } impl<'a, 'b, T> BitOr<&'b LinearSet> for &'a LinearSet where T: Eq + Clone { type Output = LinearSet; /// Returns the union of `self` and `rhs` as a new `LinearSet`. /// /// # Examples /// /// ``` /// use linear_map::set::LinearSet;; /// /// let a: LinearSet<_> = vec![1, 2, 3].into_iter().collect(); /// let b: LinearSet<_> = vec![3, 4, 5].into_iter().collect(); /// /// let set = &a | &b; /// /// let mut i = 0; /// let expected = [1, 2, 3, 4, 5]; /// for x in &set { /// assert!(expected.contains(x)); /// i += 1; /// } /// assert_eq!(i, expected.len()); /// ``` fn bitor(self, rhs: &LinearSet) -> LinearSet { self.union(rhs).cloned().collect() } } impl<'a, 'b, T> BitAnd<&'b LinearSet> for &'a LinearSet where T: Eq + Clone { type Output = LinearSet; /// Returns the intersection of `self` and `rhs` as a new `LinearSet`. /// /// # Examples /// /// ``` /// use linear_map::set::LinearSet;; /// /// let a: LinearSet<_> = vec![1, 2, 3].into_iter().collect(); /// let b: LinearSet<_> = vec![2, 3, 4].into_iter().collect(); /// /// let set = &a & &b; /// /// let mut i = 0; /// let expected = [2, 3]; /// for x in &set { /// assert!(expected.contains(x)); /// i += 1; /// } /// assert_eq!(i, expected.len()); /// ``` fn bitand(self, rhs: &LinearSet) -> LinearSet { self.intersection(rhs).cloned().collect() } } impl<'a, 'b, T> BitXor<&'b LinearSet> for &'a LinearSet where T: Eq + Clone { type Output = LinearSet; /// Returns the symmetric difference of `self` and `rhs` as a new `LinearSet`. /// /// # Examples /// /// ``` /// use linear_map::set::LinearSet;; /// /// let a: LinearSet<_> = vec![1, 2, 3].into_iter().collect(); /// let b: LinearSet<_> = vec![3, 4, 5].into_iter().collect(); /// /// let set = &a ^ &b; /// /// let mut i = 0; /// let expected = [1, 2, 4, 5]; /// for x in &set { /// assert!(expected.contains(x)); /// i += 1; /// } /// assert_eq!(i, expected.len()); /// ``` fn bitxor(self, rhs: &LinearSet) -> LinearSet { self.symmetric_difference(rhs).cloned().collect() } } impl<'a, 'b, T> Sub<&'b LinearSet> for &'a LinearSet where T: Eq + Clone { type Output = LinearSet; /// Returns the difference of `self` and `rhs` as a new `LinearSet`. /// /// # Examples /// /// ``` /// use linear_map::set::LinearSet;; /// /// let a: LinearSet<_> = vec![1, 2, 3].into_iter().collect(); /// let b: LinearSet<_> = vec![3, 4, 5].into_iter().collect(); /// /// let set = &a - &b; /// /// let mut i = 0; /// let expected = [1, 2]; /// for x in &set { /// assert!(expected.contains(x)); /// i += 1; /// } /// assert_eq!(i, expected.len()); /// ``` fn sub(self, rhs: &LinearSet) -> LinearSet { self.difference(rhs).cloned().collect() } } /// LinearSet iterator pub struct Iter<'a, K: 'a> { iter: Keys<'a, K, ()> } /// LinearSet move iterator pub struct IntoIter { iter: super::IntoIter } /// LinearSet drain iterator pub struct Drain<'a, K: 'a> { iter: super::Drain<'a, K, ()>, } /// Intersection iterator pub struct Intersection<'a, T: 'a> { // iterator of the first set iter: Iter<'a, T>, // the second set other: &'a LinearSet, } /// Difference iterator pub struct Difference<'a, T: 'a> { // iterator of the first set iter: Iter<'a, T>, // the second set other: &'a LinearSet, } /// Symmetric difference iterator. pub struct SymmetricDifference<'a, T: 'a> { iter: Chain, Difference<'a, T>> } /// Set union iterator. pub struct Union<'a, T: 'a> { iter: Chain, Difference<'a, T>> } impl<'a, T> IntoIterator for &'a LinearSet where T: Eq { type Item = &'a T; type IntoIter = Iter<'a, T>; fn into_iter(self) -> Iter<'a, T> { self.iter() } } impl IntoIterator for LinearSet where T: Eq { type Item = T; type IntoIter = IntoIter; /// Creates a consuming iterator, that is, one that moves each value out /// of the set in arbitrary order. The set cannot be used after calling /// this. /// /// # Examples /// /// ``` /// use linear_map::set::LinearSet;; /// let mut set = LinearSet::new(); /// set.insert("a".to_string()); /// set.insert("b".to_string()); /// /// // Not possible to collect to a Vec with a regular `.iter()`. /// let v: Vec = set.into_iter().collect(); /// /// // Will print in an arbitrary order. /// for x in &v { /// println!("{}", x); /// } /// ``` fn into_iter(self) -> IntoIter { IntoIter { iter: self.map.into_iter() } } } impl<'a, K> Clone for Iter<'a, K> { fn clone(&self) -> Iter<'a, K> { Iter { iter: self.iter.clone() } } } impl<'a, K> Iterator for Iter<'a, K> { type Item = &'a K; fn next(&mut self) -> Option<&'a K> { self.iter.next() } fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() } } impl<'a, K> ExactSizeIterator for Iter<'a, K> { fn len(&self) -> usize { self.iter.len() } } impl Iterator for IntoIter { type Item = K; fn next(&mut self) -> Option { self.iter.next().map(|(k, _)| k) } fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() } } impl ExactSizeIterator for IntoIter { fn len(&self) -> usize { self.iter.len() } } impl<'a, K> Iterator for Drain<'a, K> { type Item = K; fn next(&mut self) -> Option { self.iter.next().map(|(k, _)| k) } fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() } } impl<'a, K> ExactSizeIterator for Drain<'a, K> { fn len(&self) -> usize { self.iter.len() } } impl<'a, T> Clone for Intersection<'a, T> { fn clone(&self) -> Intersection<'a, T> { Intersection { iter: self.iter.clone(), ..*self } } } impl<'a, T> Iterator for Intersection<'a, T> where T: Eq { type Item = &'a T; fn next(&mut self) -> Option<&'a T> { loop { match self.iter.next() { None => return None, Some(elt) => if self.other.contains(elt) { return Some(elt) }, } } } fn size_hint(&self) -> (usize, Option) { let (_, upper) = self.iter.size_hint(); (0, upper) } } impl<'a, T> Clone for Difference<'a, T> { fn clone(&self) -> Difference<'a, T> { Difference { iter: self.iter.clone(), ..*self } } } impl<'a, T> Iterator for Difference<'a, T> where T: Eq { type Item = &'a T; fn next(&mut self) -> Option<&'a T> { loop { match self.iter.next() { None => return None, Some(elt) => if !self.other.contains(elt) { return Some(elt) }, } } } fn size_hint(&self) -> (usize, Option) { let (_, upper) = self.iter.size_hint(); (0, upper) } } impl<'a, T> Clone for SymmetricDifference<'a, T> { fn clone(&self) -> SymmetricDifference<'a, T> { SymmetricDifference { iter: self.iter.clone() } } } impl<'a, T> Iterator for SymmetricDifference<'a, T> where T: Eq { type Item = &'a T; fn next(&mut self) -> Option<&'a T> { self.iter.next() } fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() } } impl<'a, T> Clone for Union<'a, T> { fn clone(&self) -> Union<'a, T> { Union { iter: self.iter.clone() } } } impl<'a, T> Iterator for Union<'a, T> where T: Eq { type Item = &'a T; fn next(&mut self) -> Option<&'a T> { self.iter.next() } fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() } } #[allow(dead_code)] fn assert_covariance() { fn set<'new>(v: LinearSet<&'static str>) -> LinearSet<&'new str> { v } fn iter<'a, 'new>(v: Iter<'a, &'static str>) -> Iter<'a, &'new str> { v } fn into_iter<'new>(v: IntoIter<&'static str>) -> IntoIter<&'new str> { v } fn difference<'a, 'new>(v: Difference<'a, &'static str>) -> Difference<'a, &'new str> { v } fn symmetric_difference<'a, 'new>(v: SymmetricDifference<'a, &'static str>) -> SymmetricDifference<'a, &'new str> { v } fn intersection<'a, 'new>(v: Intersection<'a, &'static str>) -> Intersection<'a, &'new str> { v } fn union<'a, 'new>(v: Union<'a, &'static str>) -> Union<'a, &'new str> { v } } linear-map-1.2.0/tests/serde.rs01006440000766000002400000002563131361562530014604 0ustar0000000000000000#![cfg(feature = "serde_impl")] extern crate linear_map; use linear_map::LinearMap; extern crate serde_test; use serde_test::{Token, assert_tokens}; #[test] fn test_ser_de_empty() { let map = LinearMap::::new(); assert_tokens(&map, &[ Token::Map { len: Some(0) }, Token::MapEnd, ]); } #[test] fn test_ser_de() { let mut map = LinearMap::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, ]); } mod set { use serde_test::{Token, assert_tokens}; use linear_map::set::LinearSet; #[test] fn test_ser_de_empty() { let set = LinearSet::::new(); assert_tokens(&set, &[ Token::Seq { len: Some(0) }, Token::SeqEnd, ]); } #[test] fn test_ser_de() { let mut set = LinearSet::new(); set.insert('b'); set.insert('a'); set.insert('c'); assert_tokens(&set, &[ Token::Seq { len: Some(3) }, Token::Char('b'), Token::Char('a'), Token::Char('c'), Token::SeqEnd, ]); } } linear-map-1.2.0/tests/set.rs01006440000766000002400000015466131361562530014303 0ustar0000000000000000extern crate linear_map; use linear_map::set::LinearSet; #[test] fn test_disjoint() { let mut xs = LinearSet::new(); let mut ys = LinearSet::new(); assert!(xs.is_disjoint(&ys)); assert!(ys.is_disjoint(&xs)); assert!(xs.insert(5)); assert!(ys.insert(11)); assert!(xs.is_disjoint(&ys)); assert!(ys.is_disjoint(&xs)); assert!(xs.insert(7)); assert!(xs.insert(19)); assert!(xs.insert(4)); assert!(ys.insert(2)); assert!(ys.insert(-11)); assert!(xs.is_disjoint(&ys)); assert!(ys.is_disjoint(&xs)); assert!(ys.insert(7)); assert!(!xs.is_disjoint(&ys)); assert!(!ys.is_disjoint(&xs)); } #[test] fn test_subset_and_superset() { let mut a = LinearSet::new(); assert!(a.insert(0)); assert!(a.insert(5)); assert!(a.insert(11)); assert!(a.insert(7)); let mut b = LinearSet::new(); assert!(b.insert(0)); assert!(b.insert(7)); assert!(b.insert(19)); assert!(b.insert(250)); assert!(b.insert(11)); assert!(b.insert(200)); assert!(!a.is_subset(&b)); assert!(!a.is_superset(&b)); assert!(!b.is_subset(&a)); assert!(!b.is_superset(&a)); assert!(b.insert(5)); assert!(a.is_subset(&b)); assert!(!a.is_superset(&b)); assert!(!b.is_subset(&a)); assert!(b.is_superset(&a)); } #[test] fn test_iterate() { let mut a = LinearSet::new(); for i in 0..32 { assert!(a.insert(i)); } let mut observed: u32 = 0; for k in &a { observed |= 1 << *k; } assert_eq!(observed, 0xFFFF_FFFF); } #[test] fn test_intersection() { let mut a = LinearSet::new(); let mut b = LinearSet::new(); assert!(a.insert(11)); assert!(a.insert(1)); assert!(a.insert(3)); assert!(a.insert(77)); assert!(a.insert(103)); assert!(a.insert(5)); assert!(a.insert(-5)); assert!(b.insert(2)); assert!(b.insert(11)); assert!(b.insert(77)); assert!(b.insert(-9)); assert!(b.insert(-42)); assert!(b.insert(5)); assert!(b.insert(3)); let mut i = 0; let expected = [3, 5, 11, 77]; for x in a.intersection(&b) { assert!(expected.contains(x)); i += 1 } assert_eq!(i, expected.len()); } #[test] fn test_difference() { let mut a = LinearSet::new(); let mut b = LinearSet::new(); assert!(a.insert(1)); assert!(a.insert(3)); assert!(a.insert(5)); assert!(a.insert(9)); assert!(a.insert(11)); assert!(b.insert(3)); assert!(b.insert(9)); let mut i = 0; let expected = [1, 5, 11]; for x in a.difference(&b) { assert!(expected.contains(x)); i += 1 } assert_eq!(i, expected.len()); } #[test] fn test_symmetric_difference() { let mut a = LinearSet::new(); let mut b = LinearSet::new(); assert!(a.insert(1)); assert!(a.insert(3)); assert!(a.insert(5)); assert!(a.insert(9)); assert!(a.insert(11)); assert!(b.insert(-2)); assert!(b.insert(3)); assert!(b.insert(9)); assert!(b.insert(14)); assert!(b.insert(22)); let mut i = 0; let expected = [-2, 1, 5, 11, 14, 22]; for x in a.symmetric_difference(&b) { assert!(expected.contains(x)); i += 1 } assert_eq!(i, expected.len()); } #[test] fn test_union() { let mut a = LinearSet::new(); let mut b = LinearSet::new(); assert!(a.insert(1)); assert!(a.insert(3)); assert!(a.insert(5)); assert!(a.insert(9)); assert!(a.insert(11)); assert!(a.insert(16)); assert!(a.insert(19)); assert!(a.insert(24)); assert!(b.insert(-2)); assert!(b.insert(1)); assert!(b.insert(5)); assert!(b.insert(9)); assert!(b.insert(13)); assert!(b.insert(19)); let mut i = 0; let expected = [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24]; for x in a.union(&b) { assert!(expected.contains(x)); i += 1 } assert_eq!(i, expected.len()); } #[test] fn test_from_iter() { let xs = [1, 2, 3, 4, 5, 6, 7, 8, 9]; let set: LinearSet<_> = xs.iter().cloned().collect(); for x in &xs { assert!(set.contains(x)); } } #[test] fn test_move_iter() { let hs = { let mut hs = LinearSet::new(); hs.insert('a'); hs.insert('b'); hs }; let v = hs.into_iter().collect::>(); assert!(v == ['a', 'b'] || v == ['b', 'a']); } #[test] fn test_eq() { // These constants once happened to expose a bug in insert(). // I'm keeping them around to prevent a regression. let mut s1 = LinearSet::new(); s1.insert(1); s1.insert(2); s1.insert(3); let mut s2 = LinearSet::new(); s2.insert(1); s2.insert(2); assert!(s1 != s2); s2.insert(3); assert_eq!(s1, s2); } #[test] fn test_show() { let mut set = LinearSet::new(); let empty = LinearSet::::new(); set.insert(1); set.insert(2); let set_str = format!("{:?}", set); assert!(set_str == "{1, 2}" || set_str == "{2, 1}"); assert_eq!(format!("{:?}", empty), "{}"); } #[test] fn test_trivial_drain() { let mut s = LinearSet::::new(); for _ in s.drain() {} assert!(s.is_empty()); drop(s); let mut s = LinearSet::::new(); drop(s.drain()); assert!(s.is_empty()); } #[test] fn test_drain() { let mut s: LinearSet<_> = (1..100).collect(); // try this a bunch of times to make sure we don't screw up internal state. for _ in 0..20 { assert_eq!(s.len(), 99); { let mut last_i = 0; let mut d = s.drain(); for (i, x) in d.by_ref().take(50).enumerate() { last_i = i; assert!(x != 0); } assert_eq!(last_i, 49); } for _ in &s { panic!("s should be empty!"); } // reset to try again. s.extend(1..100); } } #[test] fn test_extend_ref() { let mut a = LinearSet::new(); a.insert(1); a.extend(&[2, 3, 4]); assert_eq!(a.len(), 4); assert!(a.contains(&1)); assert!(a.contains(&2)); assert!(a.contains(&3)); assert!(a.contains(&4)); let mut b = LinearSet::new(); b.insert(5); b.insert(6); a.extend(&b); assert_eq!(a.len(), 6); assert!(a.contains(&1)); assert!(a.contains(&2)); assert!(a.contains(&3)); assert!(a.contains(&4)); assert!(a.contains(&5)); assert!(a.contains(&6)); } #[test] fn test_into_vec() { let mut a = LinearSet::new(); assert!(a.insert(0)); assert!(a.insert(5)); assert!(a.insert(11)); assert!(a.insert(7)); let set_as_vec: Vec<_> = a.into(); assert_eq!(set_as_vec, vec![0, 5, 11, 7]); } #[test] fn test_retain() { let xs = [1,2,3,4,5,6]; let mut set: LinearSet = xs.iter().cloned().collect(); set.retain(|&k| k % 2 == 0); assert_eq!(set.len(), 3); assert!(set.contains(&2)); assert!(set.contains(&4)); assert!(set.contains(&6)); } linear-map-1.2.0/tests/test.rs01006440000766000002400000015544131361562530014464 0ustar0000000000000000#[macro_use] extern crate linear_map; use linear_map::LinearMap; use linear_map::Entry::{Occupied, Vacant}; const TEST_CAPACITY: usize = 10; #[test] fn test_new() { let map: LinearMap = LinearMap::new(); assert_eq!(map.capacity(), 0); assert_eq!(map.len(), 0); assert!(map.is_empty()); } #[test] fn test_with_capacity() { let map: LinearMap = LinearMap::with_capacity(TEST_CAPACITY); assert!(map.capacity() >= TEST_CAPACITY); } #[test] fn test_capacity() { let mut map = LinearMap::new(); map.insert(1, 2); assert!(map.capacity() >= 1); map.remove(&1); assert!(map.capacity() >= 1); map.reserve(TEST_CAPACITY); let capacity = map.capacity(); assert!(capacity >= TEST_CAPACITY); for i in 0..TEST_CAPACITY as i32 { assert!(map.insert(i, i).is_none()); } assert_eq!(capacity, map.capacity()); } #[test] fn test_reserve() { let mut map = LinearMap::new(); map.reserve(TEST_CAPACITY); assert!(map.capacity() >= TEST_CAPACITY); for i in 0..TEST_CAPACITY as i32 { assert!(map.insert(i, i).is_none()); } map.reserve(TEST_CAPACITY); assert!(map.capacity() >= 2 * TEST_CAPACITY); let mut map = LinearMap::new(); map.reserve(TEST_CAPACITY); assert!(map.capacity() >= TEST_CAPACITY); for i in 0..TEST_CAPACITY as i32 { assert!(map.insert(i, i).is_none()); } map.reserve(TEST_CAPACITY); assert!(map.capacity() >= 2 * TEST_CAPACITY); } #[test] fn test_shrink_to_fit() { let mut map = LinearMap::new(); map.shrink_to_fit(); assert_eq!(map.capacity(), 0); map.reserve(TEST_CAPACITY); map.shrink_to_fit(); assert_eq!(map.capacity(), 0); for i in 0..TEST_CAPACITY as i32 { assert!(map.insert(i, i).is_none()); } map.shrink_to_fit(); assert_eq!(map.len(), TEST_CAPACITY); assert!(map.capacity() >= TEST_CAPACITY); } #[test] fn test_len_and_is_empty() { let mut map = LinearMap::new(); assert_eq!(map.len(), 0); assert!(map.is_empty()); map.insert(100, 100); assert_eq!(map.len(), 1); assert!(!map.is_empty()); for i in 0..TEST_CAPACITY as i32 { assert!(map.insert(i, i).is_none()); } assert_eq!(map.len(), 1 + TEST_CAPACITY); assert!(!map.is_empty()); assert!(map.remove(&100).is_some()); assert_eq!(map.len(), TEST_CAPACITY); assert!(!map.is_empty()); } #[test] fn test_clear() { let mut map = LinearMap::new(); map.clear(); assert_eq!(map.len(), 0); for i in 0..TEST_CAPACITY as i32 { assert!(map.insert(i, i).is_none()); } map.clear(); assert_eq!(map.len(), 0); assert!(map.capacity() > 0); } #[test] fn test_iterators() { const ONE: i32 = 0b0001; const TWO: i32 = 0b0010; const THREE: i32 = 0b0100; const FOUR: i32 = 0b1000; const ALL: i32 = 0b1111; let mut map = LinearMap::new(); assert!(map.insert(ONE, TWO).is_none()); assert!(map.insert(TWO, THREE).is_none()); assert!(map.insert(THREE, FOUR).is_none()); assert!(map.insert(FOUR, ONE).is_none()); { let mut result_k = 0; let mut result_v = 0; for (&k, &v) in map.iter() { result_k ^= k; result_v ^= v; assert_eq!(((k << 1) & ALL) | ((k >> 3) & ALL), v); } assert_eq!(result_k, ALL); assert_eq!(result_v, ALL); } { let mut result_k = 0; let mut result_v = 0; for (&k, &mut v) in map.iter_mut() { result_k ^= k; result_v ^= v; assert_eq!(((k << 1) & ALL) | ((k >> 3) & ALL), v); } assert_eq!(result_k, ALL); assert_eq!(result_v, ALL); } { let mut result = 0; for &k in map.keys() { result ^= k; } assert_eq!(result, ALL); } { let mut result = 0; for &v in map.values() { result ^= v; } assert_eq!(result, ALL); } } #[test] fn test_insert_remove_get() { let mut map = LinearMap::new(); assert!(map.insert(100, 101).is_none()); assert!(map.contains_key(&100)); assert_eq!(map.get(&100), Some(&101)); assert_eq!(map.get_mut(&100), Some(&mut 101)); for i in 0..TEST_CAPACITY as i32 { assert!(map.insert(i, i).is_none()); } assert_eq!(map.insert(100, 102), Some(101)); assert_eq!(map.remove(&100), Some(102)); assert_eq!(map.remove(&100), None); assert_eq!(map.remove(&1000), None); } #[test] fn test_entry() { let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)]; let mut map = LinearMap::new(); for &(k, v) in &xs { map.insert(k, v); } // Existing key (insert) match map.entry(1) { Vacant(_) => unreachable!(), Occupied(mut view) => { assert_eq!(view.get(), &10); assert_eq!(view.insert(100), 10); } } assert_eq!(map.get(&1).unwrap(), &100); assert_eq!(map.len(), 6); // Existing key (update) match map.entry(2) { Vacant(_) => unreachable!(), Occupied(mut view) => { let v = view.get_mut(); let new_v = (*v) * 10; *v = new_v; } } assert_eq!(map.get(&2).unwrap(), &200); assert_eq!(map.len(), 6); // Existing key (take) match map.entry(3) { Vacant(_) => unreachable!(), Occupied(view) => { assert_eq!(view.remove(), 30); } } assert_eq!(map.get(&3), None); assert_eq!(map.len(), 5); // Inexistent key (insert) match map.entry(10) { Occupied(_) => unreachable!(), Vacant(view) => { assert_eq!(*view.insert(1000), 1000); } } assert_eq!(map.get(&10).unwrap(), &1000); assert_eq!(map.len(), 6); } #[test] fn test_eq() { let kvs = vec![('a', 1), ('b', 2), ('c', 3)]; let mut m1: LinearMap<_, _> = kvs.clone().into_iter().collect(); let m2: LinearMap<_, _> = kvs.into_iter().rev().collect(); assert_eq!(m1, m2); m1.insert('a', 11); assert!(m1 != m2); m1.insert('a', 1); assert_eq!(m1, m2); m1.remove(&'a'); assert!(m1 != m2); } #[test] fn test_macro() { let names = linear_map!{ 1 => "one", 2 => "two", }; assert_eq!(names.len(), 2); assert_eq!(names.capacity(), 2); assert_eq!(names[&1], "one"); assert_eq!(names[&2], "two"); assert_eq!(names.get(&3), None); let empty: LinearMap = linear_map!{}; assert_eq!(empty.len(), 0); assert_eq!(empty.capacity(), 0); let _nested_compiles = linear_map!{ 1 => linear_map!{0 => 1 + 2,}, 2 => linear_map!{1 => 1,}, }; } #[test] fn test_retain() { let mut map: LinearMap = (0..100).map(|x|(x, x*10)).collect(); map.retain(|&k, _| k % 2 == 0); assert_eq!(map.len(), 50); assert_eq!(map[&2], 20); assert_eq!(map[&4], 40); assert_eq!(map[&6], 60); }