Skip to content

Commit

Permalink
Use a memoization-like pattern to generate the schema
Browse files Browse the repository at this point in the history
  • Loading branch information
liuzicheng1987 committed Dec 28, 2024
1 parent 9535f0f commit 886017c
Showing 1 changed file with 19 additions and 7 deletions.
26 changes: 19 additions & 7 deletions include/rfl/capnproto/to_schema.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@

#include "../Literal.hpp"
#include "../Processors.hpp"
#include "../Result.hpp"
#include "../SnakeCaseToCamelCase.hpp"
#include "../Variant.hpp"
#include "../json.hpp"
#include "../parsing/schema/Type.hpp"
#include "../parsing/schema/ValidationType.hpp"
#include "../parsing/schema/make.hpp"
#include "Reader.hpp"
#include "Schema.hpp"
#include "Writer.hpp"
#include "schema/Type.hpp"
Expand All @@ -23,14 +23,26 @@ namespace rfl::capnproto {
std::string to_string_representation(
const parsing::schema::Definition& internal_schema);

template <class T, class... Ps>
struct SchemaHolder {
rfl::Result<Schema<T>> schema_;
static SchemaHolder<T, Ps...> make() noexcept {
const auto internal_schema =
parsing::schema::make<Reader, Writer, T,
Processors<SnakeCaseToCamelCase, Ps...>>();
const auto str = to_string_representation(internal_schema);
return SchemaHolder<T, Ps...>{Schema<T>::from_string(str)};
}
};

template <class T, class... Ps>
static const SchemaHolder<T, Ps...> schema_holder =
SchemaHolder<T, Ps...>::make();

/// Returns the Cap'n Proto schema for a class.
template <class T, class... Ps>
Schema<T> to_schema() noexcept {
const auto internal_schema =
parsing::schema::make<Reader, Writer, T,
Processors<SnakeCaseToCamelCase, Ps...>>();
const auto str = to_string_representation(internal_schema);
return Schema<T>::from_string(str).value();
Schema<T> to_schema() {
return schema_holder<T, Ps...>.schema_.value();
}
} // namespace rfl::capnproto

Expand Down

0 comments on commit 886017c

Please sign in to comment.