1use std::collections::HashMap;
5
6use jiff::Timestamp;
7use serde::de::DeserializeOwned;
8use serde::{Deserialize, Serialize};
9use serde_json::Value;
10
11#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
13pub struct Entry {
14 pub key: String,
16 pub at: Timestamp,
18 #[serde(default, skip_serializing_if = "Option::is_none")]
20 pub by: Option<String>,
21 pub value: Value,
23}
24
25pub trait Keeper {
32 fn begin(&mut self, record: &crate::Record) {
35 let _ = record;
36 }
37
38 fn kept(&mut self, entry: &Entry);
41}
42
43impl<F: FnMut(&Entry)> Keeper for F {
44 fn kept(&mut self, entry: &Entry) {
45 self(entry);
46 }
47}
48
49#[derive(Debug, Default)]
51pub(crate) struct Journal {
52 entries: Vec<Entry>,
53 places: HashMap<String, usize>,
54 pub live: bool,
56 pub time: Timestamp,
58}
59
60impl Journal {
61 pub fn new(entries: Vec<Entry>, started: Timestamp) -> Self {
63 let live = entries.is_empty();
64 let places = entries
65 .iter()
66 .enumerate()
67 .map(|(place, entry)| (entry.key.clone(), place))
68 .collect();
69 Self {
70 entries,
71 places,
72 live,
73 time: started,
74 }
75 }
76
77 pub fn recall<T: DeserializeOwned>(&mut self, key: &str) -> Option<(T, Option<String>)> {
79 let entry = &self.entries[*self.places.get(key)?];
80 let value = serde_json::from_value(entry.value.clone()).ok()?;
81 let by = entry.by.clone();
82 self.time = self.time.max(entry.at);
83 Some((value, by))
84 }
85
86 pub fn keep<T: Serialize>(&mut self, key: String, value: &T, at: Timestamp) {
88 let entry = Entry {
89 key: key.clone(),
90 at,
91 by: None,
92 value: serde_json::to_value(value).unwrap_or_default(),
93 };
94 if let Some(&place) = self.places.get(&key) {
95 self.entries[place] = entry;
96 } else {
97 self.places.insert(key, self.entries.len());
98 self.entries.push(entry);
99 }
100 }
101
102 pub fn knows(&self, key: &str) -> bool {
104 self.places.contains_key(key)
105 }
106
107 pub fn entries(&self) -> Vec<Entry> {
109 self.entries.clone()
110 }
111}
112
113pub(crate) fn stamp(text: &str) -> String {
115 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
116 for byte in text.bytes() {
117 hash ^= u64::from(byte);
118 hash = hash.wrapping_mul(0x0100_0000_01b3);
119 }
120 format!("{:08x}", hash >> 32)
121}
122
123#[cfg(test)]
124mod tests {
125 use super::{Journal, stamp};
126
127 #[test]
128 fn what_is_kept_is_recalled_by_key() {
129 let started = "2027-03-01T10:00:00Z".parse().expect("a time");
130 let mut journal = Journal::new(Vec::new(), started);
131 assert!(journal.live);
132 journal.keep(
133 "a/0/work".to_owned(),
134 &"done",
135 "2027-03-01T11:00:00Z".parse().expect("a time"),
136 );
137 let mut again = Journal::new(journal.entries(), started);
138 assert!(!again.live);
139 assert_eq!(
140 again.recall::<String>("a/0/work"),
141 Some(("done".to_owned(), None))
142 );
143 assert_eq!(again.time, "2027-03-01T11:00:00Z".parse().expect("a time"));
144 assert_eq!(again.recall::<String>("b/0/work"), None);
145 assert!(again.knows("a/0/work") && !again.knows("a/0"));
146 assert_eq!(stamp("x"), stamp("x"));
147 assert_ne!(stamp("x"), stamp("y"));
148 }
149}