television_screen/
cache.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
use devicons::FileIcon;
use rustc_hash::FxHashMap;
use std::sync::Arc;

use ratatui::widgets::Paragraph;
use television_utils::cache::RingSet;

const DEFAULT_RENDERED_PREVIEW_CACHE_SIZE: usize = 10;

#[derive(Clone, Debug)]
pub struct CachedPreview<'a> {
    pub key: String,
    pub icon: Option<FileIcon>,
    pub title: String,
    pub paragraph: Arc<Paragraph<'a>>,
}

impl<'a> CachedPreview<'a> {
    pub fn new(
        key: String,
        icon: Option<FileIcon>,
        title: String,
        paragraph: Arc<Paragraph<'a>>,
    ) -> Self {
        CachedPreview {
            key,
            icon,
            title,
            paragraph,
        }
    }
}

#[derive(Debug)]
pub struct RenderedPreviewCache<'a> {
    previews: FxHashMap<String, CachedPreview<'a>>,
    ring_set: RingSet<String>,
    pub last_preview: Option<CachedPreview<'a>>,
}

impl<'a> RenderedPreviewCache<'a> {
    pub fn new(capacity: usize) -> Self {
        RenderedPreviewCache {
            previews: FxHashMap::default(),
            ring_set: RingSet::with_capacity(capacity),
            last_preview: None,
        }
    }

    pub fn get(&self, key: &str) -> Option<CachedPreview<'a>> {
        self.previews.get(key).cloned()
    }

    pub fn insert(
        &mut self,
        key: String,
        icon: Option<FileIcon>,
        title: &str,
        paragraph: &Arc<Paragraph<'a>>,
    ) {
        let cached_preview = CachedPreview::new(
            key.clone(),
            icon,
            title.to_string(),
            paragraph.clone(),
        );
        self.last_preview = Some(cached_preview.clone());
        self.previews.insert(key.clone(), cached_preview);
        if let Some(oldest_key) = self.ring_set.push(key) {
            self.previews.remove(&oldest_key);
        }
    }
}

impl Default for RenderedPreviewCache<'_> {
    fn default() -> Self {
        RenderedPreviewCache::new(DEFAULT_RENDERED_PREVIEW_CACHE_SIZE)
    }
}