From 4b9d79fabd0b63a503ab90344ab05fabac4ace60 Mon Sep 17 00:00:00 2001 From: The MMGen Project Date: Thu, 27 Oct 2022 16:45:57 +0000 Subject: [PATCH] int2bytespec(): add `strip`, `add_space` args --- mmgen/data/version | 2 +- mmgen/tool/util.py | 12 ++++++++++-- mmgen/util2.py | 10 ++++++++-- test/tooltest2.py | 2 ++ 4 files changed, 21 insertions(+), 5 deletions(-) diff --git a/mmgen/data/version b/mmgen/data/version index ceb0c569..bd30abf1 100644 --- a/mmgen/data/version +++ b/mmgen/data/version @@ -1 +1 @@ -13.3.dev11 +13.3.dev12 diff --git a/mmgen/tool/util.py b/mmgen/tool/util.py index b82887ca..9fcb14f4 100755 --- a/mmgen/tool/util.py +++ b/mmgen/tool/util.py @@ -56,7 +56,9 @@ class tool_cmd(tool_cmd_base): n: int, dd_style_byte_specifier: str, fmt: 'width and precision of output' = '0.2', - print_sym: 'print the specifier after the numerical value' = True ): + print_sym: 'print the specifier after the numerical value' = True, + strip: 'strip trailing zeroes' = False, + add_space: 'with print_sym, add space between value and specifier' = False ): """ convert an integer to a byte specifier such as ‘4GB’ @@ -79,7 +81,13 @@ class tool_cmd(tool_cmd_base): E = 1152921504606846976 """ from ..util2 import int2bytespec - return int2bytespec( n, dd_style_byte_specifier, fmt, print_sym ) + return int2bytespec( + n, + dd_style_byte_specifier, + fmt, + print_sym = print_sym, + strip = strip, + add_space = add_space ) def randhex(self, nbytes: 'number of bytes to output' = 32 ): diff --git a/mmgen/util2.py b/mmgen/util2.py index 7b1ec903..06ac2520 100755 --- a/mmgen/util2.py +++ b/mmgen/util2.py @@ -74,14 +74,20 @@ bytespec_map = ( ('E', 1152921504606846976), ) -def int2bytespec(n,spec,fmt,print_sym=True): +def int2bytespec(n,spec,fmt,print_sym=True,strip=False,add_space=False): + def spec2int(spec): for k,v in bytespec_map: if k == spec: return v else: die('{spec}: unrecognized bytespec') - return '{:{}f}{}'.format( n / spec2int(spec), fmt, spec if print_sym else '' ) + + if strip: + ret = '{:{}f}'.format(n/spec2int(spec),fmt).rstrip('0') + return ret + ('0' if ret.endswith('.') else '') + ((' ' if add_space else '') + spec if print_sym else '') + else: + return '{:{}f}'.format(n/spec2int(spec),fmt) + ((' ' if add_space else '') + spec if print_sym else '') def parse_bytespec(nbytes): m = re.match(r'([0123456789.]+)(.*)',nbytes) diff --git a/test/tooltest2.py b/test/tooltest2.py index 1098be57..187e58a7 100755 --- a/test/tooltest2.py +++ b/test/tooltest2.py @@ -313,6 +313,8 @@ tests = { ( [str(1024*1024*1024),'G','fmt=0.0'], '1G' ), ( [str(1024*1024*1024),'G','fmt=08.5'], '01.00000G' ), ( [str(1234*1000*1000*1000),'GB'], '1234.00GB' ), + ( [str(1234*1000*1000*1000),'GB','strip=True'], '1234.0GB' ), + ( [str(1234*1000*1000*1000),'GB','add_space=True'], '1234.00 GB' ), ( [str(1234*1024*1024*1024),'G'], '1234.00G', ), ( [str(1000*1000*1000*1000*1000),'PB'], '1.00PB' ), ( [str(1024*1024*1024*1024*1024),'P'], '1.00P' ),