notedeck

One damus client to rule them all
git clone git://jb55.com/notedeck
Log | Files | Refs | README | LICENSE

notecache.rs (1674B)


      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(&note_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     pub bar_open: bool,
     39 }
     40 
     41 impl CachedNote {
     42     pub fn new(note: &Note<'_>) -> Self {
     43         let created_at = note.created_at();
     44         let reltime = TimeCached::new(
     45             Duration::from_secs(1),
     46             Box::new(move || time_ago_since(created_at)),
     47         );
     48         let reply = NoteReply::new(note.tags()).to_owned();
     49         let bar_open = false;
     50         CachedNote {
     51             reltime,
     52             reply,
     53             bar_open,
     54         }
     55     }
     56 
     57     pub fn reltime_str_mut(&mut self) -> &str {
     58         self.reltime.get_mut()
     59     }
     60 
     61     pub fn reltime_str(&self) -> Option<&str> {
     62         self.reltime.get().map(|x| x.as_str())
     63     }
     64 }