Permalink
Jul 28, 2018
Dec 18, 2019
Dec 17, 2020
Dec 17, 2020
Apr 23, 2018
Dec 17, 2020
Apr 23, 2018
Dec 17, 2020
Dec 17, 2020
Jul 28, 2018
Feb 22, 2019
Mar 10, 2018
Mar 10, 2018
Feb 10, 2018
Aug 2, 2018
Mar 10, 2018
Mar 10, 2018
Feb 22, 2019
Mar 10, 2018
Jul 28, 2018
Feb 20, 2020
Jul 28, 2018
May 19, 2017
Jul 28, 2018
Feb 20, 2020
Jul 28, 2018
Jun 30, 2020
Feb 15, 2020
Feb 11, 2018
Mar 10, 2018
Feb 22, 2019
Mar 10, 2018
Mar 23, 2018
Mar 10, 2018
Mar 10, 2018
Mar 10, 2018
Mar 10, 2018
Mar 10, 2018
Mar 10, 2018
Mar 10, 2018
Mar 10, 2018
Mar 10, 2018
Nov 28, 2018
Mar 10, 2018
Mar 10, 2018
Nov 28, 2018
Jun 14, 2018
Jan 11, 2021
Mar 10, 2018
Oct 27, 2019
Oct 27, 2019
Oct 22, 2019
Jan 7, 2021
Oct 22, 2019
Oct 22, 2019
Feb 11, 2018
Newer
100644
913 lines (823 sloc)
26.7 KB
11
function int_value(obj){
12
// Instances of int subclasses that call int.__new__(cls, value)
39
int.as_integer_ratio = function(){
40
var $ = $B.args("as_integer_ratio", 1, {self:null}, ["self"],
41
arguments, {}, null, null)
42
return $B.$list([$.self, 1])
43
}
44
46
var $ = $B.args("from_bytes", 3,
47
{bytes:null, byteorder:null, signed:null},
48
["bytes", "byteorder", "signed"],
49
arguments, {signed: false}, null, null)
50
51
var x = $.bytes,
52
byteorder = $.byteorder,
53
signed = $.signed,
54
_bytes, _len
55
if(_b_.isinstance(x, [_b_.bytes, _b_.bytearray])){
56
_bytes = x.source
57
_len = x.source.length
58
}else{
59
_bytes = _b_.list.$factory(x)
60
_len = _bytes.length
61
for(var i = 0; i < _len; i++){
62
_b_.bytes.$factory([_bytes[i]])
63
}
64
}
65
if(byteorder == "big"){
66
_bytes.reverse()
67
}else if(byteorder != "little"){
68
throw _b_.ValueError.$factory(
69
"byteorder must be either 'little' or 'big'")
70
}
71
var num = _bytes[0]
72
if(signed && num >= 128){
73
num = num - 256
74
}
75
var _mult = 256
76
for(var i = 1; i < _len; i++){
77
num = $B.add($B.mul(_mult, _bytes[i]), num)
78
_mult = $B.mul(_mult, 256)
79
}
80
if(! signed){
81
return num
82
}
83
if(_bytes[_len - 1] < 128){
84
return num
85
}
86
return $B.sub(num, _mult)
91
{self: null, len: null, byteorder: null, signed: null},
92
["self", "len", "byteorder", "*", "signed"],
93
arguments, {signed: false}, null, null),
98
if(! _b_.isinstance(len, _b_.int)){
99
throw _b_.TypeError.$factory("integer argument expected, got " +
103
throw _b_.ValueError.$factory(
104
"byteorder must be either 'little' or 'big'")
105
}
106
107
if(_b_.isinstance(self, $B.long_int)){
108
return $B.long_int.to_bytes(self, len, byteorder, signed)
123
var quotient = Math.floor(value / 256),
124
rest = value - 256 * quotient
125
res.push(rest)
126
if(res.length > len){
127
throw _b_.OverflowError.$factory("int too big to convert")
131
while(res.length < len){
132
res.push(0)
133
}
134
if(byteorder == "big"){
135
res.reverse()
145
int.__add__ = function(self, other){
146
self = int_value(self)
147
if(_b_.isinstance(other, int)){
148
if(other.__class__ == $B.long_int){
149
return $B.long_int.__add__($B.long_int.$factory(self),
150
$B.long_int.$factory(other))
151
}
152
other = int_value(other)
153
var res = self + other
154
if(res > $B.min_int && res < $B.max_int){
155
return res
156
}else{
157
return $B.long_int.__add__($B.long_int.$factory(self),
158
$B.long_int.$factory(other))
159
}
160
}
161
return _b_.NotImplemented
162
}
163
164
int.__bool__ = function(self){
165
return int_value(self).valueOf() == 0 ? false : true
166
}
184
if(_b_.isinstance(other, _b_.float)){return self.valueOf() == other.valueOf()}
185
if(_b_.isinstance(other, _b_.complex)){
198
if(fmt.type && 'bcdoxXn'.indexOf(fmt.type) == -1){
199
throw _b_.ValueError.$factory("Unknown format code '" + fmt.type +
227
if(fmt.sign !== undefined){
228
if((fmt.sign == " " || fmt.sign == "+" ) && self >= 0){
229
res = fmt.sign + res
230
}
231
}
250
for(var i = 0; i < nb; i++){
251
chunks.push(rest.substring(len - 3 * i - 3, len - 3 * i))
273
return int.__hashvalue__ || $B.$py_next_hash-- // for hash of int type (not instance of int)
299
try{
300
return int.$factory($B.long_int.__lshift__($B.long_int.$factory(self),
301
$B.long_int.$factory(other)))
302
}catch(err){
303
console.log('err in lshift', self, other)
304
throw err
305
}
313
if(other.__class__ === $B.long_int){
314
return $B.long_int.__mod__($B.long_int.$factory(self), other)
315
}
318
if(other === false){other = 0}
319
else if(other === true){other = 1}
320
if(other == 0){throw _b_.ZeroDivisionError.$factory(
330
if(other.__class__ == $B.long_int){
331
return $B.long_int.__mul__($B.long_int.$factory(self),
332
$B.long_int.$factory(other))
333
}
339
return int.$factory($B.long_int.__mul__($B.long_int.$factory(self),
340
$B.long_int.$factory(other)))
341
}
346
int.__ne__ = function(self, other){
347
var res = int.__eq__(self, other)
348
return (res === _b_.NotImplemented) ? res : !res
349
}
350
354
if(cls === undefined){
355
throw _b_.TypeError.$factory("int.__new__(): not enough arguments")
357
throw _b_.TypeError.$factory("int.__new__(X): X is not a type object")
358
}
359
if(cls === int){return int.$factory(value)}
360
return {
361
__class__: cls,
369
function extended_euclidean(a, b){
370
var d, u, v
371
if(b == 0){
372
return [a, 1, 0]
373
}else{
374
[d, u, v] = extended_euclidean(b, a % b)
375
return [d, v, u - Math.floor(a / b) * v]
376
}
377
}
378
384
other = int_value(other)
385
switch(other.valueOf()) {
386
case 0:
387
return int.$factory(1)
388
case 1:
389
return int.$factory(self.valueOf())
392
// If z is provided, the algorithm is faster than computing
393
// self ** other then applying the modulo z
394
if(z == 1){return 0}
395
var result = 1,
396
base = self % z,
397
exponent = other,
398
long_int = $B.long_int
399
if(exponent < 0){
400
var gcd, inv, _
401
[gcd, inv, _] = extended_euclidean(self, z)
402
if(gcd !== 1){
403
throw _b_.ValueError.$factory("not relative primes: " +
404
self + ' and ' + z)
405
}
406
return int.__pow__(inv, -exponent, z)
407
}
408
while(exponent > 0){
409
if(exponent % 2 == 1){
410
if(result * base > $B.max_int){
411
result = long_int.__mul__(
412
long_int.$factory(result),
413
long_int.$factory(base))
414
result = long_int.__mod__(result, z)
415
}else{
416
result = (result * base) % z
417
}
418
}
419
exponent = exponent >> 1
420
if(base * base > $B.max_int){
421
base = long_int.__mul__(long_int.$factory(base),
422
long_int.$factory(base))
423
base = long_int.__mod__(base, z)
424
}else{
425
base = (base * base) % z
426
}
431
if(res > $B.min_int && res < $B.max_int){
432
return other > 0 ? res : new Number(res)
433
}else if(res !== Infinity && !isFinite(res)){
434
return res
435
}else{
436
if($B.BigInt){
437
return {
438
__class__: $B.long_int,
439
value: ($B.BigInt(self) ** $B.BigInt(other)).toString(),
440
pos: true
441
}
442
}
443
return $B.long_int.__pow__($B.long_int.$from_int(self),
444
$B.long_int.$from_int(other))
460
var rpow = $B.$getattr(other, "__rpow__", _b_.None)
461
if(rpow !== _b_.None){
462
return rpow(self)
463
}
467
function __newobj__(){
468
// __newobj__ is called with a generator as only argument
469
var $ = $B.args('__newobj__', 0, {}, [], arguments, {}, 'args', null),
470
args = $.args
471
var res = args.slice(1)
472
res.__class__ = args[0]
473
return res
474
}
475
476
int.__reduce_ex__ = function(self){
477
return $B.fast_tuple([
478
__newobj__,
479
$B.fast_tuple([self.__class__ || int, int_value(self)]),
480
_b_.None,
481
_b_.None,
482
_b_.None])
483
}
484
492
self = int_value(self)
493
if(typeof other == "number" || _b_.isinstance(other, int)){
495
return int.$factory($B.long_int.__rshift__($B.long_int.$factory(self),
496
$B.long_int.$factory(other)))
502
if(typeof self == "number" || typeof self == "boolean"){
503
var cl_name = $B.class_name(self)
504
if(_b_.dir(self).indexOf(attr) > -1){
505
var msg = "attribute '" + attr + `' of '${cl_name}'` +
506
"objects is not writable"
517
int.__sub__ = function(self, other){
518
self = int_value(self)
519
if(_b_.isinstance(other, int)){
520
if(other.__class__ == $B.long_int){
521
return $B.long_int.__sub__($B.long_int.$factory(self),
522
$B.long_int.$factory(other))
523
}
524
other = int_value(other)
525
var res = self - other
526
if(res > $B.min_int && res < $B.max_int){
527
return res
528
}else{
529
return $B.long_int.__sub__($B.long_int.$factory(self),
530
$B.long_int.$factory(other))
531
}
532
}
533
return _b_.NotImplemented
534
}
535
542
if(other.__class__ === $B.long_int){
543
return new Number(self / parseInt(other.value))
544
}
545
return new Number(self / other)
551
s = _b_.bin(self)
552
s = $B.$getattr(s, "lstrip")("-0b") // remove leading zeros and minus sign
557
int.numerator = function(self){
558
return int_value(self)
559
}
560
int.denominator = function(self){
561
return int.$factory(1)
562
}
563
int.imag = function(self){
564
return int.$factory(0)
565
}
566
int.real = function(self){
567
return self
568
}
569
570
for(var attr of ['numerator', 'denominator', 'imag', 'real']){
571
int[attr].setter = (function(x){
572
return function(self, value){
573
throw _b_.AttributeError.$factory(`attribute '${x}' of ` +
574
`'${$B.class_name(self)}' objects is not writable`)
575
}
576
})(attr)
577
}
584
self = int_value(self)
585
if(typeof other == "number" || _b_.isinstance(other, int)){
586
if(other.__class__ === $B.long_int){
587
return $B.long_int.__sub__($B.long_int.$factory(self),
588
$B.long_int.$factory(other))
591
if(self > $B.max_int32 || self < $B.min_int32 ||
592
other > $B.max_int32 || other < $B.min_int32){
593
return $B.long_int.__sub__($B.long_int.$factory(self),
594
$B.long_int.$factory(other))
604
var opf = $op_func.replace(/-/gm, $op)
605
opf = opf.replace(new RegExp("sub", "gm"), $ops[$op])
606
eval("int.__" + $ops[$op] + "__ = " + opf)
632
eval("int.__"+$B.$comps[$op] + "__ = " +
633
$comp_func.replace(/>/gm, $op).
634
replace(/__gt__/gm,"__" + $B.$comps[$op] + "__").
635
replace(/__lt__/, "__" + $B.$inv_comps[$op] + "__"))
639
var r_opnames = ["add", "sub", "mul", "truediv", "floordiv", "mod", "pow",
640
"lshift", "rshift", "and", "xor", "or", "divmod"]
641
642
for(var r_opname of r_opnames){
643
if(int["__r" + r_opname + "__"] === undefined &&
644
int['__' + r_opname + '__']){
645
int["__r" + r_opname + "__"] = (function(name){
646
return function(self, other){
647
if(_b_.isinstance(other, int)){
648
other = int_value(other)
649
return int["__" + name + "__"](other, self)
650
}
651
return _b_.NotImplemented
652
}
653
})(r_opname)
654
}
655
}
657
var $valid_digits = function(base) {
658
var digits = ""
659
if(base === 0){return "0"}
660
if(base < 10){
676
if(typeof value == "number" &&
677
(base === undefined || base == 10)){return parseInt(value)}
683
var $ns = $B.args("int", 2, {x:null, base:null}, ["x", "base"], arguments,
684
{"base": 10}, null, null),
685
value = $ns["x"],
686
base = $ns["base"]
707
if(base == 10){
708
if(value < $B.min_int || value > $B.max_int){
709
return $B.long_int.$factory(value)
710
}
716
var res = parseInt(value, base)
717
if(value < $B.min_int || value > $B.max_int){
718
return $B.long_int.$factory(value, base)
719
}
724
if(value === true){return Number(1)}
725
if(value === false){return Number(0)}
726
if(value.__class__ === $B.long_int){
733
function invalid(value, base){
734
throw _b_.ValueError.$factory("invalid literal for int() with base " +
735
base + ": '" + _b_.str.$factory(value) + "'")
736
}
741
if(typeof value == "string") {
742
var _value = value.trim() // remove leading/trailing whitespace
743
if(_value.length == 2 && base == 0 &&
744
(_value == "0b" || _value == "0o" || _value == "0x")){
745
throw _b_.ValueError.$factory("invalid value")
746
}
748
var _pre = _value.substr(0, 2).toUpperCase()
749
if(base == 0){
750
if(_pre == "0B"){base = 2}
751
if(_pre == "0O"){base = 8}
752
if(_pre == "0X"){base = 16}
753
}else if(_pre == "0X" && base != 16){invalid(_value, base)}
754
else if(_pre == "0O" && base != 8){invalid(_value, base)}
765
var _digits = $valid_digits(base),
766
_re = new RegExp("^[+-]?[" + _digits + "]" +
767
"[" + _digits + "_]*$", "i"),
768
match = _re.exec(_value)
795
throw _b_.TypeError.$factory(
796
"int() argument must be a string, a bytes-like " +
797
"object or a number, not '" + $B.class_name(value) + "'")
806
if(obj === null || obj === undefined ){ return false}
807
switch(typeof obj){
808
case "boolean":
809
return obj
810
case "number":
811
case "string":
812
if(obj){return true}
813
return false
814
default:
816
var klass = obj.__class__ || $B.get_class(obj),
817
missing = {},
818
bool_method = $B.$getattr(klass, "__bool__", missing)
819
if(bool_method === missing){
820
try{return _b_.len(obj) > 0}
823
var res = $B.$call(bool_method)(obj)
824
if(res !== true && res !== false){
825
throw _b_.TypeError.$factory("__bool__ should return " +
826
"bool, returned " + $B.class_name(res))
827
}
828
return res
842
$native: true,
843
$descriptors: {
844
"numerator": true,
845
"denominator": true,
846
"imag": true,
847
"real": true
848
}
852
if(_b_.isinstance(other, bool)){
853
return self && other
854
}else if(_b_.isinstance(other, int)){
855
return int.__and__(bool.__index__(self), int.__index__(other))
856
}
857
return _b_.NotImplemented
860
bool.__float__ = function(self){
861
return self ? new Number(1) : new Number(0)
862
}
863
872
if(_b_.isinstance(other, bool)){
873
return self || other
874
}else if(_b_.isinstance(other, int)){
875
return int.__or__(bool.__index__(self), int.__index__(other))
876
}
877
return _b_.NotImplemented
882
bool.__repr__ = function(self){
883
$B.builtins_repr_check(bool, arguments) // in brython_builtins.js
888
if(_b_.isinstance(other, bool)){
889
return self ^ other ? true : false
890
}else if(_b_.isinstance(other, int)){
891
return int.__xor__(bool.__index__(self), int.__index__(other))
892
}
893
return _b_.NotImplemented
896
bool.$factory = function(){
897
// Calls $B.$bool, which is used inside the generated JS code and skips
898
// arguments control.
904
bool.numerator = int.numerator
905
bool.denominator = int.denominator
906
bool.real = int.real
907
bool.imag = int.imag
908