Source code for torx.performance.byte_tools_m
"""Contains basic functions to parse bytestring and to bit/byte conversions."""
import re
from torx.autodoc_decorators_m import autodoc_function
[docs]
@autodoc_function
def convert_to_bytes(bytestring):
"""
Convert a bytestring to a numerical value with the amount of bytes.
The bytestring must be given by a number plus unit with any number of spaces
around each. Allowed units are given below. There is no distinction between
upper and lower case, thus this can not return any number of bits.
"""
try:
[_, num, unit] = re.split(r"(\d+)", bytestring)
num = float(num)
except:
raise RuntimeError("Failed to convert bytestring to a number of " \
"bytes! (could not split the string into number " \
"+ byte-unit)")
# Allowed units are given in u1 and u2, the former representing a list
# of IEC prefixes (2**xx numbers) and the latter representing the
# standard SI decimal prefixes.
u1 = {"kib":2**10, "mib":2**20, "gib":2**30}
u2 = {"b":1, "kb":1e3, "mb":1e6, "gb":1e9}
unit = unit.lower().strip()
err_count = 0
try:
num = num * u1[unit]
except:
err_count = err_count + 1
try:
num = num * u2[unit]
except:
err_count = err_count + 1
if err_count > 1:
allowed = list(u1.keys()) + list(u2.keys())
raise RuntimeError("Failed to convert bytestring to a number of " \
"bytes! (byte-unit was not within the list of " \
f"allowed values {allowed})")
return int(num)