1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
/*  Copyright 2015 MaidSafe.net limited

    This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
    version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
    licence you accepted on initial access to the Software (the "Licences").

    By contributing code to the SAFE Network Software, or to this project generally, you agree to be
    bound by the terms of the MaidSafe Contributor Agreement, version 1.0, found in the root
    directory of this project at LICENSE, COPYING and CONTRIBUTOR respectively and also
    available at: http://maidsafe.net/network-platform-licensing

    Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
    under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
    OF ANY KIND, either express or implied.

    See the Licences for the specific language governing permissions and limitations relating to
    use of the SAFE Network Software.                                                                 */

#![crate_name = "lru_time_cache"]
#![crate_type = "lib"]
#![doc(html_logo_url = "http://maidsafe.net/img/Resources/branding/maidsafe_logo.fab2.png",
       html_favicon_url = "http://maidsafe.net/img/favicon.ico",
              html_root_url = "http://dirvine.github.io/dirvine/lru_time_cache/")]

//!#lru cache limited via size or time  
//! 
//! This container allows time or size to be the limiting factor for any key/value types.
//!
//!#Use
//!
//!##To use as size based LruCache 
//!
//!`let mut lru_cache = LruCache::<usize, usize>::with_capacity(size);`
//!
//!##Or as time based LruCache
//! 
//! `let time_to_live = chrono::duration::Duration::milliseconds(100);`
//!
//! `let mut lru_cache = LruCache::<usize, usize>::with_expiry_duration(time_to_live);`
//! 
//!##Or as time or size limited cache
//!
//! ` let size = 10usize;
//!     let time_to_live = chrono::duration::Duration::milliseconds(100);
//!     let mut lru_cache = LruCache::<usize, usize>::with_expiry_duration_and_capacity(time_to_live, size);`

extern crate time;

use std::usize;
use std::collections;
/// Provides a Last Recently Used caching algorithm in a container which may be limited by size or time, reordered to most recently seen.
pub struct LruCache<K, V> where K: PartialOrd + Clone {
    map: collections::BTreeMap<K, (V, time::SteadyTime)>,
    list: collections::VecDeque<K>,
    capacity: usize,
    time_to_live: time::Duration,
}
/// Constructor for size (capacity) based LruCache
impl<K, V> LruCache<K, V> where K: PartialOrd + Ord + Clone {
    pub fn with_capacity(capacity: usize) -> LruCache<K, V> {
        LruCache {
            map: collections::BTreeMap::new(),
            list: collections::VecDeque::new(),
            capacity: capacity,
            time_to_live: time::Duration::max_value(),
        }
    }
/// Constructor for time based LruCache
    pub fn with_expiry_duration(time_to_live: time::Duration) -> LruCache<K, V> {
        LruCache {
            map: collections::BTreeMap::new(),
            list: collections::VecDeque::new(),
            capacity: usize::MAX,
            time_to_live: time_to_live,
        }
    }
/// Constructor for dual feature capacity, or time based LruCache
    pub fn with_expiry_duration_and_capacity(time_to_live: time::Duration, capacity: usize) -> LruCache<K, V> {
        LruCache {
            map: collections::BTreeMap::new(),
            list: collections::VecDeque::new(),
            capacity: capacity,
            time_to_live: time_to_live,
        }
    }
/// Add a key/value pair to cache
    pub fn add(&mut self, key: K, value: V) {
        if !self.map.contains_key(&key) {
            while self.check_time_expired() || self.map.len() == self.capacity {
                self.remove_oldest_element();
            }

            self.list.push_back(key.clone());
            self.map.insert(key, (value, time::SteadyTime::now()));
        }
    }
/// Remove a key/value pair from cache
    pub fn remove(&mut self, key: K)  -> Option<V> {
        let result = self.map.remove(&key);

        if result.is_some() {
           let position = self.list.iter().enumerate().find(|a| !(*a.1 < key || *a.1 > key)).unwrap().0;
           self.list.remove(position);
           Some(result.unwrap().0)
        } else {
           None
        }
    }
/// Retrieve a value from cache
    pub fn get(&mut self, key: K) -> Option<&V> {
       let get_result = self.map.get(&key);

       if get_result.is_some() {
           let pos_in_list = self.list.iter().enumerate().find(|a| !(*a.1 < key || *a.1 > key)).unwrap().0;
           self.list.remove(pos_in_list);
           self.list.push_back(key.clone());
           Some(&get_result.unwrap().0)
       } else {
           None
       }
    }
/// Check for existence of a key
    pub fn check(&self, key: &K) -> bool {
        self.map.contains_key(key)
    }
/// Current size of cache
    pub fn len(&self) -> usize {
        self.map.len()
    }

