Skip to content

Commit

Permalink
Improve i18n for formatting memory size
Browse files Browse the repository at this point in the history
  • Loading branch information
int-y1 authored and kiritofeng committed Jan 5, 2025
1 parent 7d8b78d commit 25f4798
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 12 deletions.
26 changes: 16 additions & 10 deletions judge/jinja2/filesize.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
from django.template.defaultfilters import floatformat
from django.utils.html import avoid_wrapping
from django.utils.translation import gettext_lazy as _

from . import registry


def _format_size(bytes, callback):
def _format_size(bytes, formats, decimals):
bytes = float(bytes)

KB = 1 << 10
Expand All @@ -13,24 +15,28 @@ def _format_size(bytes, callback):
PB = 1 << 50

if bytes < KB:
return callback('', bytes)
return formats[0] % floatformat(bytes, decimals[0])
elif bytes < MB:
return callback('K', bytes / KB)
return formats[1] % floatformat(bytes / KB, decimals[1])
elif bytes < GB:
return callback('M', bytes / MB)
return formats[2] % floatformat(bytes / MB, decimals[2])
elif bytes < TB:
return callback('G', bytes / GB)
return formats[3] % floatformat(bytes / GB, decimals[3])
elif bytes < PB:
return callback('T', bytes / TB)
return formats[4] % floatformat(bytes / TB, decimals[4])
else:
return callback('P', bytes / PB)
return formats[5] % floatformat(bytes / PB, decimals[5])


@registry.filter
def kbdetailformat(bytes):
return avoid_wrapping(_format_size(bytes * 1024, lambda x, y: ['%d %sB', '%.2f %sB'][bool(x)] % (y, x)))
def kbdetailformat(kb):
formats = [_('%s B'), _('%s KB'), _('%s MB'), _('%s GB'), _('%s TB'), _('%s PB')]
decimals = [0, 2, 2, 2, 2, 2]
return avoid_wrapping(_format_size(kb * 1024, formats, decimals))


@registry.filter
def kbsimpleformat(kb):
return _format_size(kb * 1024, lambda x, y: '%.0f%s' % (y, x or 'B'))
formats = [_('%sB'), _('%sK'), _('%sM'), _('%sG'), _('%sT'), _('%sP')]
decimals = [0, 0, 0, 0, 0, 0]
return _format_size(kb * 1024, formats, decimals)
3 changes: 1 addition & 2 deletions templates/submission/row.html
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,6 @@
{% else %}
<div class="time">---</div>
{% endif %}
{# No one actually likes IEC prefixes, Jinja2. #}
<div class="memory">{{ (submission.memory_bytes|filesizeformat(True)).replace('i', '') }}</div>
<div class="memory">{{ submission.memory|kbdetailformat }}</div>
{% endif %}
</div>

0 comments on commit 25f4798

Please sign in to comment.