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
use std::collections::HashMap;
use std::time::{Duration, Instant};
use std::hash::Hash;
use std::fmt::Debug;

#[derive(Debug, Clone)]
struct Entry<V> {
  value: V,
  insert_time: Instant
}

#[derive(Debug, Clone)]
pub struct SimpleCache<K, V> {
  hashmap: Box<HashMap<K, Entry<V>>>,
  timeout: Option<Duration>
}

impl<K: Eq + Hash + Clone + Debug, V: Clone + Debug> SimpleCache<K, V> {

  /// Returns a new instance of SimpleCache
  ///
  /// ```
  /// use simple_cache_rs::SimpleCache;
  ///
  /// let mut cache: SimpleCache<i32, String> = SimpleCache::new(None);
  /// ```
  /// OR
  /// ```
  /// use simple_cache_rs::SimpleCache;
  /// use std::time::Duration;
  /// 
  /// let timeout = Duration::new(5, 0);
  /// let mut cache: SimpleCache<i32, String> = SimpleCache::new(Some(timeout));
  /// ```
  pub fn new(timeout: Option<Duration>) -> SimpleCache<K, V> {
    SimpleCache {
      hashmap: Box::new(HashMap::new()),
      timeout: timeout
    }
  }

  /// Get a value optionally from the cache, if the value is expired this method will return None
  /// and delete the value lazily from the cache.
  /// ```
  /// use simple_cache_rs::SimpleCache;
  ///
  /// let mut cache: SimpleCache<i32, String> = SimpleCache::new(None);
  ///
  /// cache.get(&1);
  /// ```
  pub fn get(&mut self, key: &K) -> Option<V> {
    let entry = self.hashmap.get(key)?;

    if let Some(timeout) = self.timeout {
      if entry.insert_time.elapsed() >= timeout {
        self.delete(key);
        return None
      }
    }

    Some(entry.value.clone())
  }

  /// Get all keys that are in the cache
  /// ```
  /// use simple_cache_rs::SimpleCache;
  ///
  /// let mut cache: SimpleCache<i32, String> = SimpleCache::new(None);
  ///
  /// cache.keys();
  /// ```
  pub fn keys(&self) -> Vec<K> {
    self.hashmap.keys()
                .map(|k| k.clone())
                .collect::<Vec<K>>()
  }

  /// Get all values that are in the cache
  /// ```
  /// use simple_cache_rs::SimpleCache;
  ///
  /// let mut cache: SimpleCache<i32, String> = SimpleCache::new(None);
  ///
  /// cache.values();
  /// ```
  pub fn values(&self) -> Vec<V> {
    self.hashmap.values()
                .map(|v| v.value.clone())
                .collect::<Vec<V>>()
  }

  /// Insert a batch of items into the cache
  /// ```
  /// use simple_cache_rs::SimpleCache;
  ///
  /// let mut cache: SimpleCache<i32, String> = SimpleCache::new(None);
  ///
  /// let items = vec!((1, String::from("a")), (2, String::from("b")));
  /// cache.insert_batch(items);
  /// ```
  pub fn insert_batch(&mut self, items: Vec<(K, V)>) {
    let i_now = Instant::now();

    for item in items {
      self.hashmap.insert(
                    item.0,
                    Entry {
                      value: item.1,
                      insert_time: i_now
                  });
    }
  }

  /// Insert an item into the cache
  /// ```
  /// use simple_cache_rs::SimpleCache;
  ///
  /// let mut cache: SimpleCache<i32, String> = SimpleCache::new(None);
  ///
  /// cache.insert(1, String::from("a"));
  /// ```
  pub fn insert(&mut self, key: K, value: V) -> Option<V> {
    let entry = self.hashmap.insert(
                              key,
                              Entry {
                                value,
                                insert_time: Instant::now()
                            })?;
    Some(entry.value)
  }

  /// Remove an entry from the cache
  /// ```
  /// use simple_cache_rs::SimpleCache;
  ///
  /// let mut cache: SimpleCache<i32, String> = SimpleCache::new(None);
  ///
  /// cache.insert(1, String::from("a"));
  /// cache.delete(&1);
  /// ```
  pub fn delete(&mut self, key: &K) -> Option<V> {
    let entry = self.hashmap.remove(key)?;
    Some(entry.value)
  }
}


#[cfg(test)]
mod tests {
  use super::SimpleCache;
  use std::{thread, time::Duration};

  #[test]
  fn insert_and_get_item() {
    let mut scache: SimpleCache<i32, String> = SimpleCache::new(None);
    scache.insert(1, String::from("hello"));

    let v = scache.get(&1);
    assert_eq!(Some(String::from("hello")), v)
  }

  #[test]
  fn insert_and_get_item_and_remove() {
    let mut scache: SimpleCache<i32, String> = SimpleCache::new(None);
    scache.insert(1, String::from("hello"));

    let v = scache.get(&1);
    assert_eq!(Some(String::from("hello")), v);

    scache.delete(&1);

    let no_value = scache.get(&1);
    assert_eq!(None, no_value)
  }

  #[test]
  fn insert_batch_test() {
    let mut scache: SimpleCache<i32, String> = SimpleCache::new(None);

    scache.insert_batch(vec![(1, String::from("hello")), (2, String::from("world"))]);

    let values = scache.values();

    assert!(values.contains(&&String::from("hello")));
    assert!(values.contains(&&String::from("world")))
  }

  #[test]
  fn get_keys_test() {
    let mut scache: SimpleCache<i32, String> = SimpleCache::new(None);
    scache.insert(1, String::from("hello"));

    let keys = scache.keys();
    assert_eq!(keys, vec!(1))
  }

  #[test]
  fn get_values_test() {
    let mut scache: SimpleCache<i32, String> = SimpleCache::new(None);
    scache.insert(1, String::from("hello"));

    let values = scache.values();
    assert_eq!(values, vec!("hello"))
  }

  #[test]
  fn insert_with_timeout() {
    let timeout = Duration::new(1, 0);
    let mut scache: SimpleCache<i32, String> = SimpleCache::new(Some(timeout));

    scache.insert(1, String::from("hello"));
    thread::sleep(Duration::new(1, 1));

    let v = scache.get(&1);
    assert_eq!(None, v)
  }
}