From cfbe7dee2062d79d7bacbf42f89a2f7346e46c2b Mon Sep 17 00:00:00 2001 From: RunasSudo Date: Sun, 24 Sep 2017 15:18:27 +1000 Subject: [PATCH] Implement BigInt in Python --- eos/core/bigint/js.py | 2 +- eos/core/bigint/python.py | 28 ++++++++++++++++++++++++++-- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/eos/core/bigint/js.py b/eos/core/bigint/js.py index 9d04477..1ebbe92 100644 --- a/eos/core/bigint/js.py +++ b/eos/core/bigint/js.py @@ -33,7 +33,7 @@ lib = __pragma__('js', ''' }})()''', __include__('eos/core/bigint/jsbn.js'), __include__('eos/core/bigint/jsbn2.js')) class BigInt(EosObject): - def __init__(self, a, b=None): + def __init__(self, a, b=10): if isinstance(a, str): self.impl = lib.nbi() self.impl.fromString(a, b) diff --git a/eos/core/bigint/python.py b/eos/core/bigint/python.py index 181520a..356d050 100644 --- a/eos/core/bigint/python.py +++ b/eos/core/bigint/python.py @@ -16,5 +16,29 @@ from eos.core.objects import EosObject -class BigInt(int, EosObject): - pass +class BigInt(EosObject): + def __init__(self, a, b=10): + self.impl = int(a, b) if isinstance(a, str) else int(a) + + def __pow__(self, other, modulo=None): + if not isinstance(other, BigInt): + other = BigInt(other) + if modulo is None: + return BigInt(self.impl.__pow__(other.impl)) + if not isinstance(modulo, BigInt): + modulo = BigInt(modulo) + return BigInt(self.impl.__pow__(other.impl, modulo.impl)) + +for func in [ + '__add__', '__sub__', '__mul__', '__mod__', '__or__', '__lshift__', '__xor__', + '__eq__', '__ne__', '__lt__', '__gt__', '__le__', '__ge__', + '__str__' +]: + def make_operator_func(func_): + # Create a closure + def operator_func(self, other): + if not isinstance(other, BigInt): + other = BigInt(other) + return BigInt(getattr(self.impl, func_)(other.impl)) + return operator_func + setattr(BigInt, func, make_operator_func(func))