aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJoel Galenson <jgalenson@google.com>2020-07-30 16:52:51 +0000
committerAutomerger Merge Worker <android-build-automerger-merge-worker@system.gserviceaccount.com>2020-07-30 16:52:51 +0000
commit4bdd88eb3c1d333edef3cb47b9d9fe253bdc16b8 (patch)
tree99a76e39cfb2b37a8a11406c34e4d3bd31ad7f10
parent58c6cd5619aceba2122382fc5444599323a8b0ab (diff)
parentc9a9d2b4a027cc47556ec151e25f1d98c6c2641e (diff)
downloadlru-cache-4bdd88eb3c1d333edef3cb47b9d9fe253bdc16b8.tar.gz
Import lru-cache-0.1.2 am: 891d7cdbb8 am: 4f24ea1bd1 am: e68cb32f2c am: ea1308d100 am: c9a9d2b4a0
Original change: https://android-review.googlesource.com/c/platform/external/rust/crates/lru-cache/+/1375176 Change-Id: I68adfbd11253d7af13f5d75f20b76538ff9c7303
-rw-r--r--.cargo_vcs_info.json5
-rw-r--r--.gitignore2
-rw-r--r--.travis.yml13
-rw-r--r--Cargo.toml32
-rw-r--r--Cargo.toml.orig23
-rw-r--r--LICENSE-APACHE201
-rw-r--r--LICENSE-MIT25
-rw-r--r--README.md14
-rwxr-xr-xdeploy-docs.sh20
-rw-r--r--src/heapsize.rs12
-rw-r--r--src/lib.rs567
11 files changed, 914 insertions, 0 deletions
diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json
new file mode 100644
index 0000000..15ff79b
--- /dev/null
+++ b/.cargo_vcs_info.json
@@ -0,0 +1,5 @@
+{
+ "git": {
+ "sha1": "dbde7d74a6ac026cfc3bd935bc5732e19c4dafe2"
+ }
+}
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..a9d37c5
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+target
+Cargo.lock
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000..961a991
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,13 @@
+language: rust
+rust: nightly
+sudo: false
+script:
+ - cargo build
+ - cargo test
+ - cargo doc --no-deps
+after_success: |
+ [ $TRAVIS_BRANCH = master ] &&
+ [ $TRAVIS_PULL_REQUEST = false ] &&
+ bash deploy-docs.sh
+notifications:
+ webhooks: http://huon.me:54857/travis
diff --git a/Cargo.toml b/Cargo.toml
new file mode 100644
index 0000000..25bcbf4
--- /dev/null
+++ b/Cargo.toml
@@ -0,0 +1,32 @@
+# 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 = "lru-cache"
+version = "0.1.2"
+authors = ["Stepan Koltsov <stepan.koltsov@gmail.com>"]
+description = "A cache that holds a limited number of key-value pairs"
+homepage = "https://github.com/contain-rs/lru-cache"
+documentation = "https://contain-rs.github.io/lru-cache/lru_cache"
+readme = "README.md"
+keywords = ["data-structures"]
+license = "MIT/Apache-2.0"
+repository = "https://github.com/contain-rs/lru-cache"
+[dependencies.heapsize]
+version = "0.4"
+optional = true
+
+[dependencies.linked-hash-map]
+version = "0.5"
+
+[features]
+heapsize_impl = ["heapsize", "linked-hash-map/heapsize_impl"]
diff --git a/Cargo.toml.orig b/Cargo.toml.orig
new file mode 100644
index 0000000..4063eb9
--- /dev/null
+++ b/Cargo.toml.orig
@@ -0,0 +1,23 @@
+[package]
+
+name = "lru-cache"
+version = "0.1.2"
+license = "MIT/Apache-2.0"
+description = "A cache that holds a limited number of key-value pairs"
+authors = [
+ "Stepan Koltsov <stepan.koltsov@gmail.com>",
+]
+
+repository = "https://github.com/contain-rs/lru-cache"
+homepage = "https://github.com/contain-rs/lru-cache"
+documentation = "https://contain-rs.github.io/lru-cache/lru_cache"
+keywords = ["data-structures"]
+readme = "README.md"
+
+[features]
+heapsize_impl = ["heapsize", "linked-hash-map/heapsize_impl"]
+
+[dependencies]
+linked-hash-map = "0.5"
+
+heapsize = { version = "0.4", optional = true }
diff --git a/LICENSE-APACHE b/LICENSE-APACHE
new file mode 100644
index 0000000..11069ed
--- /dev/null
+++ b/LICENSE-APACHE
@@ -0,0 +1,201 @@
+ 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.
diff --git a/LICENSE-MIT b/LICENSE-MIT
new file mode 100644
index 0000000..e69282e
--- /dev/null
+++ b/LICENSE-MIT
@@ -0,0 +1,25 @@
+Copyright (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.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..d835d6e
--- /dev/null
+++ b/README.md
@@ -0,0 +1,14 @@
+**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 cache that holds a limited number of key-value pairs.
+
+Documentation is available at https://contain-rs.github.io/lru-cache/lru_cache.
diff --git a/deploy-docs.sh b/deploy-docs.sh
new file mode 100755
index 0000000..c8f25ee
--- /dev/null
+++ b/deploy-docs.sh
@@ -0,0 +1,20 @@
+#!/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
diff --git a/src/heapsize.rs b/src/heapsize.rs
new file mode 100644
index 0000000..ff0170f
--- /dev/null
+++ b/src/heapsize.rs
@@ -0,0 +1,12 @@
+extern crate heapsize;
+
+use self::heapsize::HeapSizeOf;
+use std::hash::{Hash, BuildHasher};
+
+use LruCache;
+
+impl<K: Eq + Hash + HeapSizeOf, V: HeapSizeOf, S: BuildHasher> HeapSizeOf for LruCache<K, V, S> {
+ fn heap_size_of_children(&self) -> usize {
+ self.map.heap_size_of_children()
+ }
+}
diff --git a/src/lib.rs b/src/lib.rs
new file mode 100644
index 0000000..fcf9b61
--- /dev/null
+++ b/src/lib.rs
@@ -0,0 +1,567 @@
+// Copyright 2015 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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+//! A cache that holds a limited number of key-value pairs. When the
+//! capacity of the cache is exceeded, the least-recently-used
+//! (where "used" means a look-up or putting the pair into the cache)
+//! pair is automatically removed.
+//!
+//! # Examples
+//!
+//! ```
+//! use lru_cache::LruCache;
+//!
+//! let mut cache = LruCache::new(2);
+//!
+//! cache.insert(1, 10);
+//! cache.insert(2, 20);
+//! cache.insert(3, 30);
+//! assert!(cache.get_mut(&1).is_none());
+//! assert_eq!(*cache.get_mut(&2).unwrap(), 20);
+//! assert_eq!(*cache.get_mut(&3).unwrap(), 30);
+//!
+//! cache.insert(2, 22);
+//! assert_eq!(*cache.get_mut(&2).unwrap(), 22);
+//!
+//! cache.insert(6, 60);
+//! assert!(cache.get_mut(&3).is_none());
+//!
+//! cache.set_capacity(1);
+//! assert!(cache.get_mut(&2).is_none());
+//! ```
+
+extern crate linked_hash_map;
+
+use std::borrow::Borrow;
+use std::collections::hash_map::RandomState;
+use std::fmt;
+use std::hash::{Hash, BuildHasher};
+
+use linked_hash_map::LinkedHashMap;
+
+#[cfg(feature = "heapsize_impl")]
+mod heapsize;
+
+// FIXME(conventions): implement indexing?
+
+/// An LRU cache.
+#[derive(Clone)]
+pub struct LruCache<K: Eq + Hash, V, S: BuildHasher = RandomState> {
+ map: LinkedHashMap<K, V, S>,
+ max_size: usize,
+}
+
+impl<K: Eq + Hash, V> LruCache<K, V> {
+ /// Creates an empty cache that can hold at most `capacity` items.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use lru_cache::LruCache;
+ /// let mut cache: LruCache<i32, &str> = LruCache::new(10);
+ /// ```
+ pub fn new(capacity: usize) -> Self {
+ LruCache {
+ map: LinkedHashMap::new(),
+ max_size: capacity,
+ }
+ }
+}
+
+impl<K: Eq + Hash, V, S: BuildHasher> LruCache<K, V, S> {
+ /// Creates an empty cache that can hold at most `capacity` items with the given hash builder.
+ pub fn with_hasher(capacity: usize, hash_builder: S) -> Self {
+ LruCache { map: LinkedHashMap::with_hasher(hash_builder), max_size: capacity }
+ }
+
+ /// Checks if the map contains the given key.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use lru_cache::LruCache;
+ ///
+ /// let mut cache = LruCache::new(1);
+ ///
+ /// cache.insert(1, "a");
+ /// assert_eq!(cache.contains_key(&1), true);
+ /// ```
+ pub fn contains_key<Q: ?Sized>(&mut self, key: &Q) -> bool
+ where K: Borrow<Q>,
+ Q: Hash + Eq
+ {
+ self.get_mut(key).is_some()
+ }
+
+ /// Inserts a key-value pair into the cache. If the key already existed, the old value is
+ /// returned.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use lru_cache::LruCache;
+ ///
+ /// let mut cache = LruCache::new(2);
+ ///
+ /// cache.insert(1, "a");
+ /// cache.insert(2, "b");
+ /// assert_eq!(cache.get_mut(&1), Some(&mut "a"));
+ /// assert_eq!(cache.get_mut(&2), Some(&mut "b"));
+ /// ```
+ pub fn insert(&mut self, k: K, v: V) -> Option<V> {
+ let old_val = self.map.insert(k, v);
+ if self.len() > self.capacity() {
+ self.remove_lru();
+ }
+ old_val
+ }
+
+ /// Returns a mutable reference to the value corresponding to the given key in the cache, if
+ /// any.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use lru_cache::LruCache;
+ ///
+ /// let mut cache = LruCache::new(2);
+ ///
+ /// cache.insert(1, "a");
+ /// cache.insert(2, "b");
+ /// cache.insert(2, "c");
+ /// cache.insert(3, "d");
+ ///
+ /// assert_eq!(cache.get_mut(&1), None);
+ /// assert_eq!(cache.get_mut(&2), Some(&mut "c"));
+ /// ```
+ pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
+ where K: Borrow<Q>,
+ Q: Hash + Eq
+ {
+ self.map.get_refresh(k)
+ }
+
+ /// Removes the given key from the cache and returns its corresponding value.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use lru_cache::LruCache;
+ ///
+ /// let mut cache = LruCache::new(2);
+ ///
+ /// cache.insert(2, "a");
+ ///
+ /// assert_eq!(cache.remove(&1), None);
+ /// assert_eq!(cache.remove(&2), Some("a"));
+ /// assert_eq!(cache.remove(&2), None);
+ /// assert_eq!(cache.len(), 0);
+ /// ```
+ pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
+ where K: Borrow<Q>,
+ Q: Hash + Eq
+ {
+ self.map.remove(k)
+ }
+
+ /// Returns the maximum number of key-value pairs the cache can hold.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use lru_cache::LruCache;
+ /// let mut cache: LruCache<i32, &str> = LruCache::new(2);
+ /// assert_eq!(cache.capacity(), 2);
+ /// ```
+ pub fn capacity(&self) -> usize {
+ self.max_size
+ }
+
+ /// Sets the number of key-value pairs the cache can hold. Removes
+ /// least-recently-used key-value pairs if necessary.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use lru_cache::LruCache;
+ ///
+ /// let mut cache = LruCache::new(2);
+ ///
+ /// cache.insert(1, "a");
+ /// cache.insert(2, "b");
+ /// cache.insert(3, "c");
+ ///
+ /// assert_eq!(cache.get_mut(&1), None);
+ /// assert_eq!(cache.get_mut(&2), Some(&mut "b"));
+ /// assert_eq!(cache.get_mut(&3), Some(&mut "c"));
+ ///
+ /// cache.set_capacity(3);
+ /// cache.insert(1, "a");
+ /// cache.insert(2, "b");
+ ///
+ /// assert_eq!(cache.get_mut(&1), Some(&mut "a"));
+ /// assert_eq!(cache.get_mut(&2), Some(&mut "b"));
+ /// assert_eq!(cache.get_mut(&3), Some(&mut "c"));
+ ///
+ /// cache.set_capacity(1);
+ ///
+ /// assert_eq!(cache.get_mut(&1), None);
+ /// assert_eq!(cache.get_mut(&2), None);
+ /// assert_eq!(cache.get_mut(&3), Some(&mut "c"));
+ /// ```
+ pub fn set_capacity(&mut self, capacity: usize) {
+ for _ in capacity..self.len() {
+ self.remove_lru();
+ }
+ self.max_size = capacity;
+ }
+
+ /// Removes and returns the least recently used key-value pair as a tuple.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use lru_cache::LruCache;
+ ///
+ /// let mut cache = LruCache::new(2);
+ ///
+ /// cache.insert(1, "a");
+ /// cache.insert(2, "b");
+ ///
+ /// assert_eq!(cache.remove_lru(), Some((1, "a")));
+ /// assert_eq!(cache.len(), 1);
+ /// ```
+ #[inline]
+ pub fn remove_lru(&mut self) -> Option<(K, V)> {
+ self.map.pop_front()
+ }
+
+ /// Returns the number of key-value pairs in the cache.
+ pub fn len(&self) -> usize { self.map.len() }
+
+ /// Returns `true` if the cache contains no key-value pairs.
+ pub fn is_empty(&self) -> bool { self.map.is_empty() }
+
+ /// Removes all key-value pairs from the cache.
+ pub fn clear(&mut self) { self.map.clear(); }
+
+ /// Returns an iterator over the cache's key-value pairs in least- to most-recently-used order.
+ ///
+ /// Accessing the cache through the iterator does _not_ affect the cache's LRU state.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use lru_cache::LruCache;
+ ///
+ /// let mut cache = LruCache::new(2);
+ ///
+ /// cache.insert(1, 10);
+ /// cache.insert(2, 20);
+ /// cache.insert(3, 30);
+ ///
+ /// let kvs: Vec<_> = cache.iter().collect();
+ /// assert_eq!(kvs, [(&2, &20), (&3, &30)]);
+ /// ```
+ pub fn iter(&self) -> Iter<K, V> { Iter(self.map.iter()) }
+
+ /// Returns an iterator over the cache's key-value pairs in least- to most-recently-used order,
+ /// with mutable references to the values.
+ ///
+ /// Accessing the cache through the iterator does _not_ affect the cache's LRU state.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use lru_cache::LruCache;
+ ///
+ /// let mut cache = LruCache::new(2);
+ ///
+ /// cache.insert(1, 10);
+ /// cache.insert(2, 20);
+ /// cache.insert(3, 30);
+ ///
+ /// let mut n = 2;
+ ///
+ /// for (k, v) in cache.iter_mut() {
+ /// assert_eq!(*k, n);
+ /// assert_eq!(*v, n * 10);
+ /// *v *= 10;
+ /// n += 1;
+ /// }
+ ///
+ /// assert_eq!(n, 4);
+ /// assert_eq!(cache.get_mut(&2), Some(&mut 200));
+ /// assert_eq!(cache.get_mut(&3), Some(&mut 300));
+ /// ```
+ pub fn iter_mut(&mut self) -> IterMut<K, V> { IterMut(self.map.iter_mut()) }
+}
+
+impl<K: Eq + Hash, V, S: BuildHasher> Extend<(K, V)> for LruCache<K, V, S> {
+ fn extend<I: IntoIterator<Item=(K, V)>>(&mut self, iter: I) {
+ for (k, v) in iter {
+ self.insert(k, v);
+ }
+ }
+}
+
+impl<K: fmt::Debug + Eq + Hash, V: fmt::Debug, S: BuildHasher> fmt::Debug for LruCache<K, V, S> {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ f.debug_map().entries(self.iter().rev()).finish()
+ }
+}
+
+impl<K: Eq + Hash, V, S: BuildHasher> IntoIterator for LruCache<K, V, S> {
+ type Item = (K, V);
+ type IntoIter = IntoIter<K, V>;
+
+ fn into_iter(self) -> IntoIter<K, V> {
+ IntoIter(self.map.into_iter())
+ }
+}
+
+impl<'a, K: Eq + Hash, V, S: BuildHasher> IntoIterator for &'a LruCache<K, V, S> {
+ 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 + Hash, V, S: BuildHasher> IntoIterator for &'a mut LruCache<K, V, S> {
+ type Item = (&'a K, &'a mut V);
+ type IntoIter = IterMut<'a, K, V>;
+ fn into_iter(self) -> IterMut<'a, K, V> { self.iter_mut() }
+}
+
+/// An iterator over a cache's key-value pairs in least- to most-recently-used order.
+///
+/// # Examples
+///
+/// ```
+/// use lru_cache::LruCache;
+///
+/// let mut cache = LruCache::new(2);
+///
+/// cache.insert(1, 10);
+/// cache.insert(2, 20);
+/// cache.insert(3, 30);
+///
+/// let mut n = 2;
+///
+/// for (k, v) in cache {
+/// assert_eq!(k, n);
+/// assert_eq!(v, n * 10);
+/// n += 1;
+/// }
+///
+/// assert_eq!(n, 4);
+/// ```
+#[derive(Clone)]
+pub struct IntoIter<K, V>(linked_hash_map::IntoIter<K, V>);
+
+impl<K, V> Iterator for IntoIter<K, V> {
+ type Item = (K, V);
+
+ fn next(&mut self) -> Option<(K, V)> {
+ self.0.next()
+ }
+
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ self.0.size_hint()
+ }
+}
+
+impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
+ fn next_back(&mut self) -> Option<(K, V)> {
+ self.0.next_back()
+ }
+}
+
+impl<K, V> ExactSizeIterator for IntoIter<K, V> {
+ fn len(&self) -> usize {
+ self.0.len()
+ }
+}
+
+/// An iterator over a cache's key-value pairs in least- to most-recently-used order.
+///
+/// Accessing a cache through the iterator does _not_ affect the cache's LRU state.
+pub struct Iter<'a, K: 'a, V: 'a>(linked_hash_map::Iter<'a, K, V>);
+
+impl<'a, K, V> Clone for Iter<'a, K, V> {
+ fn clone(&self) -> Iter<'a, K, V> { Iter(self.0.clone()) }
+}
+
+impl<'a, K, V> Iterator for Iter<'a, K, V> {
+ type Item = (&'a K, &'a V);
+ fn next(&mut self) -> Option<(&'a K, &'a V)> { self.0.next() }
+ fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
+}
+
+impl<'a, K, V> DoubleEndedIterator for Iter<'a, K, V> {
+ fn next_back(&mut self) -> Option<(&'a K, &'a V)> { self.0.next_back() }
+}
+
+impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {
+ fn len(&self) -> usize { self.0.len() }
+}
+
+/// An iterator over a cache's key-value pairs in least- to most-recently-used order with mutable
+/// references to the values.
+///
+/// Accessing a cache through the iterator does _not_ affect the cache's LRU state.
+pub struct IterMut<'a, K: 'a, V: 'a>(linked_hash_map::IterMut<'a, K, V>);
+
+impl<'a, K, V> Iterator for IterMut<'a, K, V> {
+ type Item = (&'a K, &'a mut V);
+ fn next(&mut self) -> Option<(&'a K, &'a mut V)> { self.0.next() }
+ fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
+}
+
+impl<'a, K, V> DoubleEndedIterator for IterMut<'a, K, V> {
+ fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> { self.0.next_back() }
+}
+
+impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> {
+ fn len(&self) -> usize { self.0.len() }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::LruCache;
+
+ #[test]
+ fn test_put_and_get() {
+ let mut cache = LruCache::new(2);
+ cache.insert(1, 10);
+ cache.insert(2, 20);
+ assert_eq!(cache.get_mut(&1), Some(&mut 10));
+ assert_eq!(cache.get_mut(&2), Some(&mut 20));
+ assert_eq!(cache.len(), 2);
+ }
+
+ #[test]
+ fn test_put_update() {
+ let mut cache = LruCache::new(1);
+ cache.insert("1", 10);
+ cache.insert("1", 19);
+ assert_eq!(cache.get_mut("1"), Some(&mut 19));
+ assert_eq!(cache.len(), 1);
+ }
+
+ #[test]
+ fn test_contains_key() {
+ let mut cache = LruCache::new(1);
+ cache.insert("1", 10);
+ assert_eq!(cache.contains_key("1"), true);
+ }
+
+ #[test]
+ fn test_expire_lru() {
+ let mut cache = LruCache::new(2);
+ cache.insert("foo1", "bar1");
+ cache.insert("foo2", "bar2");
+ cache.insert("foo3", "bar3");
+ assert!(cache.get_mut("foo1").is_none());
+ cache.insert("foo2", "bar2update");
+ cache.insert("foo4", "bar4");
+ assert!(cache.get_mut("foo3").is_none());
+ }
+
+ #[test]
+ fn test_pop() {
+ let mut cache = LruCache::new(2);
+ cache.insert(1, 10);
+ cache.insert(2, 20);
+ assert_eq!(cache.len(), 2);
+ let opt1 = cache.remove(&1);
+ assert!(opt1.is_some());
+ assert_eq!(opt1.unwrap(), 10);
+ assert!(cache.get_mut(&1).is_none());
+ assert_eq!(cache.len(), 1);
+ }
+
+ #[test]
+ fn test_change_capacity() {
+ let mut cache = LruCache::new(2);
+ assert_eq!(cache.capacity(), 2);
+ cache.insert(1, 10);
+ cache.insert(2, 20);
+ cache.set_capacity(1);
+ assert!(cache.get_mut(&1).is_none());
+ assert_eq!(cache.capacity(), 1);
+ }
+
+ #[test]
+ fn test_debug() {
+ let mut cache = LruCache::new(3);
+ cache.insert(1, 10);
+ cache.insert(2, 20);
+ cache.insert(3, 30);
+ assert_eq!(format!("{:?}", cache), "{3: 30, 2: 20, 1: 10}");
+ cache.insert(2, 22);
+ assert_eq!(format!("{:?}", cache), "{2: 22, 3: 30, 1: 10}");
+ cache.insert(6, 60);
+ assert_eq!(format!("{:?}", cache), "{6: 60, 2: 22, 3: 30}");
+ cache.get_mut(&3);
+ assert_eq!(format!("{:?}", cache), "{3: 30, 6: 60, 2: 22}");
+ cache.set_capacity(2);
+ assert_eq!(format!("{:?}", cache), "{3: 30, 6: 60}");
+ }
+
+ #[test]
+ fn test_remove() {
+ let mut cache = LruCache::new(3);
+ cache.insert(1, 10);
+ cache.insert(2, 20);
+ cache.insert(3, 30);
+ cache.insert(4, 40);
+ cache.insert(5, 50);
+ cache.remove(&3);
+ cache.remove(&4);
+ assert!(cache.get_mut(&3).is_none());
+ assert!(cache.get_mut(&4).is_none());
+ cache.insert(6, 60);
+ cache.insert(7, 70);
+ cache.insert(8, 80);
+ assert!(cache.get_mut(&5).is_none());
+ assert_eq!(cache.get_mut(&6), Some(&mut 60));
+ assert_eq!(cache.get_mut(&7), Some(&mut 70));
+ assert_eq!(cache.get_mut(&8), Some(&mut 80));
+ }
+
+ #[test]
+ fn test_clear() {
+ let mut cache = LruCache::new(2);
+ cache.insert(1, 10);
+ cache.insert(2, 20);
+ cache.clear();
+ assert!(cache.get_mut(&1).is_none());
+ assert!(cache.get_mut(&2).is_none());
+ assert_eq!(format!("{:?}", cache), "{}");
+ }
+
+ #[test]
+ fn test_iter() {
+ let mut cache = LruCache::new(3);
+ cache.insert(1, 10);
+ cache.insert(2, 20);
+ cache.insert(3, 30);
+ cache.insert(4, 40);
+ cache.insert(5, 50);
+ assert_eq!(cache.iter().collect::<Vec<_>>(),
+ [(&3, &30), (&4, &40), (&5, &50)]);
+ assert_eq!(cache.iter_mut().collect::<Vec<_>>(),
+ [(&3, &mut 30), (&4, &mut 40), (&5, &mut 50)]);
+ assert_eq!(cache.iter().rev().collect::<Vec<_>>(),
+ [(&5, &50), (&4, &40), (&3, &30)]);
+ assert_eq!(cache.iter_mut().rev().collect::<Vec<_>>(),
+ [(&5, &mut 50), (&4, &mut 40), (&3, &mut 30)]);
+ }
+}