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
20 changes: 20 additions & 0 deletions docs/content/processors.md
Original file line number Diff line number Diff line change
Expand Up @@ -514,6 +514,26 @@ The resulting JSON string looks like this:
{"FirstName":"Homer","LastName":"Simpson","Age":45}
```

## `rfl::Int64AsString`

Passing `rfl::Int64AsString` serializes and deserializes 64-bit (and wider) integer fields (`int64_t`, `uint64_t`, etc.) as base-10 strings while keeping narrower integers (`int32_t`, `uint32_t`, etc.) as numbers. This lets you share one plain C++ struct across binary/columnar formats (CBOR, MsgPack, Parquet, Arrow) and JavaScript/Protobuf-JSON APIs that lose integer precision above `2^53 - 1`.

```cpp
struct Trade {
int64_t trade_id;
uint64_t sequence;
int32_t quantity;
};

const auto json_string = rfl::json::write<rfl::Int64AsString>(
Trade{.trade_id = 9007199254740993LL, .sequence = 18446744073709551615ULL, .quantity = 5});
// {"trade_id":"9007199254740993","sequence":"18446744073709551615","quantity":5}

const auto trade = rfl::json::read<Trade, rfl::Int64AsString>(json_string).value();
```

`rfl::json::to_schema<Trade, rfl::Int64AsString>()` emits `{"type":"string","format":"int64"}` / `{"type":"string","format":"uint64"}` for 64-bit integer fields and `{"type":"integer"}` for narrower integers.

## Combining several processors

You can combine several processors:
Expand Down
1 change: 1 addition & 0 deletions include/rfl.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
#include "rfl/Flatten.hpp"
#include "rfl/Generic.hpp"
#include "rfl/Hex.hpp"
#include "rfl/Int64AsString.hpp"
#include "rfl/Literal.hpp"
#include "rfl/NamedTuple.hpp"
#include "rfl/NoExtraFields.hpp"
Expand Down
22 changes: 22 additions & 0 deletions include/rfl/Int64AsString.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#ifndef RFL_INT64ASSTRING_HPP_
#define RFL_INT64ASSTRING_HPP_

namespace rfl {

/// This is a 'fake' processor - it doesn't do much by itself, but its
/// inclusion instructs parsers to serialize and deserialize 64-bit (and wider)
/// integer types as base-10 strings instead of format numbers.
/// Useful when sharing one pure C++ struct (plain int64_t / uint64_t) across
/// binary/columnar formats (Arrow, CBOR, MsgPack, Parquet) and JS/Protobuf-JSON
/// APIs that lose integer precision above 2^53 - 1.
struct Int64AsString {
public:
template <class StructType>
static auto process(auto&& _named_tuple) {
return _named_tuple;
}
};

} // namespace rfl

#endif
32 changes: 32 additions & 0 deletions include/rfl/internal/int64_as_string_v.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#ifndef RFL_INTERNAL_INT64ASSTRING_HPP_
#define RFL_INTERNAL_INT64ASSTRING_HPP_

#include <type_traits>

#include "../Int64AsString.hpp"
#include "../Processors.hpp"

namespace rfl::internal {

template <class T>
class int64_as_string;

template <class T>
class int64_as_string : public std::false_type {};

template <>
class int64_as_string<Int64AsString> : public std::true_type {};

template <class Head, class... Tail>
struct int64_as_string<Processors<Head, Tail...>> {
static constexpr bool value =
(int64_as_string<Head>::value || ... || int64_as_string<Tail>::value);
};

template <class T>
constexpr bool int64_as_string_v =
int64_as_string<std::remove_cvref_t<std::remove_pointer_t<T>>>::value;

} // namespace rfl::internal

#endif
1 change: 1 addition & 0 deletions include/rfl/json/schema/Type.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ struct Type {
struct String {
Literal<"string"> type{};
rfl::Flatten<Annotations> annotations{};
std::optional<std::string> format{};
rfl::Rename<"minLength", std::optional<size_t>> minSize{};
rfl::Rename<"maxLength", std::optional<size_t>> maxSize{};
std::optional<std::string> contentEncoding{};
Expand Down
60 changes: 56 additions & 4 deletions include/rfl/parsing/ParserBasicType.hpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
#ifndef RFL_PARSING_PARSER_BASIC_TYPE_HPP_
#define RFL_PARSING_PARSER_BASIC_TYPE_HPP_

#include <array>
#include <charconv>
#include <cstddef>
#include <map>
#include <string>
#include <system_error>
#include <type_traits>

#include "../Result.hpp"
Expand All @@ -13,6 +18,7 @@
#include "../internal/has_reflection_method_v.hpp"
#include "../internal/has_reflection_type_v.hpp"
#include "../internal/has_reflector.hpp"
#include "../internal/int64_as_string_v.hpp"
#include "../internal/is_basic_type.hpp"
#include "../internal/is_description.hpp"
#include "../internal/is_literal.hpp"
Expand Down Expand Up @@ -49,8 +55,33 @@ struct ParserBasicType {
* @return A Result containing the parsed value or an error.
*/
static RFL_ALWAYS_INLINE Result<T> read(const R& _r,
const InputVarType& _var) noexcept {
return _r.template to_basic_type<std::remove_cvref_t<T>>(_var);
const InputVarType& _var)
noexcept(!internal::int64_as_string_v<ProcessorsType>) {
using U = std::remove_cvref_t<T>;
if constexpr (internal::int64_as_string_v<ProcessorsType> &&
std::is_integral_v<U> && !std::is_same_v<U, bool> &&
sizeof(U) >= 8) {
return _r.template to_basic_type<std::string>(_var).and_then(
[](const std::string& _str) -> Result<T> {
if (_str.empty()) {
return error("Could not parse empty string as an integer.");
}
U 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 '" + _str +
"' is out of range for the target type.");
}
if (ec != std::errc{} || ptr != end) {
return error("Could not parse '" + _str + "' as an integer.");
}
return parsed;
});
} else {
return _r.template to_basic_type<U>(_var);
}
}

/**
Expand All @@ -63,7 +94,22 @@ struct ParserBasicType {
*/
template <class P>
static void write(const W& _w, const T& _var, const P& _parent) {
ParentType::add_value(_w, _var, _parent);
using U = std::remove_cvref_t<T>;
if constexpr (internal::int64_as_string_v<ProcessorsType> &&
std::is_integral_v<U> && !std::is_same_v<U, bool> &&
sizeof(U) >= 8) {
std::array<char, 64> buf{};
const auto [ptr, ec] =
std::to_chars(buf.data(), buf.data() + buf.size(), _var);
const auto str =
ec == std::errc{}
? std::string(buf.data(),
static_cast<std::size_t>(ptr - buf.data()))
: std::to_string(_var);
ParentType::add_value(_w, str, _parent);
} else {
ParentType::add_value(_w, _var, _parent);
}
}

/**
Expand All @@ -75,7 +121,13 @@ struct ParserBasicType {
static schema::Type to_schema(std::map<std::string, schema::Type>*) {
using U = std::remove_cvref_t<T>;
using Type = schema::Type;
if constexpr (std::is_same<U, bool>()) {
if constexpr (internal::int64_as_string_v<ProcessorsType> &&
std::is_integral_v<U> && !std::is_same_v<U, bool> &&
sizeof(U) >= 8) {
return Type{Type::String{
.format_ = std::is_unsigned_v<U> ? "uint64" : "int64"}};

} else if constexpr (std::is_same<U, bool>()) {
return Type{Type::Boolean{}};

} else if constexpr (std::is_same<U, std::int32_t>()) {
Expand Down
4 changes: 3 additions & 1 deletion include/rfl/parsing/schema/Type.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ struct RFL_API Type {

struct Double {};

struct String {};
struct String {
std::optional<std::string> format_{};
};

struct AnyOf {
std::vector<Type> types_;
Expand Down
6 changes: 4 additions & 2 deletions src/rfl/json/to_schema.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -215,8 +215,10 @@ schema::Type type_to_json_schema_type(const parsing::schema::Type& _type,
std::is_same<T, Type::Double>()) {
return schema::Type{.value = schema::Type::Number{}};

} else if constexpr (std::is_same<T, Type::String>() ||
std::is_same<T, Type::Vectorstring>()) {
} else if constexpr (std::is_same<T, Type::String>()) {
return schema::Type{.value = schema::Type::String{.format = _t.format_}};

} else if constexpr (std::is_same<T, Type::Vectorstring>()) {
return schema::Type{.value = schema::Type::String{}};

} else if constexpr (std::is_same<T, Type::Bytestring>()) {
Expand Down
105 changes: 105 additions & 0 deletions tests/json/test_int64_as_string.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
#include <cstdint>
#include <limits>
#include <optional>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <vector>

#include "write_and_read.hpp"

namespace test_int64_as_string {

struct Trade {
int64_t trade_id;
uint64_t sequence;
int32_t quantity;
double price;
};

TEST(json, test_int64_as_string_roundtrip) {
const auto trade = Trade{
.trade_id = 9007199254740993LL,
.sequence = std::numeric_limits<uint64_t>::max(),
.quantity = 42,
.price = 12.5,
};

// With rfl::Int64AsString: 64-bit ints become strings, 32-bit/double stay numbers.
write_and_read<rfl::Int64AsString>(
trade,
R"({"trade_id":"9007199254740993","sequence":"18446744073709551615","quantity":42,"price":12.5})");

// Default behavior (without processor) is completely unchanged.
write_and_read(
trade,
R"({"trade_id":9007199254740993,"sequence":18446744073709551615,"quantity":42,"price":12.5})");
}

TEST(json, test_int64_as_string_nested_optional_vector_validator) {
struct Envelope {
std::optional<int64_t> min_id;
std::vector<uint64_t> ids;
rfl::Validator<int64_t, rfl::Minimum<1>> positive_id;
};

const auto env = Envelope{
.min_id = std::numeric_limits<int64_t>::min(),
.ids = {0ULL, 9007199254740993ULL},
.positive_id = 9007199254740993LL,
};

write_and_read<rfl::Int64AsString>(
env,
R"({"min_id":"-9223372036854775808","ids":["0","9007199254740993"],"positive_id":"9007199254740993"})");

// Validator still rejects values failing the numeric constraint.
EXPECT_FALSE((rfl::json::read<Envelope, rfl::Int64AsString>(
R"({"ids":[],"positive_id":"0"})")));

// Works inside rfl::Processors<...> alongside other processors.
using Procs = rfl::Processors<rfl::SnakeCaseToCamelCase, rfl::Int64AsString>;
const auto trade = Trade{
.trade_id = -9223372036854775807LL,
.sequence = 1ULL,
.quantity = 3,
.price = 1.5,
};
write_and_read<Procs>(
trade,
R"({"tradeId":"-9223372036854775807","sequence":"1","quantity":3,"price":1.5})");
}

TEST(json, test_int64_as_string_errors_and_schema) {
struct SingleSigned {
int64_t v;
};
struct SingleUnsigned {
uint64_t v;
};

// Bare JSON number is rejected when Int64AsString is active.
EXPECT_FALSE((rfl::json::read<SingleSigned, rfl::Int64AsString>(R"({"v":42})")));
// Syntax and overflow errors.
EXPECT_FALSE((rfl::json::read<SingleSigned, rfl::Int64AsString>(R"({"v":""})")));
EXPECT_FALSE((rfl::json::read<SingleSigned, rfl::Int64AsString>(R"({"v":" 42"})")));
EXPECT_FALSE((rfl::json::read<SingleSigned, rfl::Int64AsString>(R"({"v":"42abc"})")));
EXPECT_FALSE((rfl::json::read<SingleSigned, rfl::Int64AsString>(
R"({"v":"9223372036854775808"})")));
EXPECT_FALSE((rfl::json::read<SingleSigned, rfl::Int64AsString>(
R"({"v":"-9223372036854775809"})")));
EXPECT_FALSE((rfl::json::read<SingleUnsigned, rfl::Int64AsString>(
R"({"v":"18446744073709551616"})")));
EXPECT_FALSE((rfl::json::read<SingleUnsigned, rfl::Int64AsString>(
R"({"v":"-1"})")));

// JSON schema emits OpenAPI/Protobuf-JSON string+format hints for 64-bit
// integers and leaves narrower integers as plain "integer".
const auto schema = rfl::json::to_schema<Trade, rfl::Int64AsString>();
EXPECT_NE(schema.find(R"("trade_id":{"type":"string","format":"int64"})"),
std::string::npos);
EXPECT_NE(schema.find(R"("sequence":{"type":"string","format":"uint64"})"),
std::string::npos);
EXPECT_NE(schema.find(R"("quantity":{"type":"integer"})"), std::string::npos);
}

} // namespace test_int64_as_string
Loading