util/abbreviate: add abbreviated-size parser

This commit is contained in:
Brian Warner 2008-12-01 17:24:12 -07:00
parent fe6abac87b
commit 39a41f1d85
2 changed files with 38 additions and 0 deletions

View File

@ -510,6 +510,22 @@ class Abbreviate(unittest.TestCase):
self.failUnlessEqual(abbreviate.abbreviate_space_both(1234567), self.failUnlessEqual(abbreviate.abbreviate_space_both(1234567),
"(1.23 MB, 1.18 MiB)") "(1.23 MB, 1.18 MiB)")
def test_parse_space(self):
p = abbreviate.parse_abbreviated_size
self.failUnlessEqual(p(""), None)
self.failUnlessEqual(p(None), None)
self.failUnlessEqual(p("123"), 123)
self.failUnlessEqual(p("123B"), 123)
self.failUnlessEqual(p("2K"), 2000)
self.failUnlessEqual(p("2kb"), 2000)
self.failUnlessEqual(p("2KiB"), 2048)
self.failUnlessEqual(p("10MB"), 10*1000*1000)
self.failUnlessEqual(p("10MiB"), 10*1024*1024)
self.failUnlessEqual(p("5G"), 5*1000*1000*1000)
self.failUnlessEqual(p("4GiB"), 4*1024*1024*1024)
e = self.failUnlessRaises(ValueError, p, "12 cubits")
self.failUnless("12 cubits" in str(e))
class Limiter(unittest.TestCase): class Limiter(unittest.TestCase):
def job(self, i, foo): def job(self, i, foo):
self.calls.append( (i, foo) ) self.calls.append( (i, foo) )

View File

@ -1,4 +1,6 @@
import re
HOUR = 3600 HOUR = 3600
DAY = 24*3600 DAY = 24*3600
WEEK = 7*DAY WEEK = 7*DAY
@ -53,3 +55,23 @@ def abbreviate_space_both(s):
return "(%s, %s)" % (abbreviate_space(s, True), return "(%s, %s)" % (abbreviate_space(s, True),
abbreviate_space(s, False)) abbreviate_space(s, False))
def parse_abbreviated_size(s):
if s is None or s == "":
return None
m = re.match(r"^(\d+)([kKmMgG]?[iB]?[bB]?)$", s)
if not m:
raise ValueError("unparseable value %s" % s)
number, suffix = m.groups()
suffix = suffix.upper()
if suffix.endswith("B"):
suffix = suffix[:-1]
multiplier = {"": 1,
"I": 1,
"K": 1000,
"M": 1000 * 1000,
"G": 1000 * 1000 * 1000,
"KI": 1024,
"MI": 1024*1024,
"GI": 1024*1024*1024,
}[suffix]
return int(number) * multiplier