From bf1ef2288656c99ec1e4b2bcdd5d52a2d20e51fe Mon Sep 17 00:00:00 2001 From: clockblocker Date: Sat, 28 Nov 2026 11:31:53 +0100 Subject: [PATCH] Add rfl::Stringified wrapper for base-10 string-encoded integers --- docs/content/_index.md | 2 +- docs/content/number_systems.md | 26 +++ include/rfl.hpp | 1 + include/rfl/Stringified.hpp | 188 ++++++++++++++++++ .../rfl/internal/HasFromReflectionMethod.hpp | 7 +- tests/json/test_stringified.cpp | 109 ++++++++++ 6 files changed, 331 insertions(+), 2 deletions(-) create mode 100644 include/rfl/Stringified.hpp create mode 100644 tests/json/test_stringified.cpp diff --git a/docs/content/_index.md b/docs/content/_index.md index 056abfd96..ec4f11853 100644 --- a/docs/content/_index.md +++ b/docs/content/_index.md @@ -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 >}} diff --git a/docs/content/number_systems.md b/docs/content/number_systems.md index 57a35ffa0..15075d141 100644 --- a/docs/content/number_systems.md +++ b/docs/content/number_systems.md @@ -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` 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 id; + rfl::Stringified 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()`. + diff --git a/include/rfl.hpp b/include/rfl.hpp index 432fff2f6..87e1ca1b9 100644 --- a/include/rfl.hpp +++ b/include/rfl.hpp @@ -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" diff --git a/include/rfl/Stringified.hpp b/include/rfl/Stringified.hpp new file mode 100644 index 000000000..5d3ef3425 --- /dev/null +++ b/include/rfl/Stringified.hpp @@ -0,0 +1,188 @@ +#ifndef RFL_STRINGIFIED_HPP_ +#define RFL_STRINGIFIED_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#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 + requires(std::is_integral_v && !std::is_same_v, 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 + requires(std::is_integral_v && + !std::is_same_v, bool> && + std::is_convertible_v) + constexpr Stringified(const Stringified& _other) noexcept + : value_(static_cast(_other.get())) {} + + /// Constructs from any integral type convertible to Type. + template + requires(std::is_integral_v && + !std::is_same_v, bool> && + !std::is_same_v, Type> && + std::is_convertible_v) + constexpr Stringified(const U& _value) noexcept + : value_(static_cast(_value)) {} + + /// Destructor. + ~Stringified() = default; + + /// Parses a base-10 integer string into a Stringified. + /// Rejects empty strings, leading/trailing whitespace, non-digit characters, + /// leading '+', negative numbers for unsigned types, and out-of-range values. + static Result> 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(parsed); + } + + /// Factory used by reflect-cpp during deserialization. + static Result> 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 + requires(std::is_integral_v && + !std::is_same_v, bool> && + !std::is_same_v, Type> && + std::is_convertible_v) + constexpr Stringified& operator=(const U& _value) noexcept { + value_ = static_cast(_value); + return *this; + } + + /// Assigns from a compatible Stringified integer type. + template + requires(std::is_integral_v && + !std::is_same_v, bool> && + std::is_convertible_v) + constexpr Stringified& operator=(const Stringified& _other) noexcept { + value_ = static_cast(_other.get()); + return *this; + } + + /// Spaceship comparison between Stringified 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 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(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 diff --git a/include/rfl/internal/HasFromReflectionMethod.hpp b/include/rfl/internal/HasFromReflectionMethod.hpp index 8c794cf06..61d28adc6 100644 --- a/include/rfl/internal/HasFromReflectionMethod.hpp +++ b/include/rfl/internal/HasFromReflectionMethod.hpp @@ -4,12 +4,17 @@ #include #include +#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 from_reflection(ReflectionType&&)`. template concept HasFromReflectionMethod = requires(typename T::ReflectionType&& _r) { { T::from_reflection(std::move(_r)) } -> std::convertible_to; +} || requires(typename T::ReflectionType&& _r) { + { T::from_reflection(std::move(_r)) } -> std::same_as>; }; } // namespace rfl::internal diff --git a/tests/json/test_stringified.cpp b/tests/json/test_stringified.cpp new file mode 100644 index 000000000..d6fb50f81 --- /dev/null +++ b/tests/json/test_stringified.cpp @@ -0,0 +1,109 @@ +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_stringified { + +struct Record { + rfl::Stringified id; + rfl::Stringified sequence; +}; + +TEST(json, test_stringified_64bit_roundtrip) { + const auto record = Record{ + .id = 9007199254740993LL, + .sequence = std::numeric_limits::max(), + }; + write_and_read( + record, + R"({"id":"9007199254740993","sequence":"18446744073709551615"})"); +} + +TEST(json, test_stringified_signed_and_narrow_bounds) { + struct Bounds { + rfl::Stringified min_i64; + rfl::Stringified max_i64; + rfl::Stringified min_i8; + rfl::Stringified max_u8; + }; + + const auto bounds = Bounds{ + .min_i64 = std::numeric_limits::min(), + .max_i64 = std::numeric_limits::max(), + .min_i8 = std::numeric_limits::min(), + .max_u8 = std::numeric_limits::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 v; + }; + struct SingleUnsigned { + rfl::Stringified v; + }; + struct SingleSmall { + rfl::Stringified v; + }; + + // Bare JSON number is rejected (wire type is string). + EXPECT_FALSE(rfl::json::read(R"({"v":42})")); + // Empty string, whitespace, plus sign, float, trailing garbage. + EXPECT_FALSE(rfl::json::read(R"({"v":""})")); + EXPECT_FALSE(rfl::json::read(R"({"v":" 42"})")); + EXPECT_FALSE(rfl::json::read(R"({"v":"42 "})")); + EXPECT_FALSE(rfl::json::read(R"({"v":"+42"})")); + EXPECT_FALSE(rfl::json::read(R"({"v":"42.0"})")); + EXPECT_FALSE(rfl::json::read(R"({"v":"42abc"})")); + // Overflow / underflow. + EXPECT_FALSE( + rfl::json::read(R"({"v":"9223372036854775808"})")); + EXPECT_FALSE( + rfl::json::read(R"({"v":"-9223372036854775809"})")); + EXPECT_FALSE( + rfl::json::read(R"({"v":"18446744073709551616"})")); + EXPECT_FALSE(rfl::json::read(R"({"v":"-1"})")); + EXPECT_FALSE(rfl::json::read(R"({"v":"128"})")); + EXPECT_FALSE(rfl::json::read(R"({"v":"-129"})")); +} + +TEST(json, test_stringified_accessors_and_composition) { + struct Envelope { + std::optional> maybe_id; + std::vector> ids; + }; + + const auto env = Envelope{ + .maybe_id = -42LL, + .ids = {1ULL, 9007199254740993ULL}, + }; + write_and_read(env, R"({"maybe_id":"-42","ids":["1","9007199254740993"]})"); + + rfl::Stringified 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::from_string("9007199254740993"); + ASSERT_TRUE(parsed.has_value()); + EXPECT_EQ(parsed->value(), 9007199254740993LL); + EXPECT_FALSE(rfl::Stringified::from_string("-5").has_value()); + + const auto schema = rfl::json::to_schema(); + EXPECT_NE(schema.find(R"("type":"string")"), std::string::npos); +} + +} // namespace test_stringified