1 | //======================================================================== |
2 | // |
3 | // PopplerCache.h |
4 | // |
5 | // This file is licensed under the GPLv2 or later |
6 | // |
7 | // Copyright (C) 2009 Koji Otani <sho@bbr.jp> |
8 | // Copyright (C) 2009, 2010, 2017, 2018, 2021 Albert Astals Cid <aacid@kde.org> |
9 | // Copyright (C) 2010 Carlos Garcia Campos <carlosgc@gnome.org> |
10 | // Copyright (C) 2018 Adam Reichold <adam.reichold@t-online.de> |
11 | // |
12 | //======================================================================== |
13 | |
14 | #ifndef POPPLER_CACHE_H |
15 | #define POPPLER_CACHE_H |
16 | |
17 | #include <algorithm> |
18 | #include <memory> |
19 | #include <utility> |
20 | #include <vector> |
21 | |
22 | template<typename Key, typename Item> |
23 | class PopplerCache |
24 | { |
25 | public: |
26 | PopplerCache(const PopplerCache &) = delete; |
27 | PopplerCache &operator=(const PopplerCache &other) = delete; |
28 | |
29 | explicit PopplerCache(std::size_t cacheSizeA) { entries.reserve(cacheSizeA); } |
30 | |
31 | /* The item returned is owned by the cache */ |
32 | Item *lookup(const Key &key) |
33 | { |
34 | if (!entries.empty() && entries.front().first == key) { |
35 | return entries.front().second.get(); |
36 | } |
37 | |
38 | for (auto it = entries.begin(); it != entries.end(); ++it) { |
39 | if (it->first == key) { |
40 | auto *item = it->second.get(); |
41 | |
42 | std::rotate(entries.begin(), it, std::next(it)); |
43 | |
44 | return item; |
45 | } |
46 | } |
47 | |
48 | return nullptr; |
49 | } |
50 | |
51 | /* The key and item pointers ownership is taken by the cache */ |
52 | void put(const Key &key, Item *item) |
53 | { |
54 | if (entries.size() == entries.capacity()) { |
55 | entries.pop_back(); |
56 | } |
57 | |
58 | entries.emplace(entries.begin(), key, std::unique_ptr<Item> { item }); |
59 | } |
60 | |
61 | private: |
62 | std::vector<std::pair<Key, std::unique_ptr<Item>>> entries; |
63 | }; |
64 | |
65 | #endif |
66 | |