Skip to content
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
23 changes: 23 additions & 0 deletions docs/content/processors.md
Original file line number Diff line number Diff line change
Expand Up @@ -549,6 +549,29 @@ The resulting JSON string looks like this:
{"type":"Person","firstName":"Homer","lastName":"Simpson","age":45}
```

## `rfl::TransformEnumNames` (`EnumSnakeCaseToKebabCase`, etc.)

Applies a whole-enum wire-name casing transform to enum fields during reading,
writing, and JSON Schema generation. Resolved wire-name tables are cached once
per `(EnumType, EnumNameTransform)` pair.

Built-in aliases:
- `rfl::EnumSnakeCaseToKebabCase`
- `rfl::EnumSnakeCaseToCamelCase`
- `rfl::EnumSnakeCaseToPascalCase`
- `rfl::EnumCamelCaseToSnakeCase`
- `rfl::EnumToLowerCase`
- `rfl::EnumToUpperCase`

```cpp
enum class CostModel { t_count, two_qubit_gate_count, gate_count };
struct Config { CostModel cost_model; };

const auto json_str = rfl::json::write<rfl::EnumSnakeCaseToKebabCase>(
Config{.cost_model = CostModel::two_qubit_gate_count});
// {"cost_model":"two-qubit-gate-count"}
```

## Writing your own processors

In principle, writing your own processors is not very difficult. You need to define a struct, which takes has a static method called `process` taking a named tuple as an input and then returning a modified named tuple. The `process` method should accept the type of the original struct as a template parameter.
Expand Down
1 change: 1 addition & 0 deletions include/rfl.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
#include "rfl/TaggedUnion.hpp"
#include "rfl/Timestamp.hpp"
#include "rfl/ToAllCaps.hpp"
#include "rfl/TransformEnumNames.hpp"
#include "rfl/UnderlyingEnums.hpp"
#include "rfl/Validator.hpp"
#include "rfl/Variant.hpp"
Expand Down
54 changes: 54 additions & 0 deletions include/rfl/TransformEnumNames.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
#ifndef RFL_TRANSFORMENUMNAMES_HPP_
#define RFL_TRANSFORMENUMNAMES_HPP_

#include <cstdint>
#include <string>
#include <string_view>

#include "common.hpp"

namespace rfl {

/// Built-in wire-name transforms applicable to C++ enum enumerator names via
/// `rfl::TransformEnumNames<...>` processors.
enum class EnumNameTransform : std::uint8_t {
none = 0,
snake_to_kebab,
snake_to_camel,
snake_to_pascal,
camel_to_snake,
to_lower,
to_upper,
};

/// Applies a built-in ASCII `EnumNameTransform` to an enumerator identifier.
RFL_API std::string apply_enum_name_transform(std::string_view _name,
EnumNameTransform _transform);

/// Processor that applies a whole-enum wire-name transform across read, write,
/// and schema generation. Resolved wire-name tables are cached once per
/// `(EnumType, EnumNameTransform)` pair.
template <EnumNameTransform _transform>
struct TransformEnumNames {
static constexpr EnumNameTransform value = _transform;

template <class StructType>
static auto process(auto&& _named_tuple) {
return _named_tuple;
}
};

using EnumSnakeCaseToKebabCase =
TransformEnumNames<EnumNameTransform::snake_to_kebab>;
using EnumSnakeCaseToCamelCase =
TransformEnumNames<EnumNameTransform::snake_to_camel>;
using EnumSnakeCaseToPascalCase =
TransformEnumNames<EnumNameTransform::snake_to_pascal>;
using EnumCamelCaseToSnakeCase =
TransformEnumNames<EnumNameTransform::camel_to_snake>;
using EnumToLowerCase = TransformEnumNames<EnumNameTransform::to_lower>;
using EnumToUpperCase = TransformEnumNames<EnumNameTransform::to_upper>;

} // namespace rfl

#endif // RFL_TRANSFORMENUMNAMES_HPP_
193 changes: 161 additions & 32 deletions include/rfl/enums.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,17 @@
#define RFL_ENUMS_HPP_

#include <charconv>
#include <exception>
#include <string>
#include <string_view>
#include <type_traits>
#include <utility>
#include <vector>

#include "Processors.hpp"
#include "Result.hpp"
#include "TransformEnumNames.hpp"
#include "internal/enum_name_transform_v.hpp"
#include "internal/enums/from_string.hpp"
#include "internal/enums/get_enum_names.hpp"
#include "internal/enums/get_enum_range.hpp"
Expand Down Expand Up @@ -56,71 +60,156 @@ constexpr auto get_enum_range() {
return internal::enums::get_enum_range<EnumType>();
}

// Converts an enum value to tis string representation.
template <class EnumType>
std::string enum_to_string(const EnumType _enum) {
if constexpr (internal::enums::is_flag_enum<EnumType>) {
namespace internal {

template <class EnumType, EnumNameTransform _transform>
inline constexpr bool has_custom_enum_names_for_transform_v =
(_transform != EnumNameTransform::none);

template <class EnumType, class ProcessorsType>
inline constexpr bool has_custom_enum_names_v =
has_custom_enum_names_for_transform_v<
std::remove_cvref_t<EnumType>, enum_name_transform_v<ProcessorsType>>;

template <class EnumType, EnumNameTransform _transform>
std::vector<std::pair<std::string, std::remove_cvref_t<EnumType>>>
build_enum_wire_names_with_transform() {
using E = std::remove_cvref_t<EnumType>;
std::vector<std::pair<std::string, E>> out;
constexpr auto enumerators = get_enumerator_array<E>();
out.reserve(enumerators.size());
for (const auto& [raw_name, val] : enumerators) {
out.emplace_back(apply_enum_name_transform(raw_name, _transform), val);
}
return out;
}

template <class EnumType, EnumNameTransform _transform>
const std::vector<std::pair<std::string, std::remove_cvref_t<EnumType>>>&
get_cached_enum_wire_names_with_transform() {
using E = std::remove_cvref_t<EnumType>;
static const auto kTable = build_enum_wire_names_with_transform<E, _transform>();
return kTable;
}

template <class EnumType, EnumNameTransform _transform>
const std::vector<std::pair<std::string, std::remove_cvref_t<EnumType>>>&
get_cached_unique_enum_wire_names_with_transform() {
using E = std::remove_cvref_t<EnumType>;
static const auto kUnique = []() {
std::vector<std::pair<std::string, E>> out;
const auto& all = get_cached_enum_wire_names_with_transform<E, _transform>();
out.reserve(all.size());
for (const auto& entry : all) {
bool dup = false;
for (const auto& existing : out) {
if (existing.first == entry.first) {
dup = true;
break;
}
}
if (!dup) {
out.push_back(entry);
}
}
return out;
}();
return kUnique;
}

template <class EnumType, EnumNameTransform _transform>
std::string enum_to_single_wire_name(const EnumType _enum) {
using E = std::remove_cvref_t<EnumType>;
if constexpr (has_custom_enum_names_for_transform_v<E, _transform>) {
for (const auto& [wire, val] :
get_cached_enum_wire_names_with_transform<E, _transform>()) {
if (val == _enum) {
return wire;
}
}
return std::to_string(static_cast<std::underlying_type_t<E>>(_enum));
} else {
return internal::enums::to_string(_enum);
}
}

template <class EnumType, EnumNameTransform _transform>
std::string enum_to_string_with_transform(const EnumType _enum) {
using E = std::remove_cvref_t<EnumType>;
if constexpr (internal::enums::is_flag_enum<E>) {
// Iterates through the enum bit by bit and matches it against the flags.
using T = std::underlying_type_t<EnumType>;
using T = std::underlying_type_t<E>;
auto val = static_cast<T>(_enum);
int i = 0;
std::vector<std::string> flags;
while (val != 0) {
const auto bit = val & static_cast<T>(1);
if (bit == 1) {
auto str = internal::enums::to_string(
static_cast<EnumType>(static_cast<T>(1) << i));
auto str = enum_to_single_wire_name<E, _transform>(
static_cast<E>(static_cast<T>(1) << i));
flags.emplace_back(std::move(str));
}
++i;
val >>= 1;
}
if (flags.empty()) {
return internal::enums::to_string(static_cast<EnumType>(0));
return enum_to_single_wire_name<E, _transform>(static_cast<E>(0));
}
return internal::strings::join("|", flags);
} else {
return internal::enums::to_string(_enum);
return enum_to_single_wire_name<E, _transform>(_enum);
}
}

// Converts a string to a value of the given enum type.
//
// By default, numeric values are accepted in addition to the declared
// enumerator names, even when they do not correspond to a declared
// enumerator (for instance, reading "4" into an enum with values 1, 2 and 3
// will produce the cast value 4). Pass enum_names_only = true (or use the
// EnumNamesOnly processor with a parser) to accept only the declared
// enumerator names instead.
template <class EnumType, bool enum_names_only = false>
Result<EnumType> string_to_enum(const std::string_view _str) {
template <class EnumType, bool enum_names_only, EnumNameTransform _transform>
Result<std::remove_cvref_t<EnumType>> string_to_enum_with_transform(
const std::string_view _str) {
using E = std::remove_cvref_t<EnumType>;
const auto make_error_msg = [](const std::string_view name) {
std::string msg = "Invalid enum value: '";
msg += name;
msg += "'. Must be one of [";
const char* sep = "";
for (const auto& p : get_enumerator_array<EnumType>()) {
msg += sep;
msg += p.first;
sep = ", ";
if constexpr (has_custom_enum_names_for_transform_v<E, _transform>) {
for (const auto& p :
get_cached_unique_enum_wire_names_with_transform<E, _transform>()) {
msg += sep;
msg += p.first;
sep = ", ";
}
} else {
for (const auto& p : get_enumerator_array<E>()) {
msg += sep;
msg += p.first;
sep = ", ";
}
}
msg += "].";
return error(msg);
};

const auto cast_numbers_or_names =
[&](const std::string_view name) -> Result<EnumType> {
const auto r = internal::enums::from_string<EnumType>(name);
if (r) {
return *r;
[&](const std::string_view name) -> Result<E> {
if constexpr (has_custom_enum_names_for_transform_v<E, _transform>) {
for (const auto& [wire, val] :
get_cached_enum_wire_names_with_transform<E, _transform>()) {
if (wire == name) {
return val;
}
}
} else {
const auto r = internal::enums::from_string<E>(name);
if (r) {
return *r;
}
}
if constexpr (enum_names_only) {
return make_error_msg(name);
} else {
if (name.empty()) {
return make_error_msg(name);
}
using Underlying = std::underlying_type_t<EnumType>;
using Underlying = std::underlying_type_t<E>;
using ParseType = std::conditional_t<
(sizeof(Underlying) < sizeof(int)), int,
std::conditional_t<
Expand All @@ -139,14 +228,14 @@ Result<EnumType> string_to_enum(const std::string_view _str) {
const auto* end = begin + name.size();
const auto [ptr, ec] = std::from_chars(begin, end, val);
if (ec == std::errc{} && ptr == end) {
return static_cast<EnumType>(val);
return static_cast<E>(val);
}
return make_error_msg(name);
}
};

if constexpr (internal::enums::is_flag_enum<EnumType>) {
using T = std::underlying_type_t<EnumType>;
if constexpr (internal::enums::is_flag_enum<E>) {
using T = std::underlying_type_t<E>;
auto res = static_cast<T>(0);
std::string_view remaining = _str;
while (true) {
Expand All @@ -162,12 +251,52 @@ Result<EnumType> string_to_enum(const std::string_view _str) {
}
remaining.remove_prefix(pos + 1);
}
return static_cast<EnumType>(res);
return static_cast<E>(res);
} else {
return cast_numbers_or_names(_str);
}
}

template <class EnumType, bool enum_names_only, EnumNameTransform _transform>
Result<std::remove_cvref_t<EnumType>> string_to_enum_with_transform_noexcept(
const std::string_view _str) noexcept {
try {
return string_to_enum_with_transform<EnumType, enum_names_only, _transform>(
_str);
} catch (const std::exception& e) {
return error(e.what());
} catch (...) {
return error("Unknown exception thrown while parsing enum value.");
}
}

} // namespace internal

// Converts an enum value to its wire string representation, honoring any
// `rfl::TransformEnumNames<...>` processor passed in `Ps...`.
template <class EnumType, class... Ps>
std::string enum_to_string(const EnumType _enum) {
return internal::enum_to_string_with_transform<
std::remove_cvref_t<EnumType>,
internal::enum_name_transform_v<Processors<Ps...>>>(_enum);
}

// Converts a string to a value of the given enum type.
//
// By default, numeric values are accepted in addition to the declared
// enumerator names, even when they do not correspond to a declared
// enumerator (for instance, reading "4" into an enum with values 1, 2 and 3
// will produce the cast value 4). Pass enum_names_only = true (or use the
// EnumNamesOnly processor with a parser) to accept only the declared
// enumerator names instead.
template <class EnumType, bool enum_names_only = false, class... Ps>
Result<std::remove_cvref_t<EnumType>> string_to_enum(
const std::string_view _str) noexcept {
return internal::string_to_enum_with_transform_noexcept<
std::remove_cvref_t<EnumType>, enum_names_only,
internal::enum_name_transform_v<Processors<Ps...>>>(_str);
}

} // namespace rfl

#endif // RFL_ENUMS_HPP_
Loading
Loading