9#include <userver/chaotic/exception.hpp>
10#include <userver/utils/text_light.hpp>
12USERVER_NAMESPACE_BEGIN
16template <
const auto& Value>
19 static void Validate(T value) {
20 static_assert(std::is_arithmetic_v<T>);
23 throw std::runtime_error(
24 fmt::format(
"Invalid value, minimum={}, given={}", Value, value));
28template <
const auto& Value>
31 static void Validate(T value) {
32 static_assert(std::is_arithmetic_v<T>);
35 throw std::runtime_error(
36 fmt::format(
"Invalid value, maximum={}, given={}", Value, value));
40template <
const auto& Value>
41struct ExclusiveMinimum final {
43 static void Validate(T value) {
44 static_assert(std::is_arithmetic_v<T>);
47 throw std::runtime_error(fmt::format(
48 "Invalid value, exclusive minimum={}, given={}", Value, value));
52template <
const auto& Value>
53struct ExclusiveMaximum final {
55 static void Validate(T value) {
56 static_assert(std::is_arithmetic_v<T>);
59 throw std::runtime_error(fmt::format(
60 "Invalid value, exclusive maximum={}, given={}", Value, value));
64template <std::int64_t Value>
65struct MinItems final {
67 static void Validate(
const T& value) {
68 if (value.size() < Value) {
69 throw std::runtime_error(fmt::format(
70 "Too short array, minimum length={}, given={}", Value, value.size()));
75template <std::int64_t Value>
76struct MaxItems final {
78 static void Validate(
const T& value) {
79 if (value.size() > Value) {
80 throw std::runtime_error(fmt::format(
81 "Too long array, maximum length={}, given={}", Value, value.size()));
86template <std::int64_t Value>
87struct MinLength final {
88 static void Validate(std::string_view value) {
89 auto length = utils::text::utf8::GetCodePointsCount(value);
91 throw std::runtime_error(fmt::format(
92 "Too short string, minimum length={}, given={}", Value, length));
97template <std::int64_t Value>
98struct MaxLength final {
99 static void Validate(std::string_view value) {
100 auto length = utils::text::utf8::GetCodePointsCount(value);
101 if (length > Value) {
102 throw std::runtime_error(fmt::format(
103 "Too long string, maximum length={}, given={}", Value, length));
108template <
typename... Validators,
typename Obj,
typename Value>
109void Validate(
const Obj& obj,
const Value& value) {
111 (Validators::Validate(obj), ...);
112 }
catch (
const std::exception& e) {
113 chaotic::ThrowForValue(e.what(), value);