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>);
22 if (value < Value)
throw std::runtime_error(fmt::format(
"Invalid value, minimum={}, given={}", Value, value));
26template <
const auto& Value>
29 static void Validate(T value) {
30 static_assert(std::is_arithmetic_v<T>);
32 if (value > Value)
throw std::runtime_error(fmt::format(
"Invalid value, maximum={}, given={}", Value, value));
36template <
const auto& Value>
37struct ExclusiveMinimum final {
39 static void Validate(T value) {
40 static_assert(std::is_arithmetic_v<T>);
43 throw std::runtime_error(fmt::format(
"Invalid value, exclusive minimum={}, given={}", Value, value));
47template <
const auto& Value>
48struct ExclusiveMaximum final {
50 static void Validate(T value) {
51 static_assert(std::is_arithmetic_v<T>);
54 throw std::runtime_error(fmt::format(
"Invalid value, exclusive maximum={}, given={}", Value, value));
58template <std::int64_t Value>
59struct MinItems final {
61 static void Validate(
const T& value) {
62 if (value.size() < Value) {
63 throw std::runtime_error(fmt::format(
"Too short array, minimum length={}, given={}", Value, value.size()));
68template <std::int64_t Value>
69struct MaxItems final {
71 static void Validate(
const T& value) {
72 if (value.size() > Value) {
73 throw std::runtime_error(fmt::format(
"Too long array, maximum length={}, given={}", Value, value.size()));
78template <std::int64_t Value>
79struct MinLength final {
80 static void Validate(std::string_view value) {
81 auto length = utils::text::utf8::GetCodePointsCount(value);
83 throw std::runtime_error(fmt::format(
"Too short string, minimum length={}, given={}", Value, length));
88template <std::int64_t Value>
89struct MaxLength final {
90 static void Validate(std::string_view value) {
91 auto length = utils::text::utf8::GetCodePointsCount(value);
93 throw std::runtime_error(fmt::format(
"Too long string, maximum length={}, given={}", Value, length));
98template <
typename... Validators,
typename Obj,
typename Value>
99void Validate(
const Obj& obj,
const Value& value) {
101 (Validators::Validate(obj), ...);
102 }
catch (
const std::exception& e) {
103 chaotic::ThrowForValue(e.what(), value);