use anyhow::{Context, Result};
use std::path::PathBuf;
pub struct FreshnessStore {
path: PathBuf,
}
impl FreshnessStore {
pub fn new(path: PathBuf) -> Self {
Self { path }
}
pub fn load(&self) -> Result<Option<i64>> {
match std::fs::read_to_string(&self.path) {
Ok(s) => Ok(s.trim().parse::<i64>().ok()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e).with_context(|| format!("read {}", self.path.display())),
}
}
pub fn store(&self, epoch: i64) -> Result<()> {
crate::roster::atomic_write_str(&self.path, &epoch.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trips_and_absent_is_none() {
let dir = tempfile::tempdir().unwrap();
let store = FreshnessStore::new(dir.path().join("roster.confirmed"));
assert!(store.load().unwrap().is_none()); store.store(1_760_000_000).unwrap();
assert_eq!(store.load().unwrap(), Some(1_760_000_000));
}
}