yum-mirror/slang

Making it easier to work with shaders

git clone https://git.yummers.dev/yum-mirror/slang

Ellie Hermaszewskaformatf65d756bf

master
2.5 KiB91 linesraw
1#pragma once
2#include "../core/slang-crypto.h"
3#include "../core/slang-io.h"
4#include "../core/slang-string.h"
5#include "slang.h"
6
7#include <mutex>
8
9namespace Slang
10{
11
12/// Implements a simple persistent cache on the filesystem for storing key/value pairs.
13/// Keys are SHA1 hashes and values are arbitrary blobs of data.
14/// The cache is save for concurrent access from multiple threads/processes by using
15/// a lock file within the cache directory. Furthermore, the cache implements a LRU
16/// eviction policy.
17class PersistentCache : public RefObject
18{
19public:
20    struct Desc
21    {
22        // The root directory for the cache.
23        const char* directory = nullptr;
24        // The maximum number of entries stored in the cache. By default, there is no limit.
25        Count maxEntryCount = 0;
26    };
27
28    struct Stats
29    {
30        // Number of cache hits since last resetting the stats.
31        Count hitCount;
32        // Number of cache misses since last resetting the stats.
33        Count missCount;
34        // Current number of entries in the cache.
35        Count entryCount;
36    };
37
38    using Key = SHA1::Digest;
39
40    PersistentCache(const Desc& desc);
41    ~PersistentCache();
42
43    /// Clear the contents of the cache by removing the cache index and all entry files.
44    SlangResult clear();
45
46    const Stats& getStats() const { return m_stats; }
47    void resetStats();
48
49    /// Read an entry from the cache.
50    /// Returns SLANG_OK if successful, SLANG_E_NOT_FOUND if the entry is not in the cache.
51    SlangResult readEntry(const Key& key, ISlangBlob** outData);
52
53    /// Write an entry to the cache.
54    /// Returns SLANG_OK if successful.
55    SlangResult writeEntry(const Key& key, ISlangBlob* data);
56
57private:
58    struct CacheEntry
59    {
60        Key key;
61        uint32_t age;
62    };
63
64    using CacheIndex = List<CacheEntry>;
65
66    SlangResult initialize();
67
68    String getEntryFileName(const Key& key);
69
70    SlangResult readIndex(const String& fileName, CacheIndex& outIndex);
71    SlangResult writeIndex(const String& fileName, const CacheIndex& index);
72
73    String m_cacheDirectory;
74    String m_lockFileName;
75    String m_indexFileName;
76
77    // For exclusive locking we need both a mutex (acquired first)
78    // followed by a a file lock. The mutex is needed because on Linux
79    // the file lock is only locking between processes, not threads.
80    std::mutex m_mutex;
81    Slang::LockFile m_lockFile;
82
83    Count m_maxEntryCount;
84
85    Stats m_stats;
86
87    // Used for unit tests.
88    friend struct PersistentCacheTest;
89};
90
91} // namespace Slang