    fn remove_oldest_element(&mut self) {
        let key = self.list.pop_front().unwrap();
        self.map.remove(&key).unwrap();
    }

    fn check_time_expired(&self) -> bool {
        if self.time_to_live == time::Duration::max_value() || self.map.len() == 0 {
            false
        } else {
            self.map.get(self.list.front().unwrap()).unwrap().1 + self.time_to_live < time::SteadyTime::now()
        }
    }
}

#[cfg(test)]
mod test {
    use time;
    extern crate rand;
    use std::thread;
    use super::LruCache;

    fn generate_random_vec<T>(len: usize) -> Vec<T> where T: rand::Rand {
        let mut vec = Vec::<T>::with_capacity(len);
        for _ in 0..len {
            vec.push(rand::random::<T>());
        }
        vec
    }

    #[test]
    fn size_only() {
        let size = 10usize;
        let mut lru_cache = LruCache::<usize, usize>::with_capacity(size);

        for i in 0..10 {
            assert_eq!(lru_cache.len(), i);
            lru_cache.add(i, i);
            assert_eq!(lru_cache.len(), i + 1);
        }

        for i in 10..1000 {
            lru_cache.add(i, i);
            assert_eq!(lru_cache.len(), size);
        }

        for _ in (0..1000).rev() {
            assert!(lru_cache.check(&(1000 - 1)));
            assert!(lru_cache.get(1000 - 1).is_some());
            assert_eq!(*lru_cache.get(1000 - 1).unwrap(), 1000 - 1);
        }
    }

    #[test]
    fn time_only() {
        let time_to_live = time::Duration::milliseconds(100);
        let mut lru_cache = LruCache::<usize, usize>::with_expiry_duration(time_to_live);

        for i in 0..10 {
            assert_eq!(lru_cache.len(), i);
            lru_cache.add(i, i);
            assert_eq!(lru_cache.len(), i + 1);
        }

        thread::sleep_ms(100);
        lru_cache.add(11, 11);

        assert_eq!(lru_cache.len(), 1);

        for i in 0..10 {
            assert_eq!(lru_cache.len(), i + 1);
            lru_cache.add(i, i);
            assert_eq!(lru_cache.len(), i + 2);
        }
    }

    #[test]
    fn time_and_size() {
        let size = 10usize;
        let time_to_live = time::Duration::milliseconds(100);
        let mut lru_cache = LruCache::<usize, usize>::with_expiry_duration_and_capacity(time_to_live, size);

        for i in 0..1000 {
            if i < size {
                assert_eq!(lru_cache.len(), i);
            }

            lru_cache.add(i, i);

            if i < size {
                assert_eq!(lru_cache.len(), i + 1);
            } else {
                assert_eq!(lru_cache.len(), size);
            }
        }

        thread::sleep_ms(100);
        lru_cache.add(1, 1);

        assert_eq!(lru_cache.len(), 1);
    }

    #[test]
    fn time_size_struct_value() {
        let size = 100usize;
        let time_to_live = time::Duration::milliseconds(100);

        #[derive(PartialEq, PartialOrd, Ord, Clone, Eq)]
        struct Temp {
            id: Vec<u8>,
        }

        let mut lru_cache = LruCache::<Temp, usize>::with_expiry_duration_and_capacity(time_to_live, size);

        for i in 0..1000 {
            if i < size {
                assert_eq!(lru_cache.len(), i);
            }

            lru_cache.add(Temp { id: generate_random_vec::<u8>(64), }, i);

            if i < size {
                assert_eq!(lru_cache.len(), i + 1);
            } else {
                assert_eq!(lru_cache.len(), size);
            }
        }

        thread::sleep_ms(100);
        lru_cache.add(Temp { id: generate_random_vec::<u8>(64), }, 1);

        assert_eq!(lru_cache.len(), 1);
    }
}