// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef NET_BASE_EXPIRING_CACHE_H_ #define NET_BASE_EXPIRING_CACHE_H_ #include <stddef.h> #include <map> #include <utility> #include "base/gtest_prod_util.h" #include "base/memory/raw_ref.h" #include "base/time/time.h" namespace net { template <typename KeyType, typename ValueType, typename ExpirationType> class NoopEvictionHandler { … }; // Cache implementation where all entries have an explicit expiration policy. As // new items are added, expired items will be removed first. // The template types have the following requirements: // KeyType must be LessThanComparable, Assignable, and CopyConstructible. // ValueType must be CopyConstructible and Assignable. // ExpirationType must be CopyConstructible and Assignable. // ExpirationCompare is a function class that takes two arguments of the // type ExpirationType and returns a bool. If |comp| is an instance of // ExpirationCompare, then the expression |comp(current, expiration)| shall // return true iff |current| is still valid within |expiration|. // // A simple use of this class may use base::TimeTicks, which provides a // monotonically increasing clock, for the expiration type. Because it's always // increasing, std::less<> can be used, which will simply ensure that |now| is // sorted before |expiration|: // // ExpiringCache<std::string, std::string, base::TimeTicks, // std::less<base::TimeTicks> > cache(0); // // Add a value that expires in 5 minutes // cache.Put("key1", "value1", base::TimeTicks::Now(), // base::TimeTicks::Now() + base::Minutes(5)); // // Add another value that expires in 10 minutes. // cache.Put("key2", "value2", base::TimeTicks::Now(), // base::TimeTicks::Now() + base::Minutes(10)); // // Alternatively, there may be some more complex expiration criteria, at which // point a custom functor may be used: // // struct ComplexExpirationFunctor { // bool operator()(const ComplexExpiration& now, // const ComplexExpiration& expiration) const; // }; // ExpiringCache<std::string, std::string, ComplexExpiration, // ComplexExpirationFunctor> cache(15); // // Add a value that expires once the 'sprocket' has 'cog'-ified. // cache.Put("key1", "value1", ComplexExpiration("sprocket"), // ComplexExpiration("cog")); template <typename KeyType, typename ValueType, typename ExpirationType, typename ExpirationCompare, typename EvictionHandler = NoopEvictionHandler<KeyType, ValueType, ExpirationType> > class ExpiringCache { … }; } // namespace net #endif // NET_BASE_EXPIRING_CACHE_H_