summaryrefslogtreecommitdiffstats
path: root/api/logic/RWStorage.h
blob: 5d7923676e0194cdd1c5566eca20aceef21446d2 (plain)
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
#pragma once
#include <QWriteLocker>
#include <QReadLocker>
template <typename K, typename V>
class RWStorage
{
public:
    void add(K key, V value)
    {
        QWriteLocker l(&lock);
        cache[key] = value;
        stale_entries.remove(key);
    }
    V get(K key)
    {
        QReadLocker l(&lock);
        if(cache.contains(key))
        {
            return cache[key];
        }
        else return V();
    }
    bool get(K key, V& value)
    {
        QReadLocker l(&lock);
        if(cache.contains(key))
        {
            value = cache[key];
            return true;
        }
        else return false;
    }
    bool has(K key)
    {
        QReadLocker l(&lock);
        return cache.contains(key);
    }
    bool stale(K key)
    {
        QReadLocker l(&lock);
        if(!cache.contains(key))
            return true;
        return stale_entries.contains(key);
    }
    void setStale(K key)
    {
        QWriteLocker l(&lock);
        if(cache.contains(key))
        {
            stale_entries.insert(key);
        }
    }
    void clear()
    {
        QWriteLocker l(&lock);
        cache.clear();
        stale_entries.clear();
    }
private:
    QReadWriteLock lock;
    QMap<K, V> cache;
    QSet<K> stale_entries;
};