diff options
author | ng0 <ng0@n0.is> | 2019-09-25 14:48:43 +0000 |
---|---|---|
committer | ng0 <ng0@n0.is> | 2019-09-25 14:48:43 +0000 |
commit | 2827dea755bc5ed97eff6f7dd598c40bd6baf211 (patch) | |
tree | f54d3bb8c5479442f589d704dc192e5994ea3ea8 /taler | |
parent | 653f87562460d9af34638f3c51ebc43c139ee953 (diff) | |
download | taler-util-2827dea755bc5ed97eff6f7dd598c40bd6baf211.tar.gz taler-util-2827dea755bc5ed97eff6f7dd598c40bd6baf211.tar.bz2 taler-util-2827dea755bc5ed97eff6f7dd598c40bd6baf211.zip |
amount.py: merge def check_overflow from bank.git
Diffstat (limited to 'taler')
-rw-r--r-- | taler/util/amount.py | 27 |
1 files changed, 27 insertions, 0 deletions
diff --git a/taler/util/amount.py b/taler/util/amount.py index e017e67..9200a38 100644 --- a/taler/util/amount.py +++ b/taler/util/amount.py @@ -129,10 +129,37 @@ class Amount: parsed = re.search(exp, amount_str) if not parsed: raise BadFormatAmount(amount_str) + + ## + # Checks if the input overflows. + # + # @param arg the input number to check. + # @return True if the overflow occurs, False otherwise. + def check_overflow(arg): + # Comes from 2^53 - 1 + JAVASCRIPT_MAX_INT = "9007199254740991" + if len(JAVASCRIPT_MAX_INT) < len(arg): + return True + if len(JAVASCRIPT_MAX_INT) == len(arg): + # Assume current system can afford to store + # a number as big as JAVASCRIPT_MAX_INT. + tmp = int(arg) + tmp_js = int(JAVASCRIPT_MAX_INT) + + if tmp > tmp_js - 1: # - 1 leaves room for the fractional part + return True + return False + + if check_overflow(parsed.group(2)): + raise AmountOverflow("integer part") + value = int(parsed.group(2)) fraction = 0 for i, digit in enumerate(parsed.group(3) or "0"): fraction += int(int(digit) * (Amount._fraction() / 10**(i + 1))) + if check_overflow(str(fraction)): + raise AmountOverflow("fraction") + return cls(parsed.group(1), value, fraction) ## |