diff options
author | Joao Eduardo Luis <joao.luis@inktank.com> | 2013-03-29 16:27:35 +0100 |
---|---|---|
committer | Sage Weil <sage@inktank.com> | 2013-03-30 00:47:28 +0100 |
commit | e2a936d2ae16db2cf081fc17f32f7f4fe62659d7 (patch) | |
tree | 2a936fa4081a9f19c52269fb088ad0ae89168016 /src/common/util.cc | |
parent | osd: osd_types: add pool quota related fields (diff) | |
download | ceph-e2a936d2ae16db2cf081fc17f32f7f4fe62659d7.tar.xz ceph-e2a936d2ae16db2cf081fc17f32f7f4fe62659d7.zip |
common: util: add 'unit_to_bytesize()' function
Converts from a numerical value that may or may not contain an unit
modifier ('1024', '1K', '2M', ..., '1E') and returns the parsed size
in bytes.
Signed-off-by: Joao Eduardo Luis <joao.luis@inktank.com>
Diffstat (limited to 'src/common/util.cc')
-rw-r--r-- | src/common/util.cc | 69 |
1 files changed, 69 insertions, 0 deletions
diff --git a/src/common/util.cc b/src/common/util.cc index 73b0c365bad..6da37e88833 100644 --- a/src/common/util.cc +++ b/src/common/util.cc @@ -12,7 +12,11 @@ * */ +#include <errno.h> + #include "include/util.h" +#include "common/errno.h" +#include "common/strtol.h" // test if an entire buf is zero in 8-byte chunks bool buf_is_zero(const char *buf, size_t len) @@ -34,3 +38,68 @@ bool buf_is_zero(const char *buf, size_t len) } +int64_t unit_to_bytesize(string val, ostream *pss) +{ + if (val.empty()) { + if (pss) + *pss << "value is empty!"; + return -EINVAL; + } + + char c = val[val.length()-1]; + int modifier = 0; + if (!::isdigit(c)) { + if (val.length() < 2) { + if (pss) + *pss << "invalid value: " << val; + return -EINVAL; + } + val = val.substr(0,val.length()-1); + switch (c) { + case 'B': + break; + case 'K': + modifier = 10; + break; + case 'M': + modifier = 20; + break; + case 'G': + modifier = 30; + break; + case 'T': + modifier = 40; + break; + case 'P': + modifier = 50; + break; + case 'E': + modifier = 60; + break; + default: + if (pss) + *pss << "unrecognized modifier '" << c << "'" << std::endl; + return -EINVAL; + } + } + + if (val[0] == '+' || val[0] == '-') { + if (pss) + *pss << "expected numerical value, got: " << val; + return -EINVAL; + } + + string err; + int64_t r = strict_strtoll(val.c_str(), 10, &err); + if ((r == 0) && !err.empty()) { + if (pss) + *pss << err; + return -1; + } + if (r < 0) { + if (pss) + *pss << "unable to parse positive integer '" << val << "'"; + return -1; + } + return (r * (1LL << modifier)); +} |