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
2 changes: 1 addition & 1 deletion docs/content/_index.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
{{< card link="expected" title="std::expected" icon="book-open" subtitle="For serializing and deserializing std::expected, the C++-23 result type.">}}
{{< card link="c_arrays_and_inheritance" title="C arrays and inheritance" icon="book-open" subtitle="How reflect-cpp handles C arrays and inheritance.">}}
{{< card link="bytestring" title="rfl::Bytestring" icon="book-open" subtitle="How reflect-cpp handles binary strings for formats that support them.">}}
{{< card link="number_systems" title="rfl::Binary, rfl::Hex and rfl::Oct" icon="book-open" subtitle="For expressing numbers in different formats.">}}
{{< card link="number_systems" title="rfl::Binary, rfl::Hex, rfl::Oct and rfl::Stringified" icon="book-open" subtitle="For expressing numbers as strings in different formats.">}}
{{< card link="default_val" title="Default values" icon="book-open" subtitle="For defining default values for fields that might be absent.">}}
{{< card link="atomic" title="Atomic types" icon="book-open" subtitle="For serializing and deserializing atomic types.">}}
{{< /cards >}}
Expand Down
26 changes: 26 additions & 0 deletions docs/content/number_systems.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,29 @@ the number of digits for `rfl::Binary` will be determined by the bitsize of the
You can access the contained value using `.value()`, `.get()`, `operator()()`, `operator*()`, or `operator->()` (const and non-const overloads).

You can produce the string representation using `.str()`.

## `rfl::Stringified`

`rfl::Stringified<T>` serializes and deserializes integral values as base-10 strings. This is useful when interoperating with JavaScript/TypeScript frontends, Protobuf JSON APIs, or Snowflake-style IDs where 64-bit integers exceed IEEE-754 double precision (`2^53 - 1`).

```cpp
struct Record {
rfl::Stringified<int64_t> id;
rfl::Stringified<uint64_t> sequence;
};

const auto record = Record{
.id = 9007199254740993LL,
.sequence = 18446744073709551615ULL};
```

This results in the following JSON:

```json
{"id":"9007199254740993","sequence":"18446744073709551615"}
```

Parsing uses `std::from_chars` and returns an `rfl::Error` on empty strings, whitespace, non-numeric characters, negative values for unsigned types, or out-of-range integers.

Like `rfl::Binary`, `rfl::Hex`, and `rfl::Oct`, you can access the underlying value with `.value()`, `.get()`, `operator*()`, `operator()()`, or `operator->()`, and format it with `.str()`.

1 change: 1 addition & 0 deletions include/rfl.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
#include "rfl/SnakeCaseToCamelCase.hpp"
#include "rfl/SnakeCaseToKebabCase.hpp"
#include "rfl/SnakeCaseToPascalCase.hpp"
#include "rfl/Stringified.hpp"
#include "rfl/TaggedUnion.hpp"
#include "rfl/Timestamp.hpp"
#include "rfl/ToAllCaps.hpp"
Expand Down
188 changes: 188 additions & 0 deletions include/rfl/Stringified.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
#ifndef RFL_STRINGIFIED_HPP_
#define RFL_STRINGIFIED_HPP_

#include <array>
#include <charconv>
#include <compare>
#include <cstddef>
#include <string>
#include <string_view>
#include <system_error>
#include <type_traits>

#include "Result.hpp"

