int2bytespec(): add strip, add_space args

This commit is contained in:
The MMGen Project 2022-10-27 16:45:57 +00:00
commit 4b9d79fabd
Signed by: mmgen
GPG key ID: 3F8B1861E32B7DA2
4 changed files with 21 additions and 5 deletions

View file

@ -1 +1 @@
13.3.dev11
13.3.dev12

View file

@ -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 ):

View file

@ -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)

View file

@ -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' ),