nip10: fetch unknown replied-to notes

Signed-off-by: William Casarin <jb55@jb55.com>
This commit is contained in:
William Casarin
2024-05-24 13:20:33 -07:00
parent 135a5c99ae
commit 739e9f87f2
6 changed files with 93 additions and 16 deletions

View File

@@ -1,26 +1,40 @@
use std::rc::Rc;
use std::time::{Duration, Instant};
#[derive(Clone)]
pub struct TimeCached<T> {
last_update: Instant,
expires_in: Duration,
value: Option<T>,
refresh: Box<dyn Fn() -> T + 'static>,
refresh: Rc<dyn Fn() -> T + 'static>,
}
impl<T> TimeCached<T> {
pub fn new(expires_in: Duration, refresh: Box<dyn Fn() -> T + 'static>) -> Self {
pub fn new(expires_in: Duration, refresh: impl Fn() -> T + 'static) -> Self {
TimeCached {
last_update: Instant::now(),
expires_in,
value: None,
refresh,
refresh: Rc::new(refresh),
}
}
pub fn get(&mut self) -> &T {
if self.value.is_none() || self.last_update.elapsed() > self.expires_in {
self.last_update = Instant::now();
self.value = Some((self.refresh)());
pub fn needs_update(&self) -> bool {
self.value.is_none() || self.last_update.elapsed() > self.expires_in
}
pub fn update(&mut self) {
self.last_update = Instant::now();
self.value = Some((self.refresh)());
}
pub fn get(&self) -> Option<&T> {
self.value.as_ref()
}
pub fn get_mut(&mut self) -> &T {
if self.needs_update() {
self.update();
}
self.value.as_ref().unwrap() // This unwrap is safe because we just set the value if it was None.
}