Added thread-safe memoization

This commit is contained in:
Patrick Urbanke
2023-11-08 21:32:31 +01:00
parent 08806d1ebf
commit 63a9de90b3
4 changed files with 75 additions and 75 deletions
+13 -8
View File
@@ -8,6 +8,7 @@
#include <stdexcept>
#include <string>
#include "internal/Memoization.hpp"
#include "internal/StringLiteral.hpp"
#include "rfl/Literal.hpp"
#include "rfl/Result.hpp"
@@ -18,8 +19,8 @@ template <internal::StringLiteral _regex, internal::StringLiteral _name>
struct PatternValidator {
static Result<std::string> validate(const std::string& _str) noexcept {
const auto check_pattern =
[&](const auto& _regex_pattern) -> rfl::Result<std::string> {
if (!std::regex_match(_str, _regex_pattern)) {
[&](const auto _regex_pattern) -> rfl::Result<std::string> {
if (!std::regex_match(_str, *_regex_pattern)) {
return rfl::Error("String '" + _str + "' did not match format '" +
_name.str() + "': '" + _regex.str() + "'.");
}
@@ -31,20 +32,24 @@ struct PatternValidator {
private:
/// Uses a memoization pattern to init the pattern.
static rfl::Result<std::regex> regex_pattern() noexcept {
if (!regex_pattern_) {
static rfl::Result<const std::regex*> regex_pattern() noexcept {
const auto compile_pattern = [](std::optional<std::regex>* _regex_pattern) {
try {
regex_pattern_ = std::regex(_regex.str());
*_regex_pattern = std::regex(_regex.str());
} catch (std::exception& e) {
return Error(e.what());
return;
}
};
const auto& r = regex_pattern_.value(compile_pattern);
if (!r) {
return Error("Regex pattern '" + _regex.str() + "' failed to compile.");
}
return *regex_pattern_;
return &(*r);
}
private:
/// The underlying regex pattern.
static inline std::optional<std::regex> regex_pattern_;
static inline internal::Memoization<std::optional<std::regex>> regex_pattern_;
};
} // namespace rfl
+53
View File
@@ -0,0 +1,53 @@
#ifndef RFL_INTERNAL_MEMOIZATION_HPP_
#define RFL_INTERNAL_MEMOIZATION_HPP_
#include <atomic>
#include <mutex>
namespace rfl {
namespace internal {
/// For a thread-safe memoization pattern.
template <class T>
class Memoization {
public:
Memoization() { flag_.clear(); }
~Memoization() = default;
public:
/// Returns the underlying value.
template <class F>
const T& value(const F& _f) {
if (flag_.test()) {
return value_;
}
std::lock_guard<std::mutex> guard(mtx_);
if (flag_.test()) {
return value_;
}
_f(&value_);
flag_.test_and_set();
return value_;
}
private:
/// Signifies whether t_ has been set.
std::atomic_flag flag_;
/// A mutex, only needed for writing.
std::mutex mtx_;
/// The type to be initialized.
T value_;
};
} // namespace internal
} // namespace rfl
#endif
+9 -9
View File
@@ -29,6 +29,7 @@
#include "rfl/always_false.hpp"
#include "rfl/field_type.hpp"
#include "rfl/from_named_tuple.hpp"
#include "rfl/internal/Memoization.hpp"
#include "rfl/internal/StringLiteral.hpp"
#include "rfl/internal/all_fields.hpp"
#include "rfl/internal/has_reflection_method_v.hpp"
@@ -462,10 +463,7 @@ struct Parser<R, W, NamedTuple<FieldTypes...>> {
/// There are some objects that we are likely to parse many times,
/// so we only calculate these indices once.
static const auto& field_indices() noexcept {
if (field_indices_.size() == 0) {
set_field_indices();
}
return Parser<R, W, NamedTuple<FieldTypes...>>::field_indices_;
return field_indices_.value(set_field_indices<0>);
}
/// Retrieves the value from the object. This is mainly needed to
@@ -482,22 +480,24 @@ struct Parser<R, W, NamedTuple<FieldTypes...>> {
/// Builds the object field by field.
template <size_t _i = 0>
static void set_field_indices() noexcept {
static void set_field_indices(
std::unordered_map<std::string_view, std::int16_t>*
_field_indices) noexcept {
if constexpr (_i >= sizeof...(FieldTypes)) {
return;
} else {
using FieldType =
typename std::tuple_element<_i, std::tuple<FieldTypes...>>::type;
const auto name = FieldType::name_.string_view();
Parser<R, W, NamedTuple<FieldTypes...>>::field_indices_[name] =
static_cast<std::int16_t>(_i);
set_field_indices<_i + 1>();
(*_field_indices)[name] = static_cast<std::int16_t>(_i);
set_field_indices<_i + 1>(_field_indices);
}
}
private:
/// Maps each of the field names to an index signifying their order.
static inline std::unordered_map<std::string_view, std::int16_t>
static inline internal::Memoization<
std::unordered_map<std::string_view, std::int16_t>>
field_indices_;
};
-58
View File
@@ -1,58 +0,0 @@
#include <cassert>
#include <rfl.hpp>
#include "write_and_read.hpp"
void test_constr() {
std::cout << "test_constr" << std::endl;
// Custom validation for string
// Masked credit cards
using MaskedCreditCardType = rfl::Annotate<std::string, rfl::Pattern<R"(XXXX-XXXX-XXXX-\d{4})">>;
//// Nick name between 5 and 10 characters long without regex use
using NickNameType = rfl::Annotate<std::string, rfl::Length<5, 10>>;
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name = "Simpson";
//rfl::Field<"id", rfl::UUIDv4> id;
//rfl::Field<"payload", rfl::Base64Encoded> payload;
rfl::Field<"maskedCreditCard", MaskedCreditCardType> masked_credit_card;
rfl::Field<"nickName", NickNameType> nick_name;
};
try {
const auto wrong_bart = Person{
.first_name = "Bart",
//.id = "de76b905-5b32-4127-96d1-48e5321e11a6",
//.payload = "aGVsbG93b3JsZAo=",
.masked_credit_card = "XXXX-XXXX-XXXX-444A",
.nick_name = "Cosmo",
};
} catch (const std::exception &e) {
std::cout << e.what() << std::endl;
//assert(
// e.what() ==
// std::string(
// R"(String 'XXXX-XXXX-XXXX-444A' did not match format 'XXXX-XXXX-XXXX-\d{4}')"));
}
const auto correct_bart = Person{
.first_name = "Bart",
//.id = "de76b905-5b32-4127-96d1-48e5321e11a6",
//.payload = "aGVsbG93b3JsZAo=",
.masked_credit_card = "XXXX-XXXX-XXXX-4440",
.nick_name = "Cosmo",
};
write_and_read(correct_bart,
"{\"firstName\":\"Bart\",\"lastName\":\"Simpson\","
"\"id\":\"de76b905-5b32-4127-96d1-48e5321e11a6\","
"\"payload\":\"aGVsbG93b3JsZAo=\","
"\"maskedCreditCard\":\"XXXX-XXXX-XXXX-4440\","
"\"nickName\":\"Cosmo\"}");
//struct Blub {
// rfl::Field<"firstName",
// rfl::Validate<std::string, "R(XXXX-XXXX-XXXX-\d{4})">>;
//};
//
}