namespace rfl {

/// Wraps an integral value for base-10 string serialization and deserialization.
/// Useful for wire formats and APIs that encode 64-bit integers as JSON strings
/// to avoid IEEE-754 double precision loss (e.g. JavaScript/TypeScript clients,
/// Protobuf JSON mapping, Snowflake IDs).
/// Uses std::to_chars / std::from_chars for exact, locale-independent
/// conversion with full overflow and syntax checking.
/// @tparam T The integral type to wrap (excluding bool)
template <class T>
requires(std::is_integral_v<T> && !std::is_same_v<std::remove_cv_t<T>, bool>)
struct Stringified {
/// The underlying integral type.
using Type = T;

/// Wire representation type used by reflect-cpp.
using ReflectionType = std::string;

/// Default constructor - initializes to zero.
constexpr Stringified() noexcept : value_(0) {}

/// Constructs from the underlying integer value.
constexpr Stringified(const Type& _value) noexcept : value_(_value) {}

/// Move constructor.
constexpr Stringified(Stringified&& _other) noexcept = default;

/// Copy constructor.
constexpr Stringified(const Stringified& _other) noexcept = default;

/// Constructs from a compatible Stringified integer type.
template <class U>
requires(std::is_integral_v<U> &&
!std::is_same_v<std::remove_cv_t<U>, bool> &&
std::is_convertible_v<U, Type>)
constexpr Stringified(const Stringified<U>& _other) noexcept
: value_(static_cast<Type>(_other.get())) {}

/// Constructs from any integral type convertible to Type.
template <class U>
requires(std::is_integral_v<U> &&
!std::is_same_v<std::remove_cv_t<U>, bool> &&
!std::is_same_v<std::remove_cv_t<U>, Type> &&
std::is_convertible_v<U, Type>)
constexpr Stringified(const U& _value) noexcept
: value_(static_cast<Type>(_value)) {}

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

/// Parses a base-10 integer string into a Stringified<T>.
/// Rejects empty strings, leading/trailing whitespace, non-digit characters,
/// leading '+', negative numbers for unsigned types, and out-of-range values.
static Result<Stringified<T>> from_string(std::string_view _str) {
if (_str.empty()) {
return error("Could not parse empty string as an integer.");
}
Type parsed = 0;
const char* const begin = _str.data();
const char* const end = _str.data() + _str.size();
const auto [ptr, ec] = std::from_chars(begin, end, parsed);
if (ec == std::errc::result_out_of_range) {
return error("Integer string '" + std::string(_str) +
"' is out of range for the target type.");
}
if (ec != std::errc{} || ptr != end) {
return error("Could not parse '" + std::string(_str) +
"' as an integer.");
}
return Stringified<T>(parsed);
}

/// Factory used by reflect-cpp during deserialization.
static Result<Stringified<T>> from_reflection(std::string_view _str) {
return from_string(_str);
}

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

/// Returns the underlying integer 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_; }

/// Copy assignment operator.
constexpr Stringified& operator=(const Stringified& _other) noexcept =
default;

/// Move assignment operator.
constexpr Stringified& operator=(Stringified&& _other) noexcept = default;

/// Assigns a new integer value.
constexpr Stringified& operator=(const Type& _value) noexcept {
value_ = _value;
return *this;
}

/// Assigns from a compatible integral type.
template <class U>
requires(std::is_integral_v<U> &&
!std::is_same_v<std::remove_cv_t<U>, bool> &&
!std::is_same_v<std::remove_cv_t<U>, Type> &&
std::is_convertible_v<U, Type>)
constexpr Stringified& operator=(const U& _value) noexcept {
value_ = static_cast<Type>(_value);
return *this;
}

/// Assigns from a compatible Stringified integer type.
template <class U>
requires(std::is_integral_v<U> &&
!std::is_same_v<std::remove_cv_t<U>, bool> &&
std::is_convertible_v<U, Type>)
constexpr Stringified& operator=(const Stringified<U>& _other) noexcept {
value_ = static_cast<Type>(_other.get());
return *this;
}

/// Spaceship comparison between Stringified<T> values.
constexpr auto operator<=>(const Stringified& _other) const noexcept =
default;

/// Equality comparison with the underlying integer type.
constexpr bool operator==(const Type& _other) const noexcept {
return value_ == _other;
}

/// Returns the value formatted as a base-10 string for serialization.
std::string reflection() const {
std::array<char, 64> buf{};
const auto [ptr, ec] =
std::to_chars(buf.data(), buf.data() + buf.size(), value_);
if (ec != std::errc{}) {
return std::to_string(value_);
}
return std::string(buf.data(), static_cast<std::size_t>(ptr - buf.data()));
}

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

/// Returns the value as a base-10 string, alias for .reflection().
std::string str() const { return reflection(); }

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

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

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

} // namespace rfl

#endif
7 changes: 6 additions & 1 deletion include/rfl/internal/HasFromReflectionMethod.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,17 @@
#include <concepts>
#include <utility>

#include "../Result.hpp"

namespace rfl::internal {

/// Satisfied by a type `T` providing `static T from_reflection(ReflectionType&&)`.
/// Satisfied by a type `T` providing `static T from_reflection(ReflectionType&&)`
/// or `static Result<T> from_reflection(ReflectionType&&)`.
template <class T>
concept HasFromReflectionMethod = requires(typename T::ReflectionType&& _r) {
{ T::from_reflection(std::move(_r)) } -> std::convertible_to<T>;
} || requires(typename T::ReflectionType&& _r) {
{ T::from_reflection(std::move(_r)) } -> std::same_as<Result<T>>;
};

} // namespace rfl::internal
Expand Down
109 changes: 109 additions & 0 deletions tests/json/test_stringified.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
#include <cstdint>
#include <limits>
#include <optional>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <vector>

#include "write_and_read.hpp"

namespace test_stringified {

struct Record {
rfl::Stringified<int64_t> id;
rfl::Stringified<uint64_t> sequence;
};

TEST(json, test_stringified_64bit_roundtrip) {
const auto record = Record{
.id = 9007199254740993LL,
.sequence = std::numeric_limits<uint64_t>::max(),
};
write_and_read(
record,
R"({"id":"9007199254740993","sequence":"18446744073709551615"})");
}

TEST(json, test_stringified_signed_and_narrow_bounds) {
struct Bounds {
rfl::Stringified<int64_t> min_i64;
rfl::Stringified<int64_t> max_i64;
rfl::Stringified<int8_t> min_i8;
rfl::Stringified<uint8_t> max_u8;
};

const auto bounds = Bounds{
.min_i64 = std::numeric_limits<int64_t>::min(),
.max_i64 = std::numeric_limits<int64_t>::max(),
.min_i8 = std::numeric_limits<int8_t>::min(),
.max_u8 = std::numeric_limits<uint8_t>::max(),
};
write_and_read(
bounds,
R"({"min_i64":"-9223372036854775808","max_i64":"9223372036854775807","min_i8":"-128","max_u8":"255"})");
}

TEST(json, test_stringified_invalid_inputs) {
struct SingleSigned {
rfl::Stringified<int64_t> v;
};
struct SingleUnsigned {
rfl::Stringified<uint64_t> v;
};
struct SingleSmall {
rfl::Stringified<int8_t> v;
};

// Bare JSON number is rejected (wire type is string).
EXPECT_FALSE(rfl::json::read<SingleSigned>(R"({"v":42})"));
// Empty string, whitespace, plus sign, float, trailing garbage.
EXPECT_FALSE(rfl::json::read<SingleSigned>(R"({"v":""})"));
EXPECT_FALSE(rfl::json::read<SingleSigned>(R"({"v":" 42"})"));
EXPECT_FALSE(rfl::json::read<SingleSigned>(R"({"v":"42 "})"));
EXPECT_FALSE(rfl::json::read<SingleSigned>(R"({"v":"+42"})"));
EXPECT_FALSE(rfl::json::read<SingleSigned>(R"({"v":"42.0"})"));
EXPECT_FALSE(rfl::json::read<SingleSigned>(R"({"v":"42abc"})"));
// Overflow / underflow.
EXPECT_FALSE(
rfl::json::read<SingleSigned>(R"({"v":"9223372036854775808"})"));
EXPECT_FALSE(
rfl::json::read<SingleSigned>(R"({"v":"-9223372036854775809"})"));
EXPECT_FALSE(
rfl::json::read<SingleUnsigned>(R"({"v":"18446744073709551616"})"));
EXPECT_FALSE(rfl::json::read<SingleUnsigned>(R"({"v":"-1"})"));
EXPECT_FALSE(rfl::json::read<SingleSmall>(R"({"v":"128"})"));
EXPECT_FALSE(rfl::json::read<SingleSmall>(R"({"v":"-129"})"));
}

TEST(json, test_stringified_accessors_and_composition) {
struct Envelope {
std::optional<rfl::Stringified<int64_t>> maybe_id;
std::vector<rfl::Stringified<uint64_t>> ids;
};

const auto env = Envelope{
.maybe_id = -42LL,
.ids = {1ULL, 9007199254740993ULL},
};
write_and_read(env, R"({"maybe_id":"-42","ids":["1","9007199254740993"]})");

rfl::Stringified<int64_t> x = 123LL;
EXPECT_EQ(x.value(), 123LL);
EXPECT_EQ(x.get(), 123LL);
EXPECT_EQ(*x, 123LL);
EXPECT_EQ(x(), 123LL);
EXPECT_EQ(x.str(), "123");
EXPECT_EQ(x, 123LL);
x.set(456LL);
EXPECT_EQ(*x.operator->(), 456LL);

const auto parsed = rfl::Stringified<int64_t>::from_string("9007199254740993");
ASSERT_TRUE(parsed.has_value());
EXPECT_EQ(parsed->value(), 9007199254740993LL);
EXPECT_FALSE(rfl::Stringified<uint64_t>::from_string("-5").has_value());

const auto schema = rfl::json::to_schema<Record>();
EXPECT_NE(schema.find(R"("type":"string")"), std::string::npos);
}

} // namespace test_stringified
Loading