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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ reflect-cpp and sqlgen fill important gaps in C++ development. They reduce boile
- Simple [installation](https://munich-data-engineering.github.io/reflect-cpp/install)
- Simple extendability to [other serialization formats](https://munich-data-engineering.github.io/reflect-cpp/supported_formats/supporting_your_own_format)
- Simple extendability to [custom classes](https://munich-data-engineering.github.io/reflect-cpp/concepts/custom_classes)
- Read-only field aliases via [`rfl::Alias`](https://munich-data-engineering.github.io/reflect-cpp/alias) for backwards-compatible schema and config migration
- Being one of the fastest serialization libraries in existence, as demonstrated by our [benchmarks](https://munich-data-engineering.github.io/reflect-cpp/benchmarks)

<br>
Expand Down
1 change: 1 addition & 0 deletions docs/content/_index.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
{{< card link="rfl_ref" title="rfl::Box and rfl::Ref" icon="book-open" subtitle="For defining recursive structures.">}}
{{< card link="timestamps" title="rfl::Timestamp and std::chrono::duration" icon="book-open" subtitle="For serializing and deserializing timestamps and durations.">}}
{{< card link="rfl_skip" title="rfl::Skip" icon="book-open" subtitle="For skipping fields during serialization and/or deserialization.">}}
{{< card link="alias" title="rfl::Alias" icon="book-open" subtitle="For accepting read-only field aliases during deserialization.">}}
{{< card link="commented" title="rfl::Commented" icon="book-open" subtitle="For adding comments to your serialized format.">}}
{{< card link="result" title="rfl::Result" icon="book-open" subtitle="For error handling without exceptions.">}}
{{< card link="standard_containers" title="Standard containers" icon="book-open" subtitle="How reflect-cpp treats containers in the standard library.">}}
Expand Down
79 changes: 79 additions & 0 deletions docs/content/alias.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# Read-only field aliases (`rfl::Alias`)

The `rfl::Alias<"old-name", T>` wrapper declares a read-only alias for a struct field. During deserialization, `reflect-cpp` accepts **either** the canonical primary wire name **or** any declared alias. During serialization and JSON Schema generation, `reflect-cpp` **always** emits the canonical primary wire name.

This is especially useful when evolving an API or configuration format (for example, migrating legacy `kebab-case` or `camelCase` RPC keys to `snake_case`, or supporting deprecated CLI flag names) without maintaining manual key-translation tables.

## Basic usage

```cpp
#include <rfl.hpp>
#include <rfl/json.hpp>

struct Settings {
rfl::Alias<"download-dir", std::string> download_dir;
rfl::Alias<"speedLimitDown", int> speed_limit_down;
};

// Accepted on read (alias or canonical name):
const auto s = rfl::json::read<Settings>(
R"({"download-dir":"/downloads","speedLimitDown":250})").value();

// Always serialized using the canonical primary names:
const auto out = rfl::json::write(s);
// {"download_dir":"/downloads","speed_limit_down":250}
```

## Multiple aliases

Nest `rfl::Alias` wrappers to accept multiple legacy names for the same field:

```cpp
struct Settings {
rfl::Alias<"download-dir", rfl::Alias<"downloadDir", std::string>>
download_dir;
};
```

Reading `{"download_dir": "/dl"}`, `{"download-dir": "/dl"}`, or `{"downloadDir": "/dl"}` all populate `download_dir`, and writing always emits `{"download_dir":"/dl"}`.

## Semantics

- **Primary wire name:** Unchanged. It comes from the C++ field name (transformed by naming processors such as `rfl::SnakeCaseToCamelCase` or `rfl::SnakeCaseToKebabCase`, or overridden by `rfl::Rename<"canonical", ...>`).
- **Serialization (write):** Always writes the canonical primary wire name.
- **JSON Schema (`to_schema`):** Emits only the canonical primary property name (preserving inner `rfl::Description`, `rfl::Deprecated`, `rfl::DefaultVal`, and `rfl::Validator` metadata).
- **`rfl::NoExtraFields`:** Aliases are recognized as valid field names and are not rejected as unknown extra fields.
- **Conflicting / duplicate input:** If an input object specifies both the primary name and an alias (or two different aliases for the same field), deserialization fails with an error instead of silently overwriting.
- **Compile-time collision check:** If an alias on one field equals the primary wire name or an alias of a different field, compilation fails with a `static_assert`.

## Composing with other wrappers and processors

`rfl::Alias` is transparent and composes cleanly with `rfl::Rename`, `rfl::Description`, `rfl::Deprecated`, `rfl::DefaultVal`, `rfl::DefaultIfMissing`, `std::optional`, `rfl::Validator`, `rfl::Short`, `rfl::Positional`, and case-transforming processors:

```cpp
struct Config {
rfl::Rename<"download_dir", rfl::Alias<"download-dir", std::string>> dir;
rfl::Alias<"old-port", rfl::DefaultVal<int>> port = 8080;
rfl::Description<"Timeout in seconds", rfl::Alias<"timeoutSec", std::optional<int>>>
timeout_sec;
};
```

## CLI support

`rfl::cli::read` also recognizes `rfl::Alias` names as long options (including under `rfl::NoExtraFields`) and detects conflicts between aliases, canonical names, `rfl::Short`, and `rfl::Positional`:

```cpp
struct CliConfig {
rfl::Alias<"download_dir", rfl::Alias<"downloadDir", std::string>>
download_dir;
rfl::Alias<"debug", rfl::DefaultVal<rfl::Short<"v", bool>>> verbose = false;
};

// Accepts --download-dir=/dl, --download_dir=/dl, or --downloadDir=/dl
// Accepts --verbose, -v, or --debug
```

## Wrapper ergonomics

`rfl::Alias<Name, T>` provides `.value()`, `.get()`, `operator*`, `operator->`, `operator()`, implicit construction from convertible values, implicit conversion to `T&` / `const T&`, `==`, `<=>`, and `std::hash` specialization. Its default constructor is constrained on `std::is_default_constructible_v<T>`.
3 changes: 2 additions & 1 deletion docs/content/supported_formats/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ option in a token treats the next token as it would alone (`-qv false` sets
## Combining wrappers

`Short` and `Positional` can be nested with `DefaultVal`, `std::optional`,
`Description`, `Rename` and `Deprecated` in any order:
`Description`, `Rename`, `Alias` and `Deprecated` in any order:
`rfl::Description<"...", rfl::Short<"o", T>>` is `-o`, and
`rfl::DefaultVal<rfl::Positional<T>>` is positional. Put `rfl::Rename`
outermost, as in `rfl::Rename<"out", rfl::Short<"o", T>>`; inside other
Expand Down Expand Up @@ -209,6 +209,7 @@ struct Config {
| Nested struct | `--parent.child=val` | Dot-separated path |
| `rfl::Flatten<T>` | fields inlined | No prefix needed |
| `rfl::Rename<"x", T>` | `--x=val` | Bypasses kebab conversion |
| `rfl::Alias<"old", T>` | `--old=val` | Read-only long alias (also works with `NoExtraFields`) |
| `rfl::Positional<T>` | bare token | Matched in declaration order |
| `rfl::Short<"x", T>` | `-x value`, `-x=value` or `-xvalue` | Single-character alias, can be grouped (`-qv`) |

Expand Down
1 change: 1 addition & 0 deletions include/rfl.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

#include "rfl/AddStructName.hpp"
#include "rfl/AddTagsToVariants.hpp"
#include "rfl/Alias.hpp"
#include "rfl/AllOf.hpp"
#include "rfl/AllowRawPtrs.hpp"
#include "rfl/AnyOf.hpp"
Expand Down
245 changes: 245 additions & 0 deletions include/rfl/Alias.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,245 @@
#ifndef RFL_ALIAS_HPP_
#define RFL_ALIAS_HPP_

#include <compare>
#include <cstddef>
#include <functional>
#include <string_view>
#include <type_traits>
#include <utility>

#include "default.hpp"
#include "internal/StringLiteral.hpp"
#include "internal/is_alias.hpp"

namespace rfl {

/// Declares a read-only field alias accepted during deserialization while
/// always serializing (and generating schemas) under the canonical primary
/// field name.
///
/// Multiple aliases can be declared by nesting `rfl::Alias`:
/// `rfl::Alias<"download-dir", rfl::Alias<"downloadDir", std::string>>`
///
/// @tparam _name The compile-time string literal alias name accepted on read
/// @tparam T The underlying value (or wrapped field) type
template <internal::StringLiteral _name, class T>
struct Alias {
/// The underlying type.
using Type = T;

/// The alias name as a compile-time string literal.
static constexpr internal::StringLiteral alias_name_ = _name;

/// Returns the alias name as a string_view.
static constexpr std::string_view alias_name() noexcept {
return alias_name_.string_view();
}

/// Default constructor - enabled only when Type is default-constructible.
template <class U = Type>
requires std::is_default_constructible_v<U>
constexpr Alias() noexcept(std::is_nothrow_default_constructible_v<U>)
: value_() {}

/// Constructs from a const reference to the value.
constexpr Alias(const Type& _value) : value_(_value) {}

/// Constructs from an rvalue reference to the value.
constexpr Alias(Type&& _value) noexcept(
std::is_nothrow_move_constructible_v<Type>)
: value_(std::move(_value)) {}

/// Move constructor.
Alias(Alias&& _field) = default;

/// Copy constructor.
Alias(const Alias& _field) = default;

/// Copy constructor from Alias with the same alias name and a compatible
/// underlying type.
template <class U>
requires(!std::is_same_v<U, Type> && std::is_convertible_v<const U&, Type>)
constexpr Alias(const Alias<_name, U>& _field) : value_(_field.get()) {}

/// Move constructor from Alias with the same alias name and a compatible
/// underlying type.
template <class U>
requires(!std::is_same_v<U, Type> && std::is_convertible_v<U&&, Type>)
constexpr Alias(Alias<_name, U>&& _field) noexcept(
std::is_nothrow_constructible_v<Type, U&&>)
: value_(std::move(_field.value_)) {}

/// Constructs from any type convertible to Type.
template <class U>
requires(!std::is_same_v<std::remove_cvref_t<U>, Alias> &&
!std::is_same_v<std::remove_cvref_t<U>, Type> &&
!std::is_same_v<std::remove_cvref_t<U>, Default> &&
std::is_convertible_v<U, Type>)
constexpr Alias(U&& _value) noexcept(
std::is_nothrow_constructible_v<Type, U>)
: value_(std::forward<U>(_value)) {}

/// Initializes the underlying object to its default value using the Default
/// sentinel.
template <class U = Type>
requires std::is_default_constructible_v<U>
constexpr Alias(const Default&) noexcept(
std::is_nothrow_default_constructible_v<U>)
: value_() {}

/// Destructor.
~Alias() = default;

/// Returns a const reference to the underlying value.
constexpr const Type& get() const noexcept { return value_; }

/// Returns a reference to the underlying value.
constexpr Type& get() noexcept { return value_; }

/// Dereference operator - returns the underlying value.
constexpr Type& operator*() noexcept { return value_; }

/// Dereference operator (const) - returns the underlying value.
constexpr const Type& operator*() const noexcept { return value_; }

/// Function call operator - returns the underlying value.
constexpr Type& operator()() noexcept { return value_; }

/// Function call operator (const) - returns the underlying value.
constexpr const Type& operator()() const noexcept { return value_; }

/// Pointer to the underlying value.
constexpr Type* operator->() noexcept { return &value_; }

/// Pointer to the underlying value (const).
constexpr const Type* operator->() const noexcept { return &value_; }

/// Implicit conversion to a mutable reference to the underlying value.
constexpr operator Type&() noexcept { return value_; }

/// Implicit conversion to a const reference to the underlying value.
constexpr operator const Type&() const noexcept { return value_; }

/// Assigns a new value (copy).
auto& operator=(const Type& _value) {
value_ = _value;
return *this;
}

/// Assigns a new value (move).
auto& operator=(Type&& _value) noexcept(
std::is_nothrow_move_assignable_v<Type>) {
value_ = std::move(_value);
return *this;
}

/// Assigns from any type convertible to the underlying type.
template <class U>
requires(!std::is_same_v<std::remove_cvref_t<U>, Alias> &&
!std::is_same_v<std::remove_cvref_t<U>, Type> &&
!std::is_same_v<std::remove_cvref_t<U>, Default> &&
std::is_convertible_v<U, Type>)
auto& operator=(U&& _value) {
value_ = std::forward<U>(_value);
return *this;
}

/// Assigns the value to its default using the Default sentinel.
template <class U = Type>
requires std::is_default_constructible_v<U>
auto& operator=(const Default&) {
value_ = Type();
return *this;
}

/// Copy assignment operator.
Alias& operator=(const Alias& _field) = default;

/// Move assignment operator.
Alias& operator=(Alias&& _field) = default;

/// Assigns from another Alias with compatible underlying type (copy).
template <class U>
requires(!std::is_same_v<U, Type> && std::is_convertible_v<const U&, Type>)
auto& operator=(const Alias<_name, U>& _field) {
value_ = _field.get();
return *this;
}

/// Assigns from another Alias with compatible underlying type (move).
template <class U>
requires(!std::is_same_v<U, Type> && std::is_convertible_v<U&&, Type>)
auto& operator=(Alias<_name, U>&& _field) {
value_ = std::move(_field.value_);
return *this;
}

/// Sets the value (copy).
void set(const Type& _value) { value_ = _value; }

/// Sets the value (move).
void set(Type&& _value) noexcept(std::is_nothrow_move_assignable_v<Type>) {
value_ = std::move(_value);
}

/// Returns a reference to the underlying value.
constexpr Type& value() noexcept { return value_; }

/// Returns a const reference to the underlying value.
constexpr const Type& value() const noexcept { return value_; }

/// The underlying value.
Type value_;
};

/// Equality comparison between two Alias wrappers.
template <internal::StringLiteral _n1, class T1, internal::StringLiteral _n2,
class T2>
requires requires(const T1& _a, const T2& _b) { _a == _b; }
constexpr bool operator==(const Alias<_n1, T1>& _lhs,
const Alias<_n2, T2>& _rhs) {
return _lhs.value() == _rhs.value();
}

/// Three-way comparison between two Alias wrappers.
template <internal::StringLiteral _n1, class T1, internal::StringLiteral _n2,
class T2>
requires requires(const T1& _a, const T2& _b) { _a <=> _b; }
constexpr auto operator<=>(const Alias<_n1, T1>& _lhs,
const Alias<_n2, T2>& _rhs) {
return _lhs.value() <=> _rhs.value();
}

/// Equality comparison between an Alias wrapper and a non-Alias value.
template <internal::StringLiteral _n, class T, class U>
requires(!internal::is_alias<std::remove_cvref_t<U>>::value &&
requires(const T& _a, const U& _b) { _a == _b; })
constexpr bool operator==(const Alias<_n, T>& _lhs, const U& _rhs) {
return _lhs.value() == _rhs;
}

/// Three-way comparison between an Alias wrapper and a non-Alias value.
template <internal::StringLiteral _n, class T, class U>
requires(!internal::is_alias<std::remove_cvref_t<U>>::value &&
requires(const T& _a, const U& _b) { _a <=> _b; })
constexpr auto operator<=>(const Alias<_n, T>& _lhs, const U& _rhs) {
return _lhs.value() <=> _rhs;
}

} // namespace rfl

namespace std {

/// Specialization of std::hash for rfl::Alias.
template <rfl::internal::StringLiteral _name, class T>
requires requires(const T& _v) { std::hash<T>{}(_v); }
struct hash<rfl::Alias<_name, T>> {
size_t operator()(const rfl::Alias<_name, T>& _a) const {
return hash<T>{}(_a.value());
}
};

} // namespace std

#endif
4 changes: 3 additions & 1 deletion include/rfl/CamelCaseToSnakeCase.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#define RFL_CAMELCASETOSNAKECASE_HPP_

#include "Field.hpp"
#include "internal/is_alias.hpp"
#include "internal/is_rename.hpp"
#include "internal/transform_case.hpp"

Expand All @@ -18,7 +19,8 @@ struct CamelCaseToSnakeCase {
static auto process(const auto& _named_tuple) {
return _named_tuple.transform([]<class FieldType>(const FieldType& _f) {
if constexpr (FieldType::name() != "xml_content" &&
!internal::is_rename_v<typename FieldType::Type>) {
!internal::is_rename_v<
internal::remove_alias_t<typename FieldType::Type>>) {
return handle_one_field(_f);
} else {
return _f;
Expand Down
Loading
Loading