blob: b8c78c6fd58e2ae7b6042cf4a3cefacd7d019286 [file] [log] [blame]
QUICHE teama6ef0a62019-03-07 20:34:33 -05001// Copyright (c) 2018 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef QUICHE_QUIC_CORE_QUIC_LRU_CACHE_H_
6#define QUICHE_QUIC_CORE_QUIC_LRU_CACHE_H_
7
8#include <memory>
9
10#include "net/third_party/quiche/src/quic/platform/api/quic_containers.h"
11#include "net/third_party/quiche/src/quic/platform/api/quic_flag_utils.h"
12#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
13
14namespace quic {
15
16// A LRU cache that maps from type Key to Value* in QUIC.
17// This cache CANNOT be shared by multiple threads (even with locks) because
18// Value* returned by Lookup() can be invalid if the entry is evicted by other
19// threads.
20template <class K, class V>
21class QuicLRUCache {
22 public:
23 explicit QuicLRUCache(size_t capacity) : capacity_(capacity) {}
24 QuicLRUCache(const QuicLRUCache&) = delete;
25 QuicLRUCache& operator=(const QuicLRUCache&) = delete;
26
27 // Inserts one unit of |key|, |value| pair to the cache. Cache takes ownership
28 // of inserted |value|.
29 void Insert(const K& key, std::unique_ptr<V> value) {
30 auto it = cache_.find(key);
31 if (it != cache_.end()) {
32 cache_.erase(it);
33 }
34 cache_.emplace(key, std::move(value));
35
36 if (cache_.size() > capacity_) {
37 cache_.pop_front();
38 }
39 DCHECK_LE(cache_.size(), capacity_);
40 }
41
42 // If cache contains an entry for |key|, return a pointer to it. This returned
43 // value is guaranteed to be valid until Insert or Clear.
44 // Else return nullptr.
45 V* Lookup(const K& key) {
46 auto it = cache_.find(key);
47 if (it == cache_.end()) {
48 return nullptr;
49 }
50
51 std::unique_ptr<V> value = std::move(it->second);
52 cache_.erase(it);
53 auto result = cache_.emplace(key, std::move(value));
54 DCHECK(result.second);
55 return result.first->second.get();
56 }
57
58 // Removes all entries from the cache.
59 void Clear() { cache_.clear(); }
60
61 // Returns maximum size of the cache.
62 size_t MaxSize() const { return capacity_; }
63
64 // Returns current size of the cache.
65 size_t Size() const { return cache_.size(); }
66
67 private:
68 QuicLinkedHashMap<K, std::unique_ptr<V>> cache_;
69 const size_t capacity_;
70};
71
72} // namespace quic
73
74#endif // QUICHE_QUIC_CORE_QUIC_LRU_CACHE_H_