# -*- coding: utf8 -*-

from math import floor

def format_timespan(seconds): # {{{1
  """
  Format a timespan in seconds as a human-readable string.
  """
  result = []
  units = [('day', 60 * 60 * 24), ('hour', 60 * 60), ('minute', 60), ('second', 1)]
  for name, size in units:
    if seconds >= size:
      count = seconds / size
      seconds %= size
      result.append('%i %s%s' % (count, name, floor(count) != 1 and 's' or ''))
  if result == []:
    return 'less than a second'
  if len(result) == 1:
    return result[0]
  else:
    return ', '.join(result[:-1]) + ' and ' + result[-1]

def format_size(nbytes):
  """
  Format a byte count as a human-readable file size.
  """
  return nbytes < 1024 and '%i bytes' % nbytes \
      or nbytes < (1024 ** 2) and __round(nbytes, 1024, 'KB') \
      or nbytes < (1024 ** 3) and __round(nbytes, 1024 ** 2, 'MB') \
      or nbytes < (1024 ** 4) and __round(nbytes, 1024 ** 3, 'GB') \
      or __round(nbytes, 1024 ** 4, 'TB')

def __round(nbytes, divisor, suffix):
  _nbytes = float(nbytes) / divisor
  if floor(_nbytes) == _nbytes:
    return str(int(_nbytes)) + ' ' + suffix
  else:
    return '%.2f %s' % (_nbytes, suffix)

# vim: sw=2 sw=2 et

@@ -612,16 +612,26 @@
 e(nbytes
+, si=False
 ):%0A  %22%22%22
@@ -684,21 +684,399 @@
 e size.%0A
-  %22%22%22
+%0A  @param si: In SI format (/1000) or Binary (/1024)%0A  %22%22%22%0A  if si:%0A    return nbytes %3C 1000 and '%25i bytes' %25 nbytes %5C%0A           or nbytes %3C (1000 ** 2) and __round(nbytes, 1000, 'kB') %5C%0A           or nbytes %3C (1000 ** 3) and __round(nbytes, 1000 ** 2, 'MB') %5C%0A           or nbytes %3C (1000 ** 4) and __round(nbytes, 1000 ** 3, 'GB') %5C%0A           or __round(nbytes, 1000 ** 4, 'TB')%0A
 %0A  retur
@@ -1175,16 +1175,17 @@
 1024, 'K
+i
 B') %5C%0A  
@@ -1237,32 +1237,33 @@
 s, 1024 ** 2, 'M
+i
 B') %5C%0A      or n
@@ -1307,32 +1307,33 @@
 s, 1024 ** 3, 'G
+i
 B') %5C%0A      or _
@@ -1356,24 +1356,25 @@
 024 ** 4, 'T
+i
 B')%0A%0Adef __r

Format numbers right