1
1
Fork 0
mirror of https://github.com/NixOS/nix.git synced 2025-11-15 15:02:42 +01:00

Move parseSize() to libutil

This commit is contained in:
Eelco Dolstra 2019-04-23 22:33:10 +02:00
parent f7f73cf5ae
commit 93b3d25bbb
2 changed files with 23 additions and 18 deletions

View file

@ -52,23 +52,7 @@ template<class N> N getIntArg(const string & opt,
{
++i;
if (i == end) throw UsageError(format("'%1%' requires an argument") % opt);
string s = *i;
N multiplier = 1;
if (allowUnit && !s.empty()) {
char u = std::toupper(*s.rbegin());
if (std::isalpha(u)) {
if (u == 'K') multiplier = 1ULL << 10;
else if (u == 'M') multiplier = 1ULL << 20;
else if (u == 'G') multiplier = 1ULL << 30;
else if (u == 'T') multiplier = 1ULL << 40;
else throw UsageError(format("invalid unit specifier '%1%'") % u);
s.resize(s.size() - 1);
}
}
N n;
if (!string2Int(s, n))
throw UsageError(format("'%1%' requires an integer argument") % opt);
return n * multiplier;
return parseSize<N>(*i, allowUnit);
}

View file

@ -359,7 +359,7 @@ bool statusOk(int status);
/* Parse a string into an integer. */
template<class N> bool string2Int(const string & s, N & n)
template<typename N> bool string2Int(const string & s, N & n)
{
if (string(s, 0, 1) == "-" && !std::numeric_limits<N>::is_signed)
return false;
@ -368,6 +368,27 @@ template<class N> bool string2Int(const string & s, N & n)
return str && str.get() == EOF;
}
template<typename N>
N parseSize(std::string s, bool allowUnit = true)
{
N multiplier = 1;
if (allowUnit && !s.empty()) {
char u = std::toupper(*s.rbegin());
if (std::isalpha(u)) {
if (u == 'K') multiplier = 1ULL << 10;
else if (u == 'M') multiplier = 1ULL << 20;
else if (u == 'G') multiplier = 1ULL << 30;
else if (u == 'T') multiplier = 1ULL << 40;
else throw Error("invalid unit specifier '%1%'", u);
s.resize(s.size() - 1);
}
}
N n;
if (!string2Int(s, n))
throw Error("'%s' is not an integer", s);
return n * multiplier;
}
/* Parse a string into a float. */
template<class N> bool string2Float(const string & s, N & n)
{