Files
Library/include/Void/Pipeline/Memo.hpp
T
faumarayandClaude Fable 5 da2e93c405 Finish module consolidation: fold Memo into Pipeline, dedupe Channel/Stopwatch
Completes the in-progress merges (Optional->Either/Opt, Curry+Memo->Pipeline,
ScopeGuard->Scope, String->Str):
- Pipeline/Memo.hpp now carries the full Memo API (memoize with recursion
  support, TupleHash, SimpleCache) alongside memoize_fn; old Memo module
  and its test dir removed.
- Duplicate Channel module removed; Concurrency::Channel gains empty() and
  the unique test cases (drain-after-close, multi-producer, string payloads).
- StopWatch module merged into Time::Stopwatch: one class with explicit
  start/stop/laps plus a started() factory for the auto-start RAII style;
  ScopedTimer moved along.
- Testing optional dep retargeted String->Str (pad_right lives in Str now).
- Stale empty dirs removed: src/{ScopeGuard,String,Core}, include/Void/{Core,
  Filesystem,Memo,Channel,StopWatch}.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 18:41:24 +03:00

168 lines
5.4 KiB
C++

#pragma once
#include <functional>
#include <optional>
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include <utility>
namespace Void::Pipeline
{
// ── memoize_fn ────────────────────────────────────────────────────────────────
// Wrap a unary callable with an argument-keyed call cache.
//
// auto sq = memoize_fn<int>([](int x){ return x * x; });
// sq(5); // computed once, cached forever
// sq(5); // returned from cache
namespace Detail
{
template <typename Fn, typename Arg, typename R>
struct MemoOne
{
Fn fn;
std::unordered_map<Arg, R> cache;
R operator()(const Arg& arg)
{
auto it = cache.find(arg);
if (it != cache.end()) return it->second;
auto [ins, _] = cache.emplace(arg, std::invoke(fn, arg));
return ins->second;
}
};
template <typename T>
void hash_combine(std::size_t& seed, const T& v)
{
seed ^= std::hash<T>{}(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
template <typename Tuple, std::size_t... Is>
std::size_t hash_tuple_impl(const Tuple& t, std::index_sequence<Is...>)
{
std::size_t seed = 0;
(hash_combine(seed, std::get<Is>(t)), ...);
return seed;
}
template <typename... Ts>
struct TupleHash {
std::size_t operator()(const std::tuple<Ts...>& t) const {
return hash_tuple_impl(t, std::index_sequence_for<Ts...>{});
}
};
} // namespace Detail
// Explicit Arg template parameter is required for key type deduction.
// Example: memoize_fn<int>(lambda) where lambda takes int.
template <typename Arg, typename F,
typename R = std::invoke_result_t<std::decay_t<F>, Arg>>
[[nodiscard]] auto memoize_fn(F&& fn)
{
return Detail::MemoOne<std::decay_t<F>, Arg, R>{std::forward<F>(fn), {}};
}
// ── memoize ───────────────────────────────────────────────────────────────────
// Wraps a callable F(self, Args...) -> R and caches results by argument tuple.
// The first parameter is a self-reference enabling recursive memoization.
// All arguments must be hashable. R must be copyable.
//
// auto fib = memoize([](auto& self, int n) -> int {
// if (n < 2) return n;
// return self(n-1) + self(n-2);
// });
template <typename F>
class Memoized
{
using Fn = std::decay_t<F>;
public:
explicit Memoized(F&& fn) : fn_{std::forward<F>(fn)} {}
template <typename... Args>
auto operator()(Args&&... args)
-> std::invoke_result_t<Fn, Memoized&, Args...>
{
using R = std::invoke_result_t<Fn, Memoized&, Args...>;
using Key = std::tuple<std::decay_t<Args>...>;
using Map = std::unordered_map<Key, R, Detail::TupleHash<std::decay_t<Args>...>>;
// One cache per unique (Fn, Args...) combination.
auto& cache = get_cache<R, Key, Map>();
Key key{std::forward<Args>(args)...};
const auto it = cache.find(key);
if (it != cache.end()) return it->second;
R result = std::apply([this](const auto&... a) -> R {
return std::invoke(fn_, *this, a...);
}, key);
auto [ins, _] = cache.emplace(key, std::move(result));
return ins->second;
}
// Clear the cache for a specific argument type signature.
template <typename... Args>
void clear()
{
using R = std::invoke_result_t<Fn, Memoized&, Args...>;
using Key = std::tuple<std::decay_t<Args>...>;
using Map = std::unordered_map<Key, R, Detail::TupleHash<std::decay_t<Args>...>>;
get_cache<R, Key, Map>().clear();
}
private:
Fn fn_;
template <typename R, typename Key, typename Map>
Map& get_cache()
{
static Map cache;
return cache;
}
};
// Factory function: deduce F automatically.
template <typename F>
[[nodiscard]] Memoized<F> memoize(F&& fn)
{
return Memoized<F>{std::forward<F>(fn)};
}
// ── SimpleCache<K, V> ────────────────────────────────────────────────────────
// Straightforward key→value cache with optional miss function.
template <typename K, typename V>
class SimpleCache
{
public:
// get_or_insert: compute value if not cached.
template <typename F>
[[nodiscard]] const V& get_or(const K& key, F&& compute)
{
const auto it = map_.find(key);
if (it != map_.end()) return it->second;
return map_.emplace(key, std::invoke(std::forward<F>(compute), key)).first->second;
}
[[nodiscard]] std::optional<V> get(const K& key) const
{
const auto it = map_.find(key);
if (it == map_.end()) return std::nullopt;
return it->second;
}
void put(K key, V value) { map_.insert_or_assign(std::move(key), std::move(value)); }
bool erase(const K& key) { return map_.erase(key) > 0; }
void clear() { map_.clear(); }
[[nodiscard]] std::size_t size() const noexcept { return map_.size(); }
[[nodiscard]] bool empty() const noexcept { return map_.empty(); }
private:
std::unordered_map<K, V> map_;
};
} // namespace Void::Pipeline