Files
Library/include/Void/Functional/Memo.hpp
T
faumarayandClaude Fable 5 28b94883fd Restructure into umbrella modules (~55 -> 16 targets)
Headers move, CMake targets merge, C++ namespaces stay unchanged:
- Core: Scope, Lazy, Counted, Flags, Hash, Bits, Uuid, TypeList, TypeMap, Variant
- Functional: Pipeline, Either, Result, Retry
- Containers: Ring, Pool, PriorityQueue, LRU, Trie, Graph, DisjointSet, Bitset, Interval
- Math: +Matrix, Numeric, Random, Histogram
- Text: Str, Format, Tokenizer, Diff, Encoding, Semver
- Data: Json, Csv, Ini
- Async: Coro, Concurrency, EventBus, Observable
- Time: +Bench
- Log: Log facade + Logging framework (facade now header-only, breaking
  the Stacktrace<->Log link cycle the merge would have created)
- System: FileSystem + Process
- Configuration: +Argparse
- Unchanged: Stacktrace, Plugin, StateMachine, Testing, TestingMock, Detail

Module system fixes:
- OPTIONAL_DEPS resolution deferred to void_finalize_modules() so it no
  longer depends on the alphabetical discovery order of src/ subdirs
  (Testing -> Text would have been silently dropped).
- Every header-only module now has a tracked module.cmake; previously the
  empty src/<Name> marker dirs were untracked, so a fresh clone would have
  silently skipped those modules.
- VOID_HAS_LOGGING/CONCURRENCY/STR consumers renamed to LOG/ASYNC/TEXT.

Tests move to tests/standalone/<Umbrella>/<Feature>.cpp (Result suite files
prefixed: ResultBasic etc.). Test count verified identical (831) before and
after. README/CLAUDE.md module tables updated.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 18:50:02 +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