Mercurial > code
view cpp/to_int/to_int.hpp @ 631:5dd3347df00d
to_int: return boost::optional instead of throwing, closes #777 @10m
author | David Demelier <markand@malikania.fr> |
---|---|
date | Tue, 20 Mar 2018 13:27:22 +0100 |
parents | b327391f6a62 |
children | 18aa7181e0c3 |
line wrap: on
line source
/* * to_int.hpp -- safely convert string to integers * * Copyright (c) 2017-2018 David Demelier <markand@malikania.fr> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef TO_INT_HPP #define TO_INT_HPP /** * \file to_int.hpp * \brief Safely convert string to integers. */ #include <boost/optional.hpp> #include <cstdlib> #include <limits> #include <string> #include <type_traits> /** * Convert the given string into a signed integer. * * \param str the string to convert * \param min the minimum value allowed * \param max the maximum value allowed * \return the value or boost::none if not convertible */ template <typename T = int> boost::optional<T> to_int(const std::string& str, T min = std::numeric_limits<T>::min(), T max = std::numeric_limits<T>::max()) noexcept { static_assert(std::is_signed<T>::value, "must be signed"); char* end; auto v = std::strtoll(str.c_str(), &end, 10); if (*end != '\0' || v < min || v > max) return boost::none; return static_cast<T>(v); } /** * Convert the given string into a unsigned integer. * * \note invalid numbers are valid as well * \param str the string to convert * \param min the minimum value allowed * \param max the maximum value allowed * \return the value or boost::none if not convertible */ template <typename T = unsigned> boost::optional<T> to_uint(const std::string& str, T min = std::numeric_limits<T>::min(), T max = std::numeric_limits<T>::max()) noexcept { static_assert(std::is_unsigned<T>::value, "must be unsigned"); char* end; auto v = std::strtoull(str.c_str(), &end, 10); if (*end != '\0' || v < min || v > max) return boost::none; return static_cast<T>(v); } #endif // !TO_INT_HPP