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
use std::marker::PhantomData;

use stc_utils::cache::Freeze;
use swc_common::TypeEq;

use crate::cache_mode::CacheMode;

#[derive(Debug)]
pub struct CacheMap<K, V, M>
where
    K: TypeEq,
    V: Freeze,
    M: CacheMode<K>,
{
    data: Vec<(K, V)>,
    _marker: PhantomData<M>,
}

impl<K, V, M> Default for CacheMap<K, V, M>
where
    K: TypeEq,
    V: Freeze,
    M: CacheMode<K>,
{
    fn default() -> Self {
        Self {
            data: Default::default(),
            _marker: Default::default(),
        }
    }
}

impl<K, V, M> CacheMap<K, V, M>
where
    K: TypeEq,
    V: Freeze,
    M: CacheMode<K>,
{
    #[inline]
    pub fn can_cache(&self, key: &K) -> bool {
        M::can_cache(key)
    }

    pub fn get(&self, key: &K) -> Option<V> {
        for (k, v) in &self.data {
            if k.type_eq(key) {
                return Some(v.clone());
            }
        }

        None
    }

    /// Returns the inserted value.
    pub fn insert(&mut self, key: K, mut value: V) -> V {
        value.freeze();

        self.data.push((key, value.clone()));

        value
    }
}