Implement BigInt in Python

This commit is contained in:
RunasSudo 2017-09-24 15:18:27 +10:00
parent c7d7c611b6
commit cfbe7dee20
Signed by: RunasSudo
GPG Key ID: 7234E476BF21C61A
2 changed files with 27 additions and 3 deletions

View File

@ -33,7 +33,7 @@ lib = __pragma__('js', '''
}})()''', __include__('eos/core/bigint/jsbn.js'), __include__('eos/core/bigint/jsbn2.js')) }})()''', __include__('eos/core/bigint/jsbn.js'), __include__('eos/core/bigint/jsbn2.js'))
class BigInt(EosObject): class BigInt(EosObject):
def __init__(self, a, b=None): def __init__(self, a, b=10):
if isinstance(a, str): if isinstance(a, str):
self.impl = lib.nbi() self.impl = lib.nbi()
self.impl.fromString(a, b) self.impl.fromString(a, b)

View File

@ -16,5 +16,29 @@
from eos.core.objects import EosObject from eos.core.objects import EosObject
class BigInt(int, EosObject): class BigInt(EosObject):
pass 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))