Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add find_or_try_insert_with for fallible insert functions #2

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/build-and-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ jobs:
run: |
mkdir build
cd build
g++ -std=c++20 -Wall -Wextra -Wconversion -Werror -I../include ../tests/memo_cache.cpp -o memo_cache
g++ -std=c++23 -Wall -Wextra -Wconversion -Werror -I../include ../tests/memo_cache.cpp -o memo_cache

- name: Test
run: |
Expand Down
38 changes: 38 additions & 0 deletions include/memo_cache.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#include <array>
#include <concepts>
#include <cstddef>
#include <expected>
#include <functional>
#include <iterator>
#include <optional>
Expand Down Expand Up @@ -146,6 +147,43 @@ class memo_cache {
return replace_and_shift(key, f(key));
}

/// Get a value, or, if it does not exist in the cache, insert it using the value computed by f.
/// Returns a result with a reference to the found, or newly inserted value associated with the given key.
/// If f fails, the error is returned.
/// If a value is inserted, the key is cloned.
///
/// # Examples
///
/// ```
/// #include <cassert>
/// #include <memo_cache.hpp>
///
/// mc::memo_cache<int, std::string, 4> c;
///
/// assert(!c.contains(42));
///
/// auto v1 = c.find_or_try_insert_with(42,
/// [] -> std::expected<std::string, std::string> { return "The Answer"; });
///
/// assert(v1 == "The Answer");
/// assert(c.find(42).has_value());
/// assert(c.find(42).value() == "The Answer");
///
/// auto v2 = c.find_or_try_insert_with(42,
/// [] -> std::expected<std::string, std::string> { return std::unexpected{"Dunno"}; });
///
/// assert(!v2.has_value());
/// assert(v2.error() == "Dunno");
/// ```
template<typename Error>
[[nodiscard]] std::expected<std::reference_wrapper<Val>, Error> find_or_try_insert_with(const Key& key, std::function<std::expected<Val, Error>(const Key&)> &&f) {
if (auto slot = find(key); slot) {
return *slot;
}

return f(key).transform([&](auto v) { return replace_and_shift(key, std::move(v)); });
}

/// Returns `true` if the cache contains a value for the specified key.
///
/// # Examples
Expand Down