qlrumap 0.1.0

An LRU HashMap with an optional passive ttl feature.
Documentation
use std::time::Duration;

#[cfg(feature = "fake-clock")]
use sn_fake_clock::FakeClock as Instant;

use qlrumap::LruMap;

#[cfg(test)]
fn delay(secs: u64) {
  #[cfg(not(feature = "sn_fake_clock"))]
  std::thread::sleep(Duration::from_secs(secs));

  // Pretend to wait more than 2s and run cleanup again
  #[cfg(feature = "sn_fake_clock")]
  Instant::advance_time(secs * 1000);
}


#[test]
fn single_entry() {
  // nodes will expire after 1 second of being idle
  let ttl = Duration::from_secs(1);

  let mut map = LruMap::with_ttl(ttl);

  map.insert("hello", "world");

  // "wait" 2 seconds
  delay(2);

  let mut drain = map.drain_timedout();

  assert_eq!(drain.next(), Some(("hello", "world")));
  assert_eq!(drain.next(), None);
}


#[test]
fn collect() {
  let ttl = Duration::from_secs(1);

  let mut map = LruMap::with_ttl(ttl);

  map.insert("hello", "world");

  // "wait" 2 seconds
  delay(2);

  // This drain should not drain any entries
  let drain = map.drain_timedout();


  let v: Vec<(&str, &str)> = drain.collect();

  assert_eq!(v.len(), 1);
  assert_eq!(v[0].0, "hello");
  assert_eq!(v[0].1, "world");
}


#[test]
fn step_by_step() {
  // nodes will expire after being idle for 3 seconds
  let ttl = Duration::from_secs(3);

  // 0 seconds

  let mut map = LruMap::with_ttl(ttl);
  map.insert("hello", "world");

  delay(1);

  // 1 second

  map.insert("moo", "cow");

  delay(1);

  // 2 seconds

  // This drain should not drain any entries
  let mut drain = map.drain_timedout();
  assert_eq!(drain.next(), None);
  drop(drain);

  delay(1);

  // 3 seconds

  // This shgould drain one node
  let mut drain = map.drain_timedout();
  assert_eq!(drain.next(), Some(("hello", "world")));
  assert_eq!(drain.next(), None);
  drop(drain);

  delay(1);

  // 4 seconds

  // This shgould drain one node
  let mut drain = map.drain_timedout();
  assert_eq!(drain.next(), Some(("moo", "cow")));
  assert_eq!(drain.next(), None);
  drop(drain);


  assert!(map.is_empty());
}

// vim: set ft=rust et sw=2 ts=2 sts=2 cinoptions=2 tw=79 :