]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/util/abbreviate.py
Make abbreviate_space able to output in exabytes. refs #1812
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / util / abbreviate.py
1
2 import re
3
4 HOUR = 3600
5 DAY = 24*3600
6 WEEK = 7*DAY
7 MONTH = 30*DAY
8 YEAR = 365*DAY
9
10 def abbreviate_time(s):
11     def _plural(count, unit):
12         count = int(count)
13         if count == 1:
14             return "%d %s" % (count, unit)
15         return "%d %ss" % (count, unit)
16     if s is None:
17         return "unknown"
18     if s < 120:
19         return _plural(s, "second")
20     if s < 3*HOUR:
21         return _plural(s/60, "minute")
22     if s < 2*DAY:
23         return _plural(s/HOUR, "hour")
24     if s < 2*MONTH:
25         return _plural(s/DAY, "day")
26     if s < 4*YEAR:
27         return _plural(s/MONTH, "month")
28     return _plural(s/YEAR, "year")
29
30 def abbreviate_space(s, SI=True):
31     if s is None:
32         return "unknown"
33     if SI:
34         U = 1000.0
35         isuffix = "B"
36     else:
37         U = 1024.0
38         isuffix = "iB"
39     def r(count, suffix):
40         return "%.2f %s%s" % (count, suffix, isuffix)
41
42     if s < 1024: # 1000-1023 get emitted as bytes, even in SI mode
43         return "%d B" % s
44     if s < U*U:
45         return r(s/U, "k")
46     if s < U*U*U:
47         return r(s/(U*U), "M")
48     if s < U*U*U*U:
49         return r(s/(U*U*U), "G")
50     if s < U*U*U*U*U:
51         return r(s/(U*U*U*U), "T")
52     if s < U*U*U*U*U*U:
53         return r(s/(U*U*U*U*U), "P")
54     return r(s/(U*U*U*U*U*U), "E")
55
56 def abbreviate_space_both(s):
57     return "(%s, %s)" % (abbreviate_space(s, True),
58                          abbreviate_space(s, False))
59
60 def parse_abbreviated_size(s):
61     if s is None or s == "":
62         return None
63     m = re.match(r"^(\d+)([KMGTPE]?[I]?[B]?)$", s.upper())
64     if not m:
65         raise ValueError("unparseable value %s" % s)
66     number, suffix = m.groups()
67     if suffix.endswith("B"):
68         suffix = suffix[:-1]
69     multiplier = {"":   1,
70                   "I":  1,
71                   "K":  1000,
72                   "M":  1000 * 1000,
73                   "G":  1000 * 1000 * 1000,
74                   "T":  1000 * 1000 * 1000 * 1000,
75                   "P":  1000 * 1000 * 1000 * 1000 * 1000,
76                   "E":  1000 * 1000 * 1000 * 1000 * 1000 * 1000,
77                   "KI": 1024,
78                   "MI": 1024 * 1024,
79                   "GI": 1024 * 1024 * 1024,
80                   "TI": 1024 * 1024 * 1024 * 1024,
81                   "PI": 1024 * 1024 * 1024 * 1024 * 1024,
82                   "EI": 1024 * 1024 * 1024 * 1024 * 1024 * 1024,
83                   }[suffix]
84     return int(number) * multiplier