Browse Source

int2bytespec(): add `strip`, `add_space` args

The MMGen Project 2 years ago
parent
commit
4b9d79fabd
4 changed files with 21 additions and 5 deletions
  1. 1 1
      mmgen/data/version
  2. 10 2
      mmgen/tool/util.py
  3. 8 2
      mmgen/util2.py
  4. 2 0
      test/tooltest2.py

+ 1 - 1
mmgen/data/version

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

+ 10 - 2
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 ):

+ 8 - 2
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)

+ 2 - 0
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' ),