Patchwork [1,of,2] util: generalize bytecount to unitcount

login
register
mail settings
Submitter Bryan O'Sullivan
Date Feb. 21, 2013, 9:33 p.m.
Message ID <19d3300883ce1407d0b5.1361482381@australite.local>
Download mbox | patch
Permalink /patch/1041/
State Superseded
Headers show

Comments

Bryan O'Sullivan - Feb. 21, 2013, 9:33 p.m.
# HG changeset patch
# User Bryan O'Sullivan <bryano@fb.com>
# Date 1361482359 28800
# Node ID 19d3300883ce1407d0b527549a82f25d3f182873
# Parent  5779b305bf3a9192823252b8caf2240124238706
util: generalize bytecount to unitcount

This gives us a function we can reuse to count units of other kinds.
tonfa - Feb. 23, 2013, 10:01 p.m.
On Thu, Feb 21, 2013 at 10:33 PM, Bryan O'Sullivan <bos@serpentine.com>wrote:

> # HG changeset patch
> # User Bryan O'Sullivan <bryano@fb.com>
> # Date 1361482359 28800
> # Node ID 19d3300883ce1407d0b527549a82f25d3f182873
> # Parent  5779b305bf3a9192823252b8caf2240124238706
> util: generalize bytecount to unitcount
>
> This gives us a function we can reuse to count units of other kinds.
>
> diff --git a/mercurial/util.py b/mercurial/util.py
> --- a/mercurial/util.py
> +++ b/mercurial/util.py
> @@ -1268,7 +1268,18 @@ def ellipsis(text, maxlength=400):
>      except (UnicodeDecodeError, UnicodeEncodeError):
>          return _ellipsis(text, maxlength)[0]
>
> -_byteunits = (
> +def unitcount(*unittable):
> +    '''return a count of some quantity formatted as a readable string'''
>

Maybe call it unitcountfn? (or something similar), since it's not directly
usable (returns a function).
(I also think the docstring could be improved).

Otherwise looks good to me.

Cheers,

Benoit

Patch

diff --git a/mercurial/util.py b/mercurial/util.py
--- a/mercurial/util.py
+++ b/mercurial/util.py
@@ -1268,7 +1268,18 @@  def ellipsis(text, maxlength=400):
     except (UnicodeDecodeError, UnicodeEncodeError):
         return _ellipsis(text, maxlength)[0]
 
-_byteunits = (
+def unitcount(*unittable):
+    '''return a count of some quantity formatted as a readable string'''
+
+    def go(count):
+        for multiplier, divisor, format in unittable:
+            if count >= divisor * multiplier:
+                return format % (count / float(divisor))
+        return unittable[-1][2] % count
+
+    return go
+
+bytecount = unitcount(
     (100, 1 << 30, _('%.0f GB')),
     (10, 1 << 30, _('%.1f GB')),
     (1, 1 << 30, _('%.2f GB')),
@@ -1281,14 +1292,6 @@  def ellipsis(text, maxlength=400):
     (1, 1, _('%.0f bytes')),
     )
 
-def bytecount(nbytes):
-    '''return byte count formatted as readable string, with units'''
-
-    for multiplier, divisor, format in _byteunits:
-        if nbytes >= divisor * multiplier:
-            return format % (nbytes / float(divisor))
-    return _byteunits[-1][2] % nbytes
-
 def uirepr(s):
     # Avoid double backslash in Windows path repr()
     return repr(s).replace('\\\\', '\\')