Skip to content

Commit

Permalink
[wombat/utils] Created a Cached<T> API for lazily loading values
Browse files Browse the repository at this point in the history
This allows us to create optimisations for values that do not need to be
called regularly.
  • Loading branch information
spacey-sooty committed Mar 2, 2024
1 parent 06befea commit 1034655
Show file tree
Hide file tree
Showing 2 changed files with 88 additions and 0 deletions.
31 changes: 31 additions & 0 deletions wombat/src/main/cpp/utils/Cache.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#include "utils/Cache.h"

#include "utils/Util.h"

template <typename T>
wom::utils::Cached<T>::Cached(std::function<T()> supplier)
: m_supplier{supplier}, k_timestamp{wom::utils::now()}, k_dt{20_ms} {};

template <typename T>
wom::utils::Cached<T>::Cached(std::function<T()> supplier, units::second_t dt)
: m_supplier{supplier}, k_timestamp{wom::utils::now()}, k_dt{dt} {};

template <typename T>
wom::utils::Cached<T>& wom::utils::Cached<T>::Update() {
this->k_timestamp = wom::utils::now();
this->m_value = m_supplier();
return this;
}

template <typename T>
T& wom::utils::Cached<T>::GetValue() {
if (IsStale()) {
Update();
}
return m_value;
}

template <typename T>
bool wom::utils::Cached<T>::IsStale() {
return wom::utils::now() - this->k_timestamp > k_dt;
}
57 changes: 57 additions & 0 deletions wombat/src/main/include/utils/Cache.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
#pragma once

#include <functional>

#include <units/time.h>

namespace wom {
namespace utils {

/* A class for a cached value that can be updated lazily */
template <typename T>
class Cached {
public:
/**
* Creates a new Cached<T> with the given supplier. Sets the validity period to 20 milliseconds by default.
*
* @param supplier A function that sources the value.
*/
Cached(std::function<T()> supplier);

/**
* Creates a new Cached<T> with the given supplier.
*
* @param supplier A function that sources the value.
* @param dt The validity length of the stored value.
*/
Cached(std::function<T()> supplier, units::second_t dt);

Cached(Cached&&) = default;
Cached& operator=(Cached&&) = default;

/**
* Updates the Cached class with the current timestamp and value.
*
* @return The updated class.
*/
Cached<T>& Update();

/**
* Gets the cached value.
*/
T& GetValue();

/**
* Checks whether or not the stored value is stale.
*/
inline bool IsStale();

private:
T& m_value;
std::function<T()> m_supplier;
const units::second_t k_timestamp;
const units::second_t k_dt;
};

} // namespace utils
} // namespace wom

0 comments on commit 1034655

Please sign in to comment.