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
Jul 28, 2018
Feb 20, 2020
Jul 28, 2018
Oct 9, 2021
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
925 lines (835 sloc)
27.1 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")
368
throw _b_.TypeError.$factory("int.__new__(X): X is not a type object")
369
}
370
if(cls === int){return int.$factory(value)}
371
return {
372
__class__: cls,
380
function extended_euclidean(a, b){
381
var d, u, v
382
if(b == 0){
383
return [a, 1, 0]
384
}else{
385
[d, u, v] = extended_euclidean(b, a % b)
386
return [d, v, u - Math.floor(a / b) * v]
387
}
388
}
389
395
other = int_value(other)
396
switch(other.valueOf()) {
397
case 0:
398
return int.$factory(1)
399
case 1:
400
return int.$factory(self.valueOf())
401
}
402
if(z !== undefined && z !== _b_.None){
403
// If z is provided, the algorithm is faster than computing
404
// self ** other then applying the modulo z
405
if(z == 1){return 0}
406
var result = 1,
407
base = self % z,
408
exponent = other,
409
long_int = $B.long_int
410
if(exponent < 0){
411
var gcd, inv, _
412
[gcd, inv, _] = extended_euclidean(self, z)
413
if(gcd !== 1){
414
throw _b_.ValueError.$factory("not relative primes: " +
415
self + ' and ' + z)
416
}
417
return int.__pow__(inv, -exponent, z)
418
}
419
while(exponent > 0){
420
if(exponent % 2 == 1){
421
if(result * base > $B.max_int){
422
result = long_int.__mul__(
423
long_int.$factory(result),
424
long_int.$factory(base))
425
result = long_int.__mod__(result, z)
426
}else{
427
result = (result * base) % z
428
}
429
}
430
exponent = exponent >> 1
431
if(base * base > $B.max_int){
432
base = long_int.__mul__(long_int.$factory(base),
433
long_int.$factory(base))
434
base = long_int.__mod__(base, z)
435
}else{
436
base = (base * base) % z
437
}
438
}
439
return result
440
}
441
var res = Math.pow(self.valueOf(), other.valueOf())
442
if(res > $B.min_int && res < $B.max_int){
443
return other > 0 ? res : new Number(res)
444
}else if(res !== Infinity && !isFinite(res)){
445
return res
446
}else{
447
if($B.BigInt){
448
return {
449
__class__: $B.long_int,
450
value: ($B.BigInt(self) ** $B.BigInt(other)).toString(),
451
pos: true
452
}
453
}
454
return $B.long_int.__pow__($B.long_int.$from_int(self),
455
$B.long_int.$from_int(other))
456
}
471
var rpow = $B.$getattr(other, "__rpow__", _b_.None)
472
if(rpow !== _b_.None){
473
return rpow(self)
474
}
478
function __newobj__(){
479
// __newobj__ is called with a generator as only argument
480
var $ = $B.args('__newobj__', 0, {}, [], arguments, {}, 'args', null),
481
args = $.args
482
var res = args.slice(1)
483
res.__class__ = args[0]
484
return res
485
}
486
487
int.__reduce_ex__ = function(self){
488
return $B.fast_tuple([
489
__newobj__,
490
$B.fast_tuple([self.__class__ || int, int_value(self)]),
491
_b_.None,
492
_b_.None,
493
_b_.None])
494
}
495
503
self = int_value(self)
504
if(typeof other == "number" || _b_.isinstance(other, int)){
506
return int.$factory($B.long_int.__rshift__($B.long_int.$factory(self),
507
$B.long_int.$factory(other)))
513
if(typeof self == "number" || typeof self == "boolean"){
514
var cl_name = $B.class_name(self)
515
if(_b_.dir(self).indexOf(attr) > -1){
516
throw _b_.AttributeError.$factory("attribute '" + attr +
517
`' of '${cl_name}' objects is not writable`)
519
throw _b_.AttributeError.$factory(`'${cl_name}' object` +
520
` has no attribute '${attr}'`)
529
int.__sub__ = function(self, other){
530
self = int_value(self)
531
if(_b_.isinstance(other, int)){
532
if(other.__class__ == $B.long_int){
533
return $B.long_int.__sub__($B.long_int.$factory(self),
534
$B.long_int.$factory(other))
535
}
536
other = int_value(other)
537
var res = self - other
538
if(res > $B.min_int && res < $B.max_int){
539
return res
540
}else{
541
return $B.long_int.__sub__($B.long_int.$factory(self),
542
$B.long_int.$factory(other))
543
}
544
}
545
return _b_.NotImplemented
546
}
547
554
if(other.__class__ === $B.long_int){
555
return new Number(self / parseInt(other.value))
556
}
557
return new Number(self / other)
563
s = _b_.bin(self)
564
s = $B.$getattr(s, "lstrip")("-0b") // remove leading zeros and minus sign
569
int.numerator = function(self){
570
return int_value(self)
571
}
572
int.denominator = function(self){
573
return int.$factory(1)
574
}
575
int.imag = function(self){
576
return int.$factory(0)
577
}
578
int.real = function(self){
579
return self
580
}
581
582
for(var attr of ['numerator', 'denominator', 'imag', 'real']){
583
int[attr].setter = (function(x){
584
return function(self, value){
585
throw _b_.AttributeError.$factory(`attribute '${x}' of ` +
586
`'${$B.class_name(self)}' objects is not writable`)
587
}
588
})(attr)
589
}
596
self = int_value(self)
597
if(typeof other == "number" || _b_.isinstance(other, int)){
598
if(other.__class__ === $B.long_int){
599
return $B.long_int.__sub__($B.long_int.$factory(self),
600
$B.long_int.$factory(other))
603
if(self > $B.max_int32 || self < $B.min_int32 ||
604
other > $B.max_int32 || other < $B.min_int32){
605
return $B.long_int.__sub__($B.long_int.$factory(self),
606
$B.long_int.$factory(other))
616
var opf = $op_func.replace(/-/gm, $op)
617
opf = opf.replace(new RegExp("sub", "gm"), $ops[$op])
618
eval("int.__" + $ops[$op] + "__ = " + opf)
644
eval("int.__"+$B.$comps[$op] + "__ = " +
645
$comp_func.replace(/>/gm, $op).
646
replace(/__gt__/gm,"__" + $B.$comps[$op] + "__").
647
replace(/__lt__/, "__" + $B.$inv_comps[$op] + "__"))
651
var r_opnames = ["add", "sub", "mul", "truediv", "floordiv", "mod", "pow",
652
"lshift", "rshift", "and", "xor", "or", "divmod"]
653
654
for(var r_opname of r_opnames){
655
if(int["__r" + r_opname + "__"] === undefined &&
656
int['__' + r_opname + '__']){
657
int["__r" + r_opname + "__"] = (function(name){
658
return function(self, other){
659
if(_b_.isinstance(other, int)){
660
other = int_value(other)
661
return int["__" + name + "__"](other, self)
662
}
663
return _b_.NotImplemented
664
}
665
})(r_opname)
666
}
667
}
669
var $valid_digits = function(base) {
670
var digits = ""
671
if(base === 0){return "0"}
672
if(base < 10){
688
if(typeof value == "number" &&
689
(base === undefined || base == 10)){return parseInt(value)}
695
var $ns = $B.args("int", 2, {x:null, base:null}, ["x", "base"], arguments,
696
{"base": 10}, null, null),
697
value = $ns["x"],
698
base = $ns["base"]
719
if(base == 10){
720
if(value < $B.min_int || value > $B.max_int){
721
return $B.long_int.$factory(value)
722
}
728
var res = parseInt(value, base)
729
if(value < $B.min_int || value > $B.max_int){
730
return $B.long_int.$factory(value, base)
731
}
736
if(value === true){return Number(1)}
737
if(value === false){return Number(0)}
738
if(value.__class__ === $B.long_int){
745
function invalid(value, base){
746
throw _b_.ValueError.$factory("invalid literal for int() with base " +
747
base + ": '" + _b_.str.$factory(value) + "'")
748
}
753
if(typeof value == "string") {
754
var _value = value.trim() // remove leading/trailing whitespace
755
if(_value.length == 2 && base == 0 &&
756
(_value == "0b" || _value == "0o" || _value == "0x")){
757
throw _b_.ValueError.$factory("invalid value")
758
}
760
var _pre = _value.substr(0, 2).toUpperCase()
761
if(base == 0){
762
if(_pre == "0B"){base = 2}
763
if(_pre == "0O"){base = 8}
764
if(_pre == "0X"){base = 16}
765
}else if(_pre == "0X" && base != 16){invalid(_value, base)}
766
else if(_pre == "0O" && base != 8){invalid(_value, base)}
777
var _digits = $valid_digits(base),
778
_re = new RegExp("^[+-]?[" + _digits + "]" +
779
"[" + _digits + "_]*$", "i"),
780
match = _re.exec(_value)
807
throw _b_.TypeError.$factory(
808
"int() argument must be a string, a bytes-like " +
809
"object or a number, not '" + $B.class_name(value) + "'")
818
if(obj === null || obj === undefined ){ return false}
819
switch(typeof obj){
820
case "boolean":
821
return obj
822
case "number":
823
case "string":
824
if(obj){return true}
825
return false
826
default:
828
var klass = obj.__class__ || $B.get_class(obj),
829
missing = {},
830
bool_method = $B.$getattr(klass, "__bool__", missing)
831
if(bool_method === missing){
832
try{return _b_.len(obj) > 0}
835
var res = $B.$call(bool_method)(obj)
836
if(res !== true && res !== false){
837
throw _b_.TypeError.$factory("__bool__ should return " +
838
"bool, returned " + $B.class_name(res))
839
}
840
return res
854
$native: true,
855
$descriptors: {
856
"numerator": true,
857
"denominator": true,
858
"imag": true,
859
"real": true
860
}
864
if(_b_.isinstance(other, bool)){
865
return self && other
866
}else if(_b_.isinstance(other, int)){
867
return int.__and__(bool.__index__(self), int.__index__(other))
868
}
869
return _b_.NotImplemented
872
bool.__float__ = function(self){
873
return self ? new Number(1) : new Number(0)
874
}
875
884
if(_b_.isinstance(other, bool)){
885
return self || other
886
}else if(_b_.isinstance(other, int)){
887
return int.__or__(bool.__index__(self), int.__index__(other))
888
}
889
return _b_.NotImplemented
894
bool.__repr__ = function(self){
895
$B.builtins_repr_check(bool, arguments) // in brython_builtins.js
900
if(_b_.isinstance(other, bool)){
901
return self ^ other ? true : false
902
}else if(_b_.isinstance(other, int)){
903
return int.__xor__(bool.__index__(self), int.__index__(other))
904
}
905
return _b_.NotImplemented
908
bool.$factory = function(){
909
// Calls $B.$bool, which is used inside the generated JS code and skips
910
// arguments control.
916
bool.numerator = int.numerator
917
bool.denominator = int.denominator
918
bool.real = int.real
919
bool.imag = int.imag
920