Diligent Engine
 
Loading...
Searching...
No Matches
Diligent::LRUCache< KeyType, DataType, KeyHasher > Class Template Reference

A thread-safe and exception-safe LRU cache. More...

#include <LRUCache.hpp>

Public Member Functions

template<typename InitDataType>
DataType Get (const KeyType &Key, InitDataType &&InitData) noexcept(false)
 
void SetMaxSize (size_t MaxSize)
 Sets the maximum cache size.
 
size_t GetCurrSize () const
 Returns the current cache size.
 

Detailed Description

template<typename KeyType, typename DataType, typename KeyHasher = std::hash<KeyType>>
class Diligent::LRUCache< KeyType, DataType, KeyHasher >

A thread-safe and exception-safe LRU cache.

Usage example:

struct CacheData
{
    RefCntAutoPtr<IDataBlob> pData;
};
LRUCache<std::string, CacheData> Cache;
Cache.SetMaxSize(32768);
auto Data = Cache.Get("DataKey",
                      [](CacheData& Data, size_t& Size) //
                      {
                          // Create the data and return its size.
                          // May throw an exception in case of an error.
                          Data.pData = pData;
                          Size       = pData->GetSize();
                      });

The Get() method returns the data by value, as the copy kept by the cache may be released immediately after the method finishes.

If the data is not found, it is atomically initialized by the provided initializer function. If the data is found, the initializer function is not called.

Member Function Documentation

◆ Get()

template<typename KeyType, typename DataType, typename KeyHasher = std::hash<KeyType>>
template<typename InitDataType>
DataType Diligent::LRUCache< KeyType, DataType, KeyHasher >::Get ( const KeyType & Key,
InitDataType && InitData )
inline

Finds the data in the cache and returns it. If the data is not found, it is atomically created using the provided initializer.

Parameters
[in]Key- The data key.
[in]InitData- Initializer function that is called if the data is not found in the cache.
Returns
Data with the specified key, either retrieved from the cache or initialized with the InitData function.
Remarks
InitData function may throw in case of an error.