libcruft-util/parse.cpp

106 lines
2.7 KiB
C++
Raw Normal View History

/*
2018-08-04 15:14:06 +10:00
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright 2017 Danny Robson <danny@nerdcruft.net>
*/
#include "parse.hpp"
#include "cast.hpp"
#include <cstdlib>
#include <stdexcept>
using cruft::parse;
///////////////////////////////////////////////////////////////////////////////
template <typename T> struct c_traits;
template <> struct c_traits<long> { static constexpr auto func = strtol; };
template <> struct c_traits<long long> { static constexpr auto func = strtoll; };
template <> struct c_traits<unsigned long> { static constexpr auto func = strtoul; };
template <> struct c_traits<unsigned long long> { static constexpr auto func = strtoull; };
template <> struct c_traits<float> { static constexpr auto func = strtof; };
template <> struct c_traits<double> { static constexpr auto func = strtod; };
template <> struct c_traits<long double> { static constexpr auto func = strtold; };
//-----------------------------------------------------------------------------
template <typename T>
T
c_iparse (const char *first, const char *last)
{
auto tail = const_cast<char *> (last);
auto val = c_traits<T>::func (first, &tail, 0);
if (tail != last)
throw std::invalid_argument ("unable to parse");
return val;
}
//-----------------------------------------------------------------------------
template <typename T>
T
c_fparse (const char *first, const char *last)
{
auto tail = const_cast<char *> (last);
auto val = c_traits<T>::func (first, &tail);
if (tail != last)
throw std::invalid_argument ("unable to parse");
return val;
}
///////////////////////////////////////////////////////////////////////////////
#define C_PARSE(T, KLASS) \
template <> \
T \
cruft::parse<T> (cruft::view<const char *> str) \
{ \
return c_ ## KLASS ## parse<T> (std::cbegin (str), std::cend (str)); \
}
//-----------------------------------------------------------------------------
C_PARSE(long, i)
C_PARSE(long long, i)
C_PARSE(unsigned long, i)
C_PARSE(unsigned long long, i)
C_PARSE(float, f)
C_PARSE(double, f)
C_PARSE(long double, f)
2017-12-19 18:12:35 +11:00
template <>
int
cruft::parse<int> (cruft::view<const char*> str)
2017-12-19 18:12:35 +11:00
{
auto intermediate = cruft::parse<long> (str);
return cruft::cast::lossless<int> (intermediate);
2017-12-19 18:12:35 +11:00
}
2018-03-27 16:11:04 +11:00
template <>
unsigned
cruft::parse<unsigned> (cruft::view<const char*> str)
2018-03-27 16:11:04 +11:00
{
return cruft::cast::narrow<unsigned> (parse<unsigned long> (str));
2018-03-27 16:11:04 +11:00
}
template <>
unsigned short
cruft::parse<unsigned short> (cruft::view<const char*> str)
{
return cruft::cast::narrow<unsigned short> (parse<unsigned long> (str));
}