notecache.rs (1565B)
1 use crate::time::time_ago_since; 2 use crate::timecache::TimeCached; 3 use nostrdb::{Note, NoteKey, NoteReply, NoteReplyBuf}; 4 use std::collections::HashMap; 5 use std::time::Duration; 6 7 #[derive(Default)] 8 pub struct NoteCache { 9 pub cache: HashMap<NoteKey, CachedNote>, 10 } 11 12 impl NoteCache { 13 pub fn cached_note_or_insert_mut(&mut self, note_key: NoteKey, note: &Note) -> &mut CachedNote { 14 self.cache 15 .entry(note_key) 16 .or_insert_with(|| CachedNote::new(note)) 17 } 18 19 pub fn cached_note(&self, note_key: NoteKey) -> Option<&CachedNote> { 20 self.cache.get(¬e_key) 21 } 22 23 pub fn cache_mut(&mut self) -> &mut HashMap<NoteKey, CachedNote> { 24 &mut self.cache 25 } 26 27 pub fn cached_note_or_insert(&mut self, note_key: NoteKey, note: &Note) -> &CachedNote { 28 self.cache 29 .entry(note_key) 30 .or_insert_with(|| CachedNote::new(note)) 31 } 32 } 33 34 #[derive(Clone)] 35 pub struct CachedNote { 36 reltime: TimeCached<String>, 37 pub reply: NoteReplyBuf, 38 } 39 40 impl CachedNote { 41 pub fn new(note: &Note<'_>) -> Self { 42 let created_at = note.created_at(); 43 let reltime = TimeCached::new( 44 Duration::from_secs(1), 45 Box::new(move || time_ago_since(created_at)), 46 ); 47 let reply = NoteReply::new(note.tags()).to_owned(); 48 CachedNote { reltime, reply } 49 } 50 51 pub fn reltime_str_mut(&mut self) -> &str { 52 self.reltime.get_mut() 53 } 54 55 pub fn reltime_str(&self) -> Option<&str> { 56 self.reltime.get().map(|x| x.as_str()) 57 } 58 }