Skip to content
Closed
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
17 changes: 17 additions & 0 deletions docs/content/size_validation.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,20 @@ using NoneOrThree =
rfl::Validator<std::vector<std::string>,
rfl::Size<rfl::AnyOf<rfl::EqualTo<0>, 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<std::string, rfl::CodePoints<rfl::Maximum<16>>>;
```

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.
1 change: 1 addition & 0 deletions include/rfl.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
62 changes: 62 additions & 0 deletions include/rfl/CodePoints.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
#ifndef RFL_CODEPOINTS_HPP_
#define RFL_CODEPOINTS_HPP_

#include <cstddef>
#include <string_view>
#include <utility>

#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 <class V>
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 <class T>
static rfl::Result<T> validate(T _t) {
const auto view = std::string_view(_t);
std::size_t n = 0;
for (const char c : view) {
if ((static_cast<unsigned char>(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 <class T>
static parsing::schema::ValidationType to_schema() {
return Size<V>::template to_schema<T>();
}
};

} // namespace rfl

#endif
140 changes: 140 additions & 0 deletions tests/json/test_code_points.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>

#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<std::string, rfl::CodePoints<rfl::Maximum<5>>> name;
};

struct MaxFiveBytes {
rfl::Validator<std::string, rfl::Size<rfl::Maximum<5>>> name;
};

struct ExactlyThreeCodePoints {
rfl::Validator<std::string, rfl::CodePoints<rfl::EqualTo<3>>> name;
};

struct ExactlyThreeBytes {
rfl::Validator<std::string, rfl::Size<rfl::EqualTo<3>>> name;
};

struct OneCodePoint {
rfl::Validator<std::string, rfl::CodePoints<rfl::EqualTo<1>>> 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<MaxFiveCodePoints>(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<MaxFiveCodePoints>(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<MaxFiveBytes>(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<ExactlyThreeCodePoints>(json);
ASSERT_TRUE(res) << res.error().what();
EXPECT_EQ(res.value().name.value(), kNihongo);

const auto res_bytes = rfl::json::read<ExactlyThreeBytes>(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<OneCodePoint>(to_json(kEmoji));
ASSERT_TRUE(res) << res.error().what();
EXPECT_EQ(res.value().name.value(), kEmoji);

const auto res_two =
rfl::json::read<OneCodePoint>(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<std::string, rfl::CodePoints<rfl::Minimum<3>>>;

// "日本" 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<std::string, rfl::CodePoints<rfl::Minimum<4>>,
rfl::CodePoints<rfl::Maximum<6>>>;
EXPECT_EQ(rfl::json::to_schema<MinMax>(), expected);

using AllOf = rfl::Validator<
std::string,
rfl::CodePoints<rfl::AllOf<rfl::Minimum<4>, rfl::Maximum<6>>>>;
EXPECT_EQ(rfl::json::to_schema<AllOf>(), expected);

// Schema output is identical to the byte-based rfl::Size.
using SizeMinMax = rfl::Validator<std::string, rfl::Size<rfl::Minimum<4>>,
rfl::Size<rfl::Maximum<6>>>;
EXPECT_EQ(rfl::json::to_schema<MinMax>(),
rfl::json::to_schema<SizeMinMax>());
}

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<std::string, rfl::CodePoints<rfl::EqualTo<3>>>;
EXPECT_EQ(rfl::json::to_schema<Exact>(), expected);
}

} // namespace test_code_points