From 90989d72711a8d62e03cfb746ce94f3b8d178ffb Mon Sep 17 00:00:00 2001 From: clockblocker Date: Tue, 10 Nov 2026 13:33:56 +0100 Subject: [PATCH] Add rfl::CodePoints validator for UTF-8 string length rfl::Size validates .size(), which is the byte count for std::string, but its JSON schema emits minLength/maxLength, which JSON Schema defines in Unicode code points. For non-ASCII strings the validator and the schema disagree. rfl::CodePoints counts UTF-8 code points (bytes that are not continuation bytes) and applies V to that count. Its schema output is identical to rfl::Size, so it composes with AllOf/AnyOf the same way. rfl::Size is unchanged. Co-Authored-By: Claude Opus 5.5 --- docs/content/size_validation.md | 17 ++++ include/rfl.hpp | 1 + include/rfl/CodePoints.hpp | 62 ++++++++++++++ tests/json/test_code_points.cpp | 140 ++++++++++++++++++++++++++++++++ 4 files changed, 220 insertions(+) create mode 100644 include/rfl/CodePoints.hpp create mode 100644 tests/json/test_code_points.cpp diff --git a/docs/content/size_validation.md b/docs/content/size_validation.md index 358453a3e..f2e6a4b9e 100644 --- a/docs/content/size_validation.md +++ b/docs/content/size_validation.md @@ -16,3 +16,20 @@ using NoneOrThree = rfl::Validator, rfl::Size, rfl::EqualTo<3>>>>; ``` + +Note that for `std::string`, `.size()` returns the number of bytes, not the number of characters. + +## `rfl::CodePoints` + +JSON Schema's `minLength` and `maxLength` count Unicode code points, whereas `rfl::Size` counts bytes. For UTF-8 strings containing non-ASCII characters, the two disagree: `"héllo"` is 6 bytes, but only 5 code points. + +If you want the validation to match the generated JSON schema, use `rfl::CodePoints` instead. It works just like `rfl::Size`, but counts the UTF-8 code points in a string: + +```cpp +using Username = + rfl::Validator>>; +``` + +The generated JSON schema is the same as for `rfl::Size` (`minLength`/`maxLength`). + +Keep in mind that `rfl::CodePoints` counts code points, not grapheme clusters (user-perceived characters): an emoji with a skin-tone modifier counts as two. It also does not check that the string is valid UTF-8. diff --git a/include/rfl.hpp b/include/rfl.hpp index 2663929a3..432fff2f6 100644 --- a/include/rfl.hpp +++ b/include/rfl.hpp @@ -17,6 +17,7 @@ #include "rfl/Box.hpp" #include "rfl/Bytestring.hpp" #include "rfl/CamelCaseToSnakeCase.hpp" +#include "rfl/CodePoints.hpp" #include "rfl/Commented.hpp" #include "rfl/DefaultIfMissing.hpp" #include "rfl/DefaultVal.hpp" diff --git a/include/rfl/CodePoints.hpp b/include/rfl/CodePoints.hpp new file mode 100644 index 000000000..edbadb986 --- /dev/null +++ b/include/rfl/CodePoints.hpp @@ -0,0 +1,62 @@ +#ifndef RFL_CODEPOINTS_HPP_ +#define RFL_CODEPOINTS_HPP_ + +#include +#include +#include + +#include "Result.hpp" +#include "Size.hpp" +#include "parsing/schema/ValidationType.hpp" + +namespace rfl { + +/// Validates the length of a UTF-8 encoded string, measured in Unicode code +/// points, using a validator V. +/// +/// Unlike rfl::Size, which applies V to the number of bytes returned by +/// size(), this counts code points. This matches the semantics of the +/// minLength/maxLength keywords in JSON Schema, which is what the generated +/// schema emits. +/// +/// Note that this counts code points, not grapheme clusters (user-perceived +/// characters), so e.g. an emoji with a skin-tone modifier counts as two. +/// It also does not check that the input is well-formed UTF-8: it simply +/// counts every byte that is not a UTF-8 continuation byte (10xxxxxx). +template +struct CodePoints { + /// Validates that the number of code points in the string satisfies the + /// validator V. + /// @tparam T The type of the string to validate + /// @param _t The string whose code point count will be validated + /// @return The string if validation passes, otherwise an error + template + static rfl::Result validate(T _t) { + const auto view = std::string_view(_t); + std::size_t n = 0; + for (const char c : view) { + if ((static_cast(c) & 0xC0) != 0x80) { + ++n; + } + } + auto res = V::validate(n); + if (!res) { + return error("Code point count validation failed: " + + res.error().what()); + } + return std::move(_t); + } + + /// Converts the code point validator to a JSON schema type. The output is + /// identical to that of rfl::Size, i.e. minLength/maxLength for strings. + /// @tparam T The type of the string being validated + /// @return A ValidationType representing length constraints + template + static parsing::schema::ValidationType to_schema() { + return Size::template to_schema(); + } +}; + +} // namespace rfl + +#endif diff --git a/tests/json/test_code_points.cpp b/tests/json/test_code_points.cpp new file mode 100644 index 000000000..08f5add62 --- /dev/null +++ b/tests/json/test_code_points.cpp @@ -0,0 +1,140 @@ +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_code_points { + +// UTF-8 escapes are used so the test does not depend on the source or +// execution character set. +// "héllo": 5 code points, 6 bytes. +constexpr const char* kHello = "h\xC3\xA9llo"; +// "日本語": 3 code points, 9 bytes. +constexpr const char* kNihongo = "\xE6\x97\xA5\xE6\x9C\xAC\xE8\xAA\x9E"; +// U+1F600 (grinning face): 1 code point, 4 bytes. +constexpr const char* kEmoji = "\xF0\x9F\x98\x80"; + +struct MaxFiveCodePoints { + rfl::Validator>> name; +}; + +struct MaxFiveBytes { + rfl::Validator>> name; +}; + +struct ExactlyThreeCodePoints { + rfl::Validator>> name; +}; + +struct ExactlyThreeBytes { + rfl::Validator>> name; +}; + +struct OneCodePoint { + rfl::Validator>> name; +}; + +std::string to_json(const std::string& _name) { + return R"({"name":")" + _name + R"("})"; +} + +TEST(json, test_code_points_ascii_within_limit) { + write_and_read(MaxFiveCodePoints{.name = "hello"}, R"({"name":"hello"})"); +} + +TEST(json, test_code_points_ascii_over_limit) { + const auto res = rfl::json::read(R"({"name":"hello!"})"); + ASSERT_FALSE(res); + EXPECT_EQ(res.error().what(), + "Failed to parse field 'name': Code point count validation " + "failed: Value expected to be less than or equal to 5, but got " + "6."); +} + +TEST(json, test_code_points_multibyte_latin) { + const auto json = to_json(kHello); + + const auto res = rfl::json::read(json); + ASSERT_TRUE(res) << res.error().what(); + EXPECT_EQ(res.value().name.value(), kHello); + EXPECT_EQ(rfl::json::write(res.value()), json); + + // The same limit expressed in bytes rejects the string. + const auto res_bytes = rfl::json::read(json); + ASSERT_FALSE(res_bytes); + EXPECT_EQ(res_bytes.error().what(), + "Failed to parse field 'name': Size validation failed: Value " + "expected to be less than or equal to 5, but got 6."); +} + +TEST(json, test_code_points_cjk) { + const auto json = to_json(kNihongo); + + const auto res = rfl::json::read(json); + ASSERT_TRUE(res) << res.error().what(); + EXPECT_EQ(res.value().name.value(), kNihongo); + + const auto res_bytes = rfl::json::read(json); + ASSERT_FALSE(res_bytes); + EXPECT_EQ(res_bytes.error().what(), + "Failed to parse field 'name': Size validation failed: Value " + "expected to be equal to 3, but got 9."); +} + +TEST(json, test_code_points_emoji) { + const auto res = rfl::json::read(to_json(kEmoji)); + ASSERT_TRUE(res) << res.error().what(); + EXPECT_EQ(res.value().name.value(), kEmoji); + + const auto res_two = + rfl::json::read(to_json(std::string(kEmoji) + kEmoji)); + ASSERT_FALSE(res_two); + EXPECT_EQ(res_two.error().what(), + "Failed to parse field 'name': Code point count validation " + "failed: Value expected to be equal to 1, but got 2."); +} + +TEST(json, test_code_points_minimum) { + using AtLeastThree = + rfl::Validator>>; + + // "日本" is 6 bytes but only 2 code points. + const auto res = AtLeastThree::from_value("\xE6\x97\xA5\xE6\x9C\xAC"); + ASSERT_FALSE(res); + EXPECT_EQ(res.error().what(), + "Code point count validation failed: Value expected to be greater " + "than or equal to 3, but got 2."); + + EXPECT_TRUE(AtLeastThree::from_value(kNihongo)); +} + +TEST(json, test_code_points_schema) { + constexpr auto expected = + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","allOf":[{"type":"string","minLength":4},{"type":"string","maxLength":6}],"$defs":{}})"; + + using MinMax = rfl::Validator>, + rfl::CodePoints>>; + EXPECT_EQ(rfl::json::to_schema(), expected); + + using AllOf = rfl::Validator< + std::string, + rfl::CodePoints, rfl::Maximum<6>>>>; + EXPECT_EQ(rfl::json::to_schema(), expected); + + // Schema output is identical to the byte-based rfl::Size. + using SizeMinMax = rfl::Validator>, + rfl::Size>>; + EXPECT_EQ(rfl::json::to_schema(), + rfl::json::to_schema()); +} + +TEST(json, test_code_points_schema_exact) { + constexpr auto expected = + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","type":"string","minLength":3,"maxLength":3,"$defs":{}})"; + + using Exact = rfl::Validator>>; + EXPECT_EQ(rfl::json::to_schema(), expected); +} + +} // namespace test_code_points