Skip to content
Merged
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
15 changes: 13 additions & 2 deletions include/rfl/json/Reader.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
#include "../thirdparty/yyjson.h"
#endif

#include <cstdint>
#include <exception>
#include <limits>
#include <optional>
#include <string>
#include <string_view>
Expand Down Expand Up @@ -166,13 +168,22 @@ struct Reader {
if (!yyjson_is_uint(_var.val_)) {
return error("Could not cast to uint.");
}
return static_cast<T>(yyjson_get_uint(_var.val_));
const auto value = yyjson_get_uint(_var.val_);
if (value > static_cast<uint64_t>(std::numeric_limits<std::remove_cvref_t<T>>::max())) {
return error("Integer is out of range for the target type.");
}
return static_cast<T>(value);

} else if constexpr (std::is_integral<std::remove_cvref_t<T>>()) {
if (!yyjson_is_int(_var.val_)) {
return error("Could not cast to int.");
}
return static_cast<T>(yyjson_get_sint(_var.val_));
const auto value = yyjson_get_sint(_var.val_);
if (value < std::numeric_limits<std::remove_cvref_t<T>>::min() ||
value > std::numeric_limits<std::remove_cvref_t<T>>::max()) {
return error("Integer is out of range for the target type.");
}
return static_cast<T>(value);

} else {
static_assert(rfl::always_false_v<T>, "Unsupported type.");
Expand Down
17 changes: 17 additions & 0 deletions tests/json/test_integers.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,23 @@

namespace test_integers {

TEST(json, test_narrow_integer_bounds) {
struct NarrowIntegers {
int16_t signed_value;
uint16_t unsigned_value;
};

write_and_read(NarrowIntegers{.signed_value = INT16_MIN,
.unsigned_value = UINT16_MAX},
R"({"signed_value":-32768,"unsigned_value":65535})");
EXPECT_FALSE(rfl::json::read<NarrowIntegers>(
R"({"signed_value":32768,"unsigned_value":1})"));
EXPECT_FALSE(rfl::json::read<NarrowIntegers>(
R"({"signed_value":-32769,"unsigned_value":1})"));
EXPECT_FALSE(rfl::json::read<NarrowIntegers>(
R"({"signed_value":0,"unsigned_value":100200})"));
}

TEST(json, test_integers) {

struct Integers {
Expand Down
Loading