libcruft-util/json/schema/length.cpp

84 lines
2.5 KiB
C++
Raw Normal View History

/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright 2018 Danny Robson <danny@nerdcruft.net>
*/
#include "length.hpp"
#include "../tree.hpp"
using util::json::schema::constraint::length;
///////////////////////////////////////////////////////////////////////////////
namespace {
template <typename ComparatorT>
struct field_name { };
template <>
struct field_name<std::greater_equal<std::size_t>> {
static constexpr char const *const value = "minLength";
};
template <>
struct field_name<std::less_equal<std::size_t>> {
static constexpr char const *const value = "maxLength";
};
template <typename ComparatorT>
static constexpr auto field_name_v = field_name<ComparatorT>::value;
}
///////////////////////////////////////////////////////////////////////////////
template <typename ComparatorT>
length<ComparatorT>::length(::json::tree::node const &def):
m_length(def.as<std::size_t> ())
{ ; }
///////////////////////////////////////////////////////////////////////////////
template <typename ComparatorT>
typename length<ComparatorT>::output_iterator
length<ComparatorT>::validate (output_iterator res, ::json::tree::node &target) const noexcept
{
if (!target.is_string ()) {
return *res++ = failure { .rule = *this, .target = target };
}
auto const &val = target.as_string ();
if (!ComparatorT{}(val.size (), m_length))
*res++ = failure { .rule = *this, .target = target };
return res;
}
///////////////////////////////////////////////////////////////////////////////
template <typename ComparatorT>
std::ostream&
length<ComparatorT>::describe (std::ostream &os) const
{
return os << "{ " << ::field_name_v<ComparatorT> << ": " << m_length << " }";
}
///////////////////////////////////////////////////////////////////////////////
template class util::json::schema::constraint::length<std::less_equal<std::size_t>>;
template class util::json::schema::constraint::length<std::greater_equal<std::size_t>>;