diff options
author | Aldo Cortesi <aldo@nullcube.com> | 2016-05-31 19:32:08 +1200 |
---|---|---|
committer | Aldo Cortesi <aldo@nullcube.com> | 2016-05-31 19:32:08 +1200 |
commit | b2f63458fcda7878d5cf674c2f1e9ca7db5bf3ce (patch) | |
tree | 639b7e8408a52dc8828f579f324dab065e4b4cb2 /netlib/human.py | |
parent | ec34cae6181d6af0150ac730d70b96104a07e9d5 (diff) | |
download | mitmproxy-b2f63458fcda7878d5cf674c2f1e9ca7db5bf3ce.tar.gz mitmproxy-b2f63458fcda7878d5cf674c2f1e9ca7db5bf3ce.tar.bz2 mitmproxy-b2f63458fcda7878d5cf674c2f1e9ca7db5bf3ce.zip |
Move human-friendly format functions to netlib.human, remove redundant implementations
Diffstat (limited to 'netlib/human.py')
-rw-r--r-- | netlib/human.py | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/netlib/human.py b/netlib/human.py new file mode 100644 index 00000000..f4640c00 --- /dev/null +++ b/netlib/human.py @@ -0,0 +1,51 @@ +SIZE_UNITS = dict( + b=1024 ** 0, + k=1024 ** 1, + m=1024 ** 2, + g=1024 ** 3, + t=1024 ** 4, +) + + +def pretty_size(size): + suffixes = [ + ("B", 2 ** 10), + ("kB", 2 ** 20), + ("MB", 2 ** 30), + ] + for suf, lim in suffixes: + if size >= lim: + continue + else: + x = round(size / float(lim / 2 ** 10), 2) + if x == int(x): + x = int(x) + return str(x) + suf + + +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) |