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
Jul 25, 2021
Mar 10, 2018
Mar 10, 2018
Aug 2, 2018
Mar 10, 2018
Mar 10, 2018
Feb 22, 2019
Mar 10, 2018
Feb 20, 2020
Jul 28, 2018
Oct 9, 2021
Feb 15, 2020
Feb 11, 2018
Mar 10, 2018
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
938 lines (847 sloc)
27.3 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
}
183
if(_b_.isinstance(other, _b_.float)){
184
return self.valueOf() == other.valueOf()
185
}
199
if(fmt.type && 'bcdoxXn'.indexOf(fmt.type) == -1){
200
throw _b_.ValueError.$factory("Unknown format code '" + fmt.type +
228
if(fmt.sign !== undefined){
229
if((fmt.sign == " " || fmt.sign == "+" ) && self >= 0){
230
res = fmt.sign + res
231
}
232
}
251
for(var i = 0; i < nb; i++){
252
chunks.push(rest.substring(len - 3 * i - 3, len - 3 * i))
273
if(self.$brython_value){
274
// int subclass
275
var hash_method = $B.$getattr(self.__class__, '__hash__')
276
if(hash_method === int.__hash__){
277
if(typeof self.$brython_value == "number"){
278
return self.$brython_value
279
}else{ // long int
280
return $B.long_int.__hash__(self.$brython_value)
281
}
282
}else{
283
return hash_method(self)
284
}
285
}
286
return self.valueOf()
310
try{
311
return int.$factory($B.long_int.__lshift__($B.long_int.$factory(self),
312
$B.long_int.$factory(other)))
313
}catch(err){
314
console.log('err in lshift', self, other)
315
throw err
316
}
324
if(other.__class__ === $B.long_int){
325
return $B.long_int.__mod__($B.long_int.$factory(self), other)
326
}
329
if(other === false){other = 0}
330
else if(other === true){other = 1}
331
if(other == 0){throw _b_.ZeroDivisionError.$factory(
341
if(other.__class__ == $B.long_int){
342
return $B.long_int.__mul__($B.long_int.$factory(self),
343
$B.long_int.$factory(other))
344
}
350
return int.$factory($B.long_int.__mul__($B.long_int.$factory(self),
351
$B.long_int.$factory(other)))
352
}
357
int.__ne__ = function(self, other){
358
var res = int.__eq__(self, other)
359
return (res === _b_.NotImplemented) ? res : !res
360
}
361
365
if(cls === undefined){
366
throw _b_.TypeError.$factory("int.__new__(): not enough arguments")
382
function extended_euclidean(a, b){
383
var d, u, v
384
if(b == 0){
385
return [a, 1, 0]
386
}else{
387
[d, u, v] = extended_euclidean(b, a % b)
388
return [d, v, u - Math.floor(a / b) * v]
389
}
390
}
391
397
other = int_value(other)
398
switch(other.valueOf()) {
399
case 0:
400
return int.$factory(1)
401
case 1:
402
return int.$factory(self.valueOf())
403
}
404
if(z !== undefined && z !== _b_.None){
405
// If z is provided, the algorithm is faster than computing
406
// self ** other then applying the modulo z
407
if(z == 1){return 0}
408
var result = 1,
409
base = self % z,
410
exponent = other,
411
long_int = $B.long_int
412
if(exponent < 0){
413
var gcd, inv, _
414
[gcd, inv, _] = extended_euclidean(self, z)
415
if(gcd !== 1){
416
throw _b_.ValueError.$factory("not relative primes: " +
417
self + ' and ' + z)
418
}
419
return int.__pow__(inv, -exponent, z)
420
}
421
while(exponent > 0){
422
if(exponent % 2 == 1){
423
if(result * base > $B.max_int){
424
result = long_int.__mul__(
425
long_int.$factory(result),
426
long_int.$factory(base))
427
result = long_int.__mod__(result, z)
428
}else{
429
result = (result * base) % z
430
}
431
}
432
exponent = exponent >> 1
433
if(base * base > $B.max_int){
434
base = long_int.__mul__(long_int.$factory(base),
435
long_int.$factory(base))
436
base = long_int.__mod__(base, z)
437
}else{
438
base = (base * base) % z
439
}
440
}
441
return result
442
}
443
var res = Math.pow(self.valueOf(), other.valueOf())
444
if(res > $B.min_int && res < $B.max_int){
445
return other > 0 ? res : new Number(res)
446
}else if(res !== Infinity && !isFinite(res)){
447
return res
448
}else{
449
if($B.BigInt){
450
return {
451
__class__: $B.long_int,
452
value: ($B.BigInt(self) ** $B.BigInt(other)).toString(),
453
pos: true
454
}
455
}
456
return $B.long_int.__pow__($B.long_int.$from_int(self),
457
$B.long_int.$from_int(other))
458
}
473
var rpow = $B.$getattr(other, "__rpow__", _b_.None)
474
if(rpow !== _b_.None){
475
return rpow(self)
476
}
480
function __newobj__(){
481
// __newobj__ is called with a generator as only argument
482
var $ = $B.args('__newobj__', 0, {}, [], arguments, {}, 'args', null),
483
args = $.args
484
var res = args.slice(1)
485
res.__class__ = args[0]
486
return res
487
}
488
489
int.__reduce_ex__ = function(self){
490
return $B.fast_tuple([
491
__newobj__,
492
$B.fast_tuple([self.__class__ || int, int_value(self)]),
493
_b_.None,
494
_b_.None,
495
_b_.None])
496
}
497
505
self = int_value(self)
506
if(typeof other == "number" || _b_.isinstance(other, int)){
508
return int.$factory($B.long_int.__rshift__($B.long_int.$factory(self),
509
$B.long_int.$factory(other)))
515
if(typeof self == "number" || typeof self == "boolean"){
516
var cl_name = $B.class_name(self)
517
if(_b_.dir(self).indexOf(attr) > -1){
518
throw _b_.AttributeError.$factory("attribute '" + attr +
519
`' of '${cl_name}' objects is not writable`)
521
throw _b_.AttributeError.$factory(`'${cl_name}' object` +
522
` has no attribute '${attr}'`)
531
int.__sub__ = function(self, other){
532
self = int_value(self)
533
if(_b_.isinstance(other, int)){
534
if(other.__class__ == $B.long_int){
535
return $B.long_int.__sub__($B.long_int.$factory(self),
536
$B.long_int.$factory(other))
537
}
538
other = int_value(other)
539
var res = self - other
540
if(res > $B.min_int && res < $B.max_int){
541
return res
542
}else{
543
return $B.long_int.__sub__($B.long_int.$factory(self),
544
$B.long_int.$factory(other))
545
}
546
}
547
return _b_.NotImplemented
548
}
549
556
if(other.__class__ === $B.long_int){
557
return new Number(self / parseInt(other.value))
558
}
559
return new Number(self / other)
564
int.bit_count = function(self){
565
var s = _b_.bin(_b_.abs(self)),
566
nb = 0
567
for(var x of s){
568
if(x == '1'){
569
nb++
570
}
571
}
572
return nb
573
}
574
582
int.numerator = function(self){
583
return int_value(self)
584
}
585
int.denominator = function(self){
586
return int.$factory(1)
587
}
588
int.imag = function(self){
589
return int.$factory(0)
590
}
591
int.real = function(self){
592
return self
593
}
594
595
for(var attr of ['numerator', 'denominator', 'imag', 'real']){
596
int[attr].setter = (function(x){
597
return function(self, value){
598
throw _b_.AttributeError.$factory(`attribute '${x}' of ` +
599
`'${$B.class_name(self)}' objects is not writable`)
600
}
601
})(attr)
602
}
609
self = int_value(self)
610
if(typeof other == "number" || _b_.isinstance(other, int)){
611
if(other.__class__ === $B.long_int){
612
return $B.long_int.__sub__($B.long_int.$factory(self),
613
$B.long_int.$factory(other))
616
if(self > $B.max_int32 || self < $B.min_int32 ||
617
other > $B.max_int32 || other < $B.min_int32){
618
return $B.long_int.__sub__($B.long_int.$factory(self),
619
$B.long_int.$factory(other))
629
var opf = $op_func.replace(/-/gm, $op)
630
opf = opf.replace(new RegExp("sub", "gm"), $ops[$op])
631
eval("int.__" + $ops[$op] + "__ = " + opf)
657
eval("int.__"+$B.$comps[$op] + "__ = " +
658
$comp_func.replace(/>/gm, $op).
659
replace(/__gt__/gm,"__" + $B.$comps[$op] + "__").
660
replace(/__lt__/, "__" + $B.$inv_comps[$op] + "__"))
664
var r_opnames = ["add", "sub", "mul", "truediv", "floordiv", "mod", "pow",
665
"lshift", "rshift", "and", "xor", "or", "divmod"]
666
667
for(var r_opname of r_opnames){
668
if(int["__r" + r_opname + "__"] === undefined &&
669
int['__' + r_opname + '__']){
670
int["__r" + r_opname + "__"] = (function(name){
671
return function(self, other){
672
if(_b_.isinstance(other, int)){
673
other = int_value(other)
674
return int["__" + name + "__"](other, self)
675
}
676
return _b_.NotImplemented
677
}
678
})(r_opname)
679
}
680
}
682
var $valid_digits = function(base) {
683
var digits = ""
684
if(base === 0){return "0"}
685
if(base < 10){
701
if(typeof value == "number" &&
702
(base === undefined || base == 10)){return parseInt(value)}
708
var $ns = $B.args("int", 2, {x:null, base:null}, ["x", "base"], arguments,
709
{"base": 10}, null, null),
710
value = $ns["x"],
711
base = $ns["base"]
732
if(base == 10){
733
if(value < $B.min_int || value > $B.max_int){
734
return $B.long_int.$factory(value)
735
}
741
var res = parseInt(value, base)
742
if(value < $B.min_int || value > $B.max_int){
743
return $B.long_int.$factory(value, base)
744
}
749
if(value === true){return Number(1)}
750
if(value === false){return Number(0)}
751
if(value.__class__ === $B.long_int){
758
function invalid(value, base){
759
throw _b_.ValueError.$factory("invalid literal for int() with base " +
760
base + ": '" + _b_.str.$factory(value) + "'")
761
}
766
if(typeof value == "string") {
767
var _value = value.trim() // remove leading/trailing whitespace
768
if(_value.length == 2 && base == 0 &&
769
(_value == "0b" || _value == "0o" || _value == "0x")){
770
throw _b_.ValueError.$factory("invalid value")
771
}
773
var _pre = _value.substr(0, 2).toUpperCase()
774
if(base == 0){
775
if(_pre == "0B"){base = 2}
776
if(_pre == "0O"){base = 8}
777
if(_pre == "0X"){base = 16}
778
}else if(_pre == "0X" && base != 16){invalid(_value, base)}
779
else if(_pre == "0O" && base != 8){invalid(_value, base)}
790
var _digits = $valid_digits(base),
791
_re = new RegExp("^[+-]?[" + _digits + "]" +
792
"[" + _digits + "_]*$", "i"),
793
match = _re.exec(_value)
820
throw _b_.TypeError.$factory(
821
"int() argument must be a string, a bytes-like " +
822
"object or a number, not '" + $B.class_name(value) + "'")
831
if(obj === null || obj === undefined ){ return false}
832
switch(typeof obj){
833
case "boolean":
834
return obj
835
case "number":
836
case "string":
837
if(obj){return true}
838
return false
839
default:
841
var klass = obj.__class__ || $B.get_class(obj),
842
missing = {},
843
bool_method = $B.$getattr(klass, "__bool__", missing)
844
if(bool_method === missing){
845
try{return _b_.len(obj) > 0}
848
var res = $B.$call(bool_method)(obj)
849
if(res !== true && res !== false){
850
throw _b_.TypeError.$factory("__bool__ should return " +
851
"bool, returned " + $B.class_name(res))
852
}
853
return res
867
$native: true,
868
$descriptors: {
869
"numerator": true,
870
"denominator": true,
871
"imag": true,
872
"real": true
873
}
877
if(_b_.isinstance(other, bool)){
878
return self && other
879
}else if(_b_.isinstance(other, int)){
880
return int.__and__(bool.__index__(self), int.__index__(other))
881
}
882
return _b_.NotImplemented
885
bool.__float__ = function(self){
886
return self ? new Number(1) : new Number(0)
887
}
888
897
if(_b_.isinstance(other, bool)){
898
return self || other
899
}else if(_b_.isinstance(other, int)){
900
return int.__or__(bool.__index__(self), int.__index__(other))
901
}
902
return _b_.NotImplemented
907
bool.__repr__ = function(self){
908
$B.builtins_repr_check(bool, arguments) // in brython_builtins.js
913
if(_b_.isinstance(other, bool)){
914
return self ^ other ? true : false
915
}else if(_b_.isinstance(other, int)){
916
return int.__xor__(bool.__index__(self), int.__index__(other))
917
}
918
return _b_.NotImplemented
921
bool.$factory = function(){
922
// Calls $B.$bool, which is used inside the generated JS code and skips
923
// arguments control.
929
bool.numerator = int.numerator
930
bool.denominator = int.denominator
931
bool.real = int.real
932
bool.imag = int.imag
933