The purpose of this class is to implement a short live cache (time to live (or TTL) being a constructor parameter) for data.
More...
Inherits ITimerCallback.
template<typename T, typename Ptr = std::shared_ptr<T>, typename Loader = std::function<Ptr()>>
class pongasoft::VST::VstUtils::ExpiringDataCache< T, Ptr, Loader >
The purpose of this class is to implement a short live cache (time to live (or TTL) being a constructor parameter) for data.
This class uses the Timer
class from the VST3 SDK to implement the timeout so that it can safely be used by all classes living in the plugin. This class is not thread safe but is intended to be used in the VST3 plugin environment where the timer (ITimerCallback::onTimer
) and caller (ExpiringDataCache::getData
) are part of the event loop and thus never called by 2 threads at the same time.
- Note
- This class offers copy/move constructors and copy/move assignment operators but care must be taken that the
Loader
can safely be moved/copied if you use them. A bad example would be a lambda capturing this
struct MyClass
{
std::shared_ptr<MyData> getMyData() const { return fMyDataCache.getData(); }
MyClass(std::shared_ptr<MyStorage> iStorage) : fStorage{iStorage},
fMyDataCache{[iStorage]() -> auto { return iStorage->loadMyData(); }, myTTL} {}
std::shared_ptr<MyStorage> fStorage{};
mutable ExpiringDataCache<MyData> fMyDataCache{};
}
- Template Parameters
-
T | the type of the data that is being cached |
Ptr | the (optional) type for the pointer. By default it is std::shared_ptr<T> because this makes the most sense for data that needs to be shared (clearly this class keeps it and then the caller via ExpiringDataCache::getData() ). You can use T* if you prefer/need to, but is not recommended. |
Loader | the (optional) type for the loader "function" which must be a "callable" object (iDataLoader() returns a Ptr ) and is by default std::function<Ptr()> . |
Main api to retrieve the data.
If the data is in the cache, it simply returns it (and extends the duration to remain in the cache by TTL). If it is not in the cache, it delegates to the loader to get it. Note that it is ok for the loader to return nullptr
, but this result will not be cached (meaning, the loader will be called every time).
- Returns
- the data (which can be
nullptr
)