use std::collections::HashMap;
use jiff::Timestamp;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Entry {
pub key: String,
pub at: Timestamp,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub by: Option<String>,
pub value: Value,
}
pub trait Keeper {
fn begin(&mut self, record: &crate::Record) {
let _ = record;
}
fn kept(&mut self, entry: &Entry);
}
impl<F: FnMut(&Entry)> Keeper for F {
fn kept(&mut self, entry: &Entry) {
self(entry);
}
}
#[derive(Debug, Default)]
pub(crate) struct Journal {
entries: Vec<Entry>,
places: HashMap<String, usize>,
pub live: bool,
pub time: Timestamp,
}
impl Journal {
pub fn new(entries: Vec<Entry>, started: Timestamp) -> Self {
let live = entries.is_empty();
let places = entries
.iter()
.enumerate()
.map(|(place, entry)| (entry.key.clone(), place))
.collect();
Self {
entries,
places,
live,
time: started,
}
}
pub fn recall<T: DeserializeOwned>(&mut self, key: &str) -> Option<(T, Option<String>)> {
let entry = &self.entries[*self.places.get(key)?];
let value = serde_json::from_value(entry.value.clone()).ok()?;
let by = entry.by.clone();
self.time = self.time.max(entry.at);
Some((value, by))
}
pub fn keep<T: Serialize>(&mut self, key: String, value: &T, at: Timestamp) {
let entry = Entry {
key: key.clone(),
at,
by: None,
value: serde_json::to_value(value).unwrap_or_default(),
};
if let Some(&place) = self.places.get(&key) {
self.entries[place] = entry;
} else {
self.places.insert(key, self.entries.len());
self.entries.push(entry);
}
}
pub fn knows(&self, key: &str) -> bool {
self.places.contains_key(key)
}
pub fn entries(&self) -> Vec<Entry> {
self.entries.clone()
}
}
pub(crate) fn stamp(text: &str) -> String {
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
for byte in text.bytes() {
hash ^= u64::from(byte);
hash = hash.wrapping_mul(0x0100_0000_01b3);
}
format!("{:08x}", hash >> 32)
}
#[cfg(test)]
mod tests {
use super::{Journal, stamp};
#[test]
fn what_is_kept_is_recalled_by_key() {
let started = "2027-03-01T10:00:00Z".parse().expect("a time");
let mut journal = Journal::new(Vec::new(), started);
assert!(journal.live);
journal.keep(
"a/0/work".to_owned(),
&"done",
"2027-03-01T11:00:00Z".parse().expect("a time"),
);
let mut again = Journal::new(journal.entries(), started);
assert!(!again.live);
assert_eq!(
again.recall::<String>("a/0/work"),
Some(("done".to_owned(), None))
);
assert_eq!(again.time, "2027-03-01T11:00:00Z".parse().expect("a time"));
assert_eq!(again.recall::<String>("b/0/work"), None);
assert!(again.knows("a/0/work") && !again.knows("a/0"));
assert_eq!(stamp("x"), stamp("x"));
assert_ne!(stamp("x"), stamp("y"));
}
}