aboutsummaryrefslogtreecommitdiff
path: root/src/libutil/util.hh
diff options
context:
space:
mode:
authorThéophane Hufschmitt <7226587+thufschmitt@users.noreply.github.com>2022-01-12 10:52:40 +0100
committerGitHub <noreply@github.com>2022-01-12 10:52:40 +0100
commite61c4bc25a876ce303022435342748cafeced010 (patch)
tree77a629a905c99ec1d8fcbb915c6d90cdda81ebae /src/libutil/util.hh
parentd023903b6f39b2026716d83f32850e44df26c805 (diff)
parent73fcc40fa4382e2325be601bd85ebe258420e1ce (diff)
Merge pull request #5887 from pennae/avoid-streams
avoid std::?stream overhead when it's not helpful
Diffstat (limited to 'src/libutil/util.hh')
-rw-r--r--src/libutil/util.hh30
1 files changed, 16 insertions, 14 deletions
diff --git a/src/libutil/util.hh b/src/libutil/util.hh
index dfad33ed2..c900033f8 100644
--- a/src/libutil/util.hh
+++ b/src/libutil/util.hh
@@ -11,6 +11,8 @@
#include <unistd.h>
#include <signal.h>
+#include <boost/lexical_cast.hpp>
+
#include <atomic>
#include <functional>
#include <map>
@@ -419,21 +421,21 @@ bool statusOk(int status);
/* Parse a string into an integer. */
template<class N>
-std::optional<N> string2Int(const std::string & s)
+std::optional<N> string2Int(const std::string_view s)
{
if (s.substr(0, 1) == "-" && !std::numeric_limits<N>::is_signed)
return std::nullopt;
- std::istringstream str(s);
- N n;
- str >> n;
- if (str && str.get() == EOF) return n;
- return std::nullopt;
+ try {
+ return boost::lexical_cast<N>(s.data(), s.size());
+ } catch (const boost::bad_lexical_cast &) {
+ return std::nullopt;
+ }
}
/* Like string2Int(), but support an optional suffix 'K', 'M', 'G' or
'T' denoting a binary unit prefix. */
template<class N>
-N string2IntWithUnitPrefix(std::string s)
+N string2IntWithUnitPrefix(std::string_view s)
{
N multiplier = 1;
if (!s.empty()) {
@@ -444,7 +446,7 @@ N string2IntWithUnitPrefix(std::string s)
else if (u == 'G') multiplier = 1ULL << 30;
else if (u == 'T') multiplier = 1ULL << 40;
else throw UsageError("invalid unit specifier '%1%'", u);
- s.resize(s.size() - 1);
+ s.remove_suffix(1);
}
}
if (auto n = string2Int<N>(s))
@@ -454,13 +456,13 @@ N string2IntWithUnitPrefix(std::string s)
/* Parse a string into a float. */
template<class N>
-std::optional<N> string2Float(const string & s)
+std::optional<N> string2Float(const std::string_view s)
{
- std::istringstream str(s);
- N n;
- str >> n;
- if (str && str.get() == EOF) return n;
- return std::nullopt;
+ try {
+ return boost::lexical_cast<N>(s.data(), s.size());
+ } catch (const boost::bad_lexical_cast &) {
+ return std::nullopt;
+ }
}