strtonumber.hh 5.49 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
// -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
// vi: set et ts=4 sw=2 sts=2:
#ifndef DUNE_COMMON_STRTONUMBER_HH
#define DUNE_COMMON_STRTONUMBER_HH

#include <cerrno>
#include <cstdlib>
#include <limits>

#include <dune/common/exceptions.hh>
#include <dune/common/std/charconv.hh>
#include <dune/common/std/type_traits.hh>

namespace Dune
{
  /// An exception thrown whenever interpretation of the argument is not possible.
  class InvalidArgument : public Exception {};

  namespace Impl
  {
    // forward declaration of default parser
    template <class T>
    struct FromCharsParser;

    template <class T>
    using HasFromChars
      = decltype(Std::from_chars(std::declval<const char*>(), std::declval<const char*>(), std::declval<T&>()));


    // default behavior: call the string constructor
    template<typename T, class = void>
    struct StrToNumber
    {
      static T eval (const char* first, const char* /*last*/)
      {
        return T(first);;
      }
    };

    // if possible, use std::from_chars to convert string to number
    template<typename T>
    struct StrToNumber<T, std::enable_if_t<Std::is_detected<HasFromChars, T>::value>>
    {
      static T eval (const char* first, const char* last)
      {
        return FromCharsParser<T>::eval(first, last);
      }
    };


    /// \brief Implementation of a parser using std::from_chars functions
    /**
     * \tparam T  Target numeric type
     **/
    template<typename T>
    struct FromCharsParser
    {
      static T eval (const char* first, const char* last)
      {
        T value;
        auto result = Std::from_chars(first, last, value);

        if (result.ec == std::errc::result_out_of_range) {
          DUNE_THROW(RangeError, std::error_condition(result.ec).message());
        }
        else if (result.ec == std::errc::invalid_argument) {
          DUNE_THROW(InvalidArgument,
            "Conversion of '" << first << "' to number failed. Possible reason: invalid string or locale format.");
        }
        else if (result.ec == std::errc::not_supported) {
          DUNE_THROW(NotImplemented,
            "Parameter passed to from_chars not supported.");
        }

        return value;
      }
    };

    /// \brief Implementation of a fallback parser using std::strtoXXX like functions
    /**
     * Allows leading and trailing whitespace characters.
     * NOTE: This parser is not locale independent, but throws an error if whole
     *       string can not be parsed completely.
     *
     * \tparam T  Target numeric type
     **/
    template<typename T>
    struct StrToNumberParser
    {
      // The parser has the signature `T(const char*, char**)` and may set the errno
      // in case of a range error.
      template<typename Parser>
      T eval (const char* first, const char* /*last*/, Parser parser)
      {
        char* end;
        auto old_errno = errno;
        errno = 0;
        auto x = parser(first, &end); // maybe sets errno
        std::swap(errno, old_errno);

        if (old_errno == ERANGE) {
          DUNE_THROW(RangeError, std::strerror(old_errno));
        }

        // test whether all non-space characters are consumed during conversion
        bool all_consumed = (end != first);
        while (all_consumed && (*end != '\0'))
          all_consumed = std::isspace(*end++);

        if (!all_consumed) {
          DUNE_THROW(InvalidArgument,
            "Conversion of '" << first << "' to number failed. Possible reason: invalid string or locale format");
        }

        return convertToRange<T>(x);
      }

    private:
      // Check whether a numeric conversion is safe
      template<typename U>
      static T convertToRange (U const& u)
      {
        if (sizeof(U) > sizeof(T) && (u > U(std::numeric_limits<T>::max()) ||
                                      u < U(std::numeric_limits<T>::min()))) {
          DUNE_THROW(RangeError, "Numerical result out of range");
        }
        return T(u);
      }
    };

  } // end namespace Impl


  /// \brief Convert a character sequence to a number type `T`
  /**
   * The cast from character sequence to any numeric type is implemented in terms of the std library function
   * `from_chars()` but parametrized with the concrete target type for ease of usage
   * in generic code.
   *
   * Only types that provide a specialization of `Impl::StrToNumber` can call the special functions
   * for conversion. All other types by default call the constructor with strings.
   *
   * The conversion is locale-independent if an overload of from_chars() is found and
   * throws in the case of the fallback implementation an \ref InvalidArgument exception if not all
   * characters are consumed during conversion, except leading and trailing whitespaces.
   *
   * In case the represented number is out of range of the number type T, a \ref RangeError exception
   * is thrown.
   *
   * \tparam T   The target number type to convert the string to.
   * \param str  A pointer to the null-terminated byte string to be interpreted.
   *
   * \throws InvalidArgument
   * \throws RangeError
   *
   * Example of usage:
   * \code{.cpp}
   * double x = strTo<double>("1.2345");
   * \endcode
   **/
  template<typename T>
  T strTo (const char* str)
  {
    return Impl::StrToNumber<T>::eval(str, str + std::strlen(str));
  }

  /// Overload of \ref strTo for `std::string` arguments.
  template<typename T>
  T strTo (const std::string& str)
  {
    return Impl::StrToNumber<T>::eval(str.c_str(), str.c_str() + str.size());
  }

} // end namespace Dune

#endif // DUNE_COMMON_STRTONUMBER_HH