]> git.lyx.org Git - lyx.git/blob - src/support/Cache.h
Update sk.po
[lyx.git] / src / support / Cache.h
1 // -*- C++ -*-
2 /**
3  * \file Cache.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Guillaume Munch
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef CACHE_H
13 #define CACHE_H
14
15 #include <QCache>
16
17 #include <list>
18 #include <type_traits>
19
20 namespace lyx {
21
22 /**
23  * Cache<Key, T> implements a cache where objects are stored by copy.
24  *
25  * This is a wrapper for QCache. See the documentation of QCache:
26  * <https://doc.qt.io/qt-5/qcache.html>.
27  *
28  * It is especially useful for storing shared pointers. This turns QCache into a
29  * shared-ownership cache with no risks of dangling pointer. It is also useful
30  * for small copyable objects.
31  *
32  * Use this rather than QCache directly, to avoid naked pointers.
33  */
34 template <class Key, class Val>
35 class Cache : private QCache<Key, Val> {
36         static_assert(std::is_copy_constructible<Val>::value,
37                       "lyx::Cache only stores copyable objects!");
38         static_assert(std::is_default_constructible<Val>::value,
39                       "lyx::Cache only stores default-constructible objects!");
40         using Q = QCache<Key, Val>;
41
42 public:
43         ///
44         Cache(int max_cost = 100) : Q(max_cost) {}
45         ///
46         bool insert(Key const & key, Val object, int cost = 1)
47         {
48                 return Q::insert(key, new Val(std::move(object)), cost);
49         }
50         // Returns the default value (e.g. null pointer) if not found in the
51         // cache. If this is not convenient for your class Val, check if it exists
52         // beforehand with Cache::contains.
53         Val object(Key const & key) const
54         {
55                 if (Val * obj = Q::object(key))
56                         return *obj;
57                 return Val();
58         }
59         // Version that returns a pointer, and nullptr if the object is not present
60         Val * object_ptr(Key const & key) const { return Q::object(key); }
61         /// Synonymous for object, same remark as above.
62         Val operator[](Key const & key) const { return object(key); }
63         /// Everything from QCache except QCache::take.
64         using Q::clear;
65         using Q::contains;
66         using Q::count;
67         using Q::remove;
68         using Q::size;
69         bool empty() const { return Q::isEmpty(); }
70         std::list<Key> keys() { return Q::keys().toStdList(); }
71         int max_cost() const { return Q::maxCost(); }
72         void set_max_cost(int cost) { Q::setMaxCost(cost); }
73         int total_cost() const { return Q::totalCost(); }
74 };
75
76 } // namespace lyx
77
78 #endif