diff options
Diffstat (limited to 'openstack/common/strutils.py')
-rw-r--r-- | openstack/common/strutils.py | 44 |
1 files changed, 23 insertions, 21 deletions
diff --git a/openstack/common/strutils.py b/openstack/common/strutils.py index 05c178c..a3fb53a 100644 --- a/openstack/common/strutils.py +++ b/openstack/common/strutils.py @@ -35,7 +35,7 @@ BYTE_MULTIPLIERS = { 'm': 1024 ** 2, 'k': 1024, } - +BYTE_REGEX = re.compile(r'(^-?\d+)(\D*)') TRUE_STRINGS = ('1', 't', 'true', 'on', 'y', 'yes') FALSE_STRINGS = ('0', 'f', 'false', 'off', 'n', 'no') @@ -162,31 +162,33 @@ def safe_encode(text, incoming=None, def to_bytes(text, default=0): - """Try to turn a string into a number of bytes. Looks at the last - characters of the text to determine what conversion is needed to - turn the input text into a byte number. + """Converts a string into an integer of bytes. + + Looks at the last characters of the text to determine + what conversion is needed to turn the input text into a byte number. + Supports "B, K(B), M(B), G(B), and T(B)". (case insensitive) - Supports: B/b, K/k, M/m, G/g, T/t (or the same with b/B on the end) + :param text: String input for bytes size conversion. + :param default: Default return value when text is blank. """ - # Take off everything not number 'like' (which should leave - # only the byte 'identifier' left) - mult_key_org = text.lstrip('-1234567890') - mult_key = mult_key_org.lower() - mult_key_len = len(mult_key) - if mult_key.endswith("b"): - mult_key = mult_key[0:-1] - try: - multiplier = BYTE_MULTIPLIERS[mult_key] - if mult_key_len: - # Empty cases shouldn't cause text[0:-0] - text = text[0:-mult_key_len] - return int(text) * multiplier - except KeyError: - msg = _('Unknown byte multiplier: %s') % mult_key_org + match = BYTE_REGEX.search(text) + if match: + magnitude = int(match.group(1)) + mult_key_org = match.group(2) + if not mult_key_org: + return magnitude + elif text: + msg = _('Invalid string format: %s') % text raise TypeError(msg) - except ValueError: + else: return default + mult_key = mult_key_org.lower().replace('b', '', 1) + multiplier = BYTE_MULTIPLIERS.get(mult_key) + if multiplier is None: + msg = _('Unknown byte multiplier: %s') % mult_key_org + raise TypeError(msg) + return magnitude * multiplier def to_slug(value, incoming=None, errors="strict"): |