1 /**
2 Copyright: Copyright (c) 2019, Joakim Brännström. All rights reserved.
3 License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost Software License 1.0)
4 Author: Joakim Brännström (joakim.brannstrom@gmx.com)
5 
6 Based on require in `object.d` in druntime therefor the Boost license.
7 
8 A convenient function extending cachetools with a common recurring function.
9 */
10 module dextool.cachetools;
11 
12 import dextool.from;
13 
14 /***********************************
15  * Looks up key; if it exists returns corresponding value else evaluates
16  * value, adds it to the associative array and returns it.
17  * Params:
18  *      aa =     The cache.
19  *      key =    The key.
20  *      value =  The required value.
21  * Returns:
22  *      The value.
23  *
24  * Example:
25  * ---
26  * auto cache = CacheLRU!(int,string);
27  * cache.require(5, { return "5"; }());
28  * ---
29  */
30 //TODO: rename to require when the workaround for <2.082 compiles is removed.
31 V cacheToolsRequire(CT, K, V)(CT aa, K key, lazy V value = V.init)
32         if (is(CT == class) && !is(CT == V[K])) {
33     // TODO: when upgrading to a 2.082+ compiler use this constraint instead
34     //if (is(CT == from!"cachetools".CacheLRU!(K, V))) {
35     auto q = aa.get(key);
36     if (q.isNull) {
37         auto v = value;
38         aa.put(key, v);
39         return v;
40     }
41     return q.get;
42 }
43 
44 // TODO: remove this when upgrading the minimal compiler.
45 static if (__VERSION__ < 2082L) {
46     /***********************************
47  * Looks up key; if it exists returns corresponding value else evaluates
48  * value, adds it to the associative array and returns it.
49  * Params:
50  *      aa =     The associative array.
51  *      key =    The key.
52  *      value =  The required value.
53  * Returns:
54  *      The value.
55  */
56     ref V require(K, V)(ref V[K] aa, K key, lazy V value = V.init) @trusted {
57         if (auto v = key in aa) {
58             return *v;
59         }
60 
61         aa[key] = value;
62         return aa[key];
63     }
64 }