diff options
author | Aldo Cortesi <aldo@corte.si> | 2016-05-31 21:03:42 +1200 |
---|---|---|
committer | Aldo Cortesi <aldo@corte.si> | 2016-05-31 21:03:42 +1200 |
commit | a7abf8b731658b4e7ed8705f7a94a6a62f08d51d (patch) | |
tree | cb86e2e483530f5e1e8b0c5d60839de21fcf7390 /netlib/human.py | |
parent | 2f526393d29b6a03e43d1f6240175b4dfb13dc7d (diff) | |
parent | 4da125b6a098cc0fd8b1fd2878584beb5df75c6c (diff) | |
download | mitmproxy-a7abf8b731658b4e7ed8705f7a94a6a62f08d51d.tar.gz mitmproxy-a7abf8b731658b4e7ed8705f7a94a6a62f08d51d.tar.bz2 mitmproxy-a7abf8b731658b4e7ed8705f7a94a6a62f08d51d.zip |
Merge pull request #1179 from cortesi/reorg
Start reorganising */utils.py
Diffstat (limited to 'netlib/human.py')
-rw-r--r-- | netlib/human.py | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/netlib/human.py b/netlib/human.py new file mode 100644 index 00000000..a007adc7 --- /dev/null +++ b/netlib/human.py @@ -0,0 +1,50 @@ + +SIZE_TABLE = [ + ("b", 1024 ** 0), + ("k", 1024 ** 1), + ("m", 1024 ** 2), + ("g", 1024 ** 3), + ("t", 1024 ** 4), +] + +SIZE_UNITS = dict(SIZE_TABLE) + + +def pretty_size(size): + for bottom, top in zip(SIZE_TABLE, SIZE_TABLE[1:]): + if bottom[1] <= size < top[1]: + suf = bottom[0] + lim = bottom[1] + x = round(size / lim, 2) + if x == int(x): + x = int(x) + return str(x) + suf + return "%s%s" % (size, SIZE_TABLE[0][0]) + + +def parse_size(s): + try: + return int(s) + except ValueError: + pass + for i in SIZE_UNITS.keys(): + if s.endswith(i): + try: + return int(s[:-1]) * SIZE_UNITS[i] + except ValueError: + break + raise ValueError("Invalid size specification.") + + +def pretty_duration(secs): + formatters = [ + (100, "{:.0f}s"), + (10, "{:2.1f}s"), + (1, "{:1.2f}s"), + ] + + for limit, formatter in formatters: + if secs >= limit: + return formatter.format(secs) + # less than 1 sec + return "{:.0f}ms".format(secs * 1000) |