PopplerCache.h 1.59 KB
Newer Older
1 2 3 4 5 6 7
//========================================================================
//
// PopplerCache.h
//
// This file is licensed under the GPLv2 or later
//
// Copyright (C) 2009 Koji Otani <sho@bbr.jp>
8
// Copyright (C) 2009, 2010, 2017, 2018 Albert Astals Cid <aacid@kde.org>
9
// Copyright (C) 2010 Carlos Garcia Campos <carlosgc@gnome.org>
Albert Astals Cid's avatar
Albert Astals Cid committed
10
// Copyright (C) 2018 Adam Reichold <adam.reichold@t-online.de>
11 12 13 14 15 16
//
//========================================================================

#ifndef POPPLER_CACHE_H
#define POPPLER_CACHE_H

17 18
#include <algorithm>
#include <memory>
19 20
#include <utility>
#include <vector>
21

22 23
template<typename Key, typename Item>
class PopplerCache
24
{
25 26 27
public:
  PopplerCache(const PopplerCache &) = delete;
  PopplerCache& operator=(const PopplerCache &other) = delete;
28

29
  PopplerCache(std::size_t cacheSizeA) { entries.reserve(cacheSizeA); }
30

31 32 33 34 35
  /* The item returned is owned by the cache */
  Item *lookup(const Key &key) {
    if (!entries.empty() && entries.front().first == key) {
      return entries.front().second.get();
    }
36

37 38 39
    for (auto it = entries.begin(); it != entries.end(); ++it) {
      if (it->first == key) {
	auto *item = it->second.get();
40

41
	std::rotate(entries.begin(), it, std::next(it));
42

43 44 45 46 47 48
	return item;
      }
    }

    return nullptr;
  }
49
    
50 51 52 53 54 55 56 57 58 59 60
  /* The key and item pointers ownership is taken by the cache */
  void put(const Key &key, Item *item) {
    if (entries.size() == entries.capacity()) {
      entries.pop_back();
    }

    entries.emplace(entries.begin(), key, std::unique_ptr<Item>{item});
  }

private:
  std::vector<std::pair<Key, std::unique_ptr<Item>>> entries;
61 62 63
};

#endif