Skip to content

Commit

Permalink
move TimedLruCache to util module
Browse files Browse the repository at this point in the history
  • Loading branch information
shouya committed Sep 27, 2024
1 parent c808aca commit fa253d1
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 52 deletions.
47 changes: 0 additions & 47 deletions src/cache.rs

This file was deleted.

4 changes: 1 addition & 3 deletions src/client/cache.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
use std::sync::Arc;

use crate::cache::TimedLruCache;

use mime::Mime;
use reqwest::header::HeaderMap;
use url::Url;

use crate::{Error, Result};
use crate::{util::TimedLruCache, Error, Result};

pub type ResponseCache = TimedLruCache<Url, Response>;

Expand Down
2 changes: 1 addition & 1 deletion src/filter/full_text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use url::Url;

use crate::cache::TimedLruCache;
use crate::client::{self, Client};
use crate::feed::{Feed, Post};
use crate::html::convert_relative_url;
use crate::util::TimedLruCache;
use crate::{ConfigError, Error, Result};

use super::html::{KeepElement, KeepElementConfig};
Expand Down
1 change: 0 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
mod cache;
mod cli;
mod client;
mod config;
Expand Down
48 changes: 48 additions & 0 deletions src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,51 @@ impl<'a, T> Iterator for SingleOrVecIter<'a, T> {
}
}
}

use std::{
hash::Hash,
num::NonZeroUsize,
sync::RwLock,
time::{Duration, Instant},
};

use lru::LruCache;

pub struct Timed<T> {
value: T,
created: Instant,
}

pub struct TimedLruCache<K: Hash + Eq, V: Clone> {
map: RwLock<LruCache<K, Timed<V>>>,
timeout: Duration,
}

impl<K: Hash + Eq, V: Clone> TimedLruCache<K, V> {
pub fn new(max_entries: usize, timeout: Duration) -> Self {
let max_entries = max_entries.try_into().unwrap_or(NonZeroUsize::MIN);
Self {
map: RwLock::new(LruCache::new(max_entries)),
timeout,
}
}

pub fn get_cached(&self, key: &K) -> Option<V> {
let mut map = self.map.write().ok()?;
let entry = map.get(key)?;
if entry.created.elapsed() > self.timeout {
map.pop(key);
return None;
}
Some(entry.value.clone())
}

pub fn insert(&self, key: K, value: V) -> Option<()> {
let timed = Timed {
value,
created: Instant::now(),
};
self.map.write().ok()?.push(key, timed);
Some(())
}
}

0 comments on commit fa253d1

Please sign in to comment.