NDOJ/judge/jinja2/filesize.py

41 lines
879 B
Python
Raw Permalink Normal View History

2020-01-21 06:35:58 +00:00
from django.utils.html import avoid_wrapping
from . import registry
def _format_size(bytes, callback):
bytes = float(bytes)
KB = 1 << 10
MB = 1 << 20
GB = 1 << 30
TB = 1 << 40
PB = 1 << 50
if bytes < KB:
2022-05-14 17:57:27 +00:00
return callback("", bytes)
2020-01-21 06:35:58 +00:00
elif bytes < MB:
2022-05-14 17:57:27 +00:00
return callback("K", bytes / KB)
2020-01-21 06:35:58 +00:00
elif bytes < GB:
2022-05-14 17:57:27 +00:00
return callback("M", bytes / MB)
2020-01-21 06:35:58 +00:00
elif bytes < TB:
2022-05-14 17:57:27 +00:00
return callback("G", bytes / GB)
2020-01-21 06:35:58 +00:00
elif bytes < PB:
2022-05-14 17:57:27 +00:00
return callback("T", bytes / TB)
2020-01-21 06:35:58 +00:00
else:
2022-05-14 17:57:27 +00:00
return callback("P", bytes / PB)
2020-01-21 06:35:58 +00:00
@registry.filter
def kbdetailformat(bytes):
2022-05-14 17:57:27 +00:00
return avoid_wrapping(
_format_size(
bytes * 1024, lambda x, y: ["%d %sB", "%.2f %sB"][bool(x)] % (y, x)
)
)
2020-01-21 06:35:58 +00:00
@registry.filter
def kbsimpleformat(kb):
2022-05-14 17:57:27 +00:00
return _format_size(kb * 1024, lambda x, y: "%.0f%s" % (y, x or "B"))