summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorZhongyue Luo <zhongyue.nah@intel.com>2013-06-07 14:20:24 +0800
committerZhongyue Luo <zhongyue.nah@intel.com>2013-06-13 09:24:54 +0800
commitb0c51ec300a58f42f283108ae5f651dfa8bd744b (patch)
treee4c24e1e2f42e7c0c8ce2cb3f797e9adf12b0f41
parentfb13686a00e933c17bca163b51fb3d7119d34e5a (diff)
downloadoslo-b0c51ec300a58f42f283108ae5f651dfa8bd744b.tar.gz
oslo-b0c51ec300a58f42f283108ae5f651dfa8bd744b.tar.xz
oslo-b0c51ec300a58f42f283108ae5f651dfa8bd744b.zip
Refactors to_bytes
The original logic was not intuitive. Changed the code for better readability. Change-Id: I0d96105d4ff22eed827ed61466a26f69f33addd1
-rw-r--r--openstack/common/strutils.py44
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"):