1 /**
2  * Retrograde Engine
3  *
4  * Authors:
5  *  Mike Bierlee, m.bierlee@lostmoment.com
6  * Copyright: 2014-2021 Mike Bierlee
7  * License:
8  *  This software is licensed under the terms of the MIT license.
9  *  The full terms of the license can be found in the LICENSE.txt file.
10  */
11 
12 module retrograde.cache;
13 
14 import retrograde.option;
15 
16 import std.exception;
17 
18 class Cache(KeyType, DataType) {
19     private DataType[KeyType] cacheData;
20 
21     public Option!DataType get(KeyType key) {
22         auto cachedData = key in cacheData;
23         if (cachedData) {
24             return Some!DataType(*cachedData);
25         }
26 
27         return None!DataType();
28     }
29 
30     public DataType getOrAdd(KeyType key, DataType delegate() fetch) {
31         auto cachedData = key in cacheData;
32         if (cachedData) {
33             return *cachedData;
34         }
35 
36         auto fetchedData = fetch();
37         add(key, fetchedData);
38         return fetchedData;
39     }
40 
41     public void add(KeyType key, DataType data) {
42         enforce(data !is null, "Given cache data is null");
43         cacheData[key] = data;
44     }
45 
46     public void remove(KeyType key) {
47         cacheData.remove(key);
48     }
49 
50     public bool has(KeyType key) {
51         return (key in cacheData) !is null;
52     }
53 
54     public void clear() {
55         cacheData.destroy();
56     }
57 }