Permalink
Sep 2, 2017
May 19, 2017
Dec 18, 2015
Dec 14, 2015
Dec 7, 2017
Jan 25, 2017
Dec 14, 2017
Jan 13, 2017
Jan 13, 2017
Jan 13, 2017
Jan 13, 2017
Jan 13, 2017
Jan 13, 2017
Newer
100644
694 lines (589 sloc)
21.1 KB
6
7
function $err(op,other){
8
var msg = "unsupported operand type(s) for "+op
9
msg += ": 'int' and '"+$B.get_class(other).__name__+"'"
10
throw _b_.TypeError(msg)
11
}
12
26
{bytes:null, byteorder:null, signed:null}, ['bytes', 'byteorder', 'signed'],
27
arguments, {signed:False}, null, null)
32
var _bytes, _len
33
if (isinstance(x, [_b_.list, _b_.tuple])) {
34
_bytes=x
35
_len=len(x)
39
} else {
40
_b_.TypeError("Error! " + _b_.type(x) + " is not supported in int.from_bytes. fix me!")
43
switch(byteorder) {
44
case 'big':
45
var num = _bytes[_len - 1];
46
var _mult=256
47
for (var i = (_len - 2); i >= 0; i--) {
48
// For operations, use the functions that can take or return
49
// big integers
50
num = $B.add($B.mul(_mult, _bytes[i]), num)
51
_mult = $B.mul(_mult,256)
56
case 'little':
57
var num = _bytes[0]
58
if (num >= 128) num = num - 256
59
var _mult=256
60
for (var i = 1; i < _len; i++) {
67
}
68
69
throw _b_.ValueError("byteorder must be either 'little' or 'big'");
70
}
71
72
$IntDict.to_bytes = function(length, byteorder, star) {
73
//var len = x.length
74
throw _b_.NotImplementedError("int.to_bytes is not implemented yet")
75
}
76
77
78
//$IntDict.__and__ = function(self,other){return self & other} // bitwise AND
79
91
$IntDict.__eq__ = function(self,other){
92
// compare object "self" to class "int"
93
if(other===undefined) return self===int
94
if(isinstance(other,int)) return self.valueOf()==other.valueOf()
110
function preformat(self, fmt){
111
if(fmt.empty){return _b_.str(self)}
112
if(fmt.type && 'bcdoxXn'.indexOf(fmt.type)==-1){
113
throw _b_.ValueError("Unknown format code '"+fmt.type+
114
"' for object of type 'int'")
115
}
117
switch(fmt.type){
118
case undefined:
119
case 'd':
120
return self.toString()
121
case 'b':
141
if(fmt.type && 'eEfFgG%'.indexOf(fmt.type)!=-1){
142
// Call __format__ on float(self)
164
$IntDict.__floordiv__ = function(self,other){
165
if(isinstance(other,int)){
166
if(other==0) throw ZeroDivisionError('division by zero')
167
return Math.floor(self/other)
168
}
169
if(isinstance(other,_b_.float)){
170
if(!other.valueOf()) throw ZeroDivisionError('division by zero')
171
return Math.floor(self/other)
172
}
173
if(hasattr(other,'__rfloordiv__')){
174
return getattr(other,'__rfloordiv__')(self)
175
}
176
$err("//",other)
177
}
178
179
$IntDict.__hash__ = function(self){
180
if (self === undefined) {
181
return $IntDict.__hashvalue__ || $B.$py_next_hash-- // for hash of int type (not instance of int)
182
}
183
184
return self.valueOf()
185
}
186
187
//$IntDict.__ior__ = function(self,other){return self | other} // bitwise OR
188
189
$IntDict.__index__ = function(self){return self}
190
191
$IntDict.__init__ = function(self,value){
192
if(value===undefined){value=0}
193
self.toString = function(){return value}
194
//self.valueOf = function(){return value}
196
}
197
198
$IntDict.__int__ = function(self){return self}
199
200
$IntDict.__invert__ = function(self){return ~self}
201
202
// bitwise left shift
203
$IntDict.__lshift__ = function(self,other){
204
if(isinstance(other, int)){
205
return int($B.LongInt.$dict.__lshift__($B.LongInt(self), $B.LongInt(other)))
206
}
207
var rlshift = getattr(other, '__rlshift__', null)
208
if(rlshift!==null){return rlshift(self)}
209
$err('<<', other)
210
}
211
212
$IntDict.__mod__ = function(self,other) {
213
// can't use Javascript % because it works differently for negative numbers
214
if(isinstance(other,_b_.tuple) && other.length==1) other=other[0]
215
if(isinstance(other,[int, _b_.float, bool])){
216
if(other===false){other=0}else if(other===true){other=1}
217
if(other==0){throw _b_.ZeroDivisionError(
218
"integer division or modulo by zero")}
219
return (self%other+other)%other
220
}
221
if(hasattr(other,'__rmod__')) return getattr(other,'__rmod__')(self)
222
$err('%',other)
223
}
224
230
231
// this will be quick check, so lets do it early.
232
if(typeof other==="string") {
233
return other.repeat(val)
234
}
235
236
if(isinstance(other,int)){
237
var res = self*other
238
if(res>$B.min_int && res<$B.max_int){return res}
250
return _b_.complex($IntDict.__mul__(self, other.$real),
251
$IntDict.__mul__(self, other.$imag))
252
}
253
if(isinstance(other,[_b_.list,_b_.tuple])){
254
var res = []
255
// make temporary copy of list
256
var $temp = other.slice(0,other.length)
257
for(var i=0;i<val;i++) res=res.concat($temp)
258
if(isinstance(other,_b_.tuple)) res=_b_.tuple(res)
259
return res
260
}
261
if(hasattr(other,'__rmul__')) return getattr(other,'__rmul__')(self)
262
$err("*",other)
263
}
264
265
$IntDict.__name__ = 'int'
266
267
$IntDict.__neg__ = function(self){return -self}
268
269
$IntDict.__new__ = function(cls){
270
if(cls===undefined){throw _b_.TypeError('int.__new__(): not enough arguments')}
278
switch(other.valueOf()) {
279
case 0:
280
return int(1)
281
case 1:
282
return int(self.valueOf())
283
}
284
if(z !== undefined && z !== null){
285
// If z is provided, the algorithm is faster than computing
286
// self ** other then applying the modulo z
287
var res = (self % z + z) % z
288
for(var i=1; i<other; i++){
289
res *= self
290
res = (res % z + z) % z
291
}
292
return res
293
}
303
if(self>=0){return new Number(Math.pow(self, other.valueOf()))}
304
else{
305
// use complex power
306
return _b_.complex.$dict.__pow__(_b_.complex(self, 0), other)
307
}
312
}
313
if(hasattr(other,'__rpow__')) return getattr(other,'__rpow__')(self)
314
$err("**",other)
315
}
316
317
$IntDict.__repr__ = function(self){
318
if(self===int) return "<class 'int'>"
319
return self.toString()
320
}
321
322
// bitwise right shift
323
$IntDict.__rshift__ = function(self,other){
324
if(isinstance(other, int)){
325
return int($B.LongInt.$dict.__rshift__($B.LongInt(self), $B.LongInt(other)))
326
}
327
var rrshift = getattr(other, '__rrshift__', null)
328
if(rrshift!==null){return rrshift(self)}
329
$err('>>', other)
330
}
333
if(typeof self=="number"){
334
if($IntDict[attr]===undefined){
335
throw _b_.AttributeError("'int' object has no attribute '"+attr+"'")
336
}else{
337
throw _b_.AttributeError("'int' object attribute '"+attr+"' is read-only")
338
}
343
}
344
345
$IntDict.__str__ = $IntDict.__repr__
346
347
$IntDict.__truediv__ = function(self,other){
348
if(isinstance(other,int)){
349
if(other==0) throw ZeroDivisionError('division by zero')
350
if(other.__class__==$B.LongInt.$dict){return new Number(self/parseInt(other.value))}
354
if(!other.valueOf()) throw ZeroDivisionError('division by zero')
355
return new Number(self/other)
361
}
362
if(hasattr(other,'__rtruediv__')) return getattr(other,'__rtruediv__')(self)
363
$err("/",other)
364
}
365
366
//$IntDict.__xor__ = function(self,other){return self ^ other} // bitwise XOR
367
368
$IntDict.bit_length = function(self){
369
s = bin(self)
370
s = getattr(s,'lstrip')('-0b') // remove leading zeros and minus sign
371
return s.length // len('100101') --> 6
372
}
373
375
$IntDict.numerator = function(self){return self}
376
$IntDict.denominator = function(self){return int(1)}
377
$IntDict.imag = function(self){return int(0)}
378
$IntDict.real = function(self){return self}
379
387
if(other.__class__===$B.LongInt.$dict){
388
return $B.LongInt.$dict.__sub__($B.LongInt(self), $B.LongInt(other))
389
}
391
other > $B.max_int32 || other < $B.min_int32) {
392
return $B.LongInt.$dict.__sub__($B.LongInt(self), $B.LongInt(other))
393
}
394
return self-other
396
if(isinstance(other,_b_.bool)) return self-other
397
if(hasattr(other,'__rsub__')) return getattr(other,'__rsub__')(self)
398
$err("-",other)
399
}
400
401
$op_func += '' // source code
403
for(var $op in $ops){
404
var opf = $op_func.replace(/-/gm,$op)
405
opf = opf.replace(new RegExp('sub','gm'),$ops[$op])
406
eval('$IntDict.__'+$ops[$op]+'__ = '+opf)
407
}
408
409
// code for + and -
410
var $op_func = function(self,other){
411
if(isinstance(other,int)){
412
if(typeof other=='number'){
413
var res = self.valueOf()-other.valueOf()
414
if(res>=$B.min_int && res<=$B.max_int){return res}
429
}
430
if(isinstance(other,_b_.bool)){
431
var bool_value=0;
432
if(other.valueOf()) bool_value=1;
437
}
438
if(hasattr(other,'__rsub__')) return getattr(other,'__rsub__')(self)
439
throw $err('-',other)
440
}
441
$op_func += '' // source code
442
var $ops = {'+':'add','-':'sub'}
443
for(var $op in $ops){
444
var opf = $op_func.replace(/-/gm,$op)
445
opf = opf.replace(new RegExp('sub','gm'),$ops[$op])
446
eval('$IntDict.__'+$ops[$op]+'__ = '+opf)
447
}
448
449
// comparison methods
450
var $comp_func = function(self,other){
451
if (other.__class__ === $B.LongInt.$dict) {
452
return $B.LongInt.$dict.__lt__(other, $B.LongInt(self))
453
}
456
if(isinstance(other,_b_.bool)) {
457
return self.valueOf() > _b_.bool.$dict.__hash__(other)
458
}
459
if (hasattr(other, '__int__') || hasattr(other, '__index__')) {
460
return $IntDict.__gt__(self, $B.$GetInt(other))
461
}
463
// See if other has the opposite operator, eg < for >
464
var inv_op = getattr(other, '__lt__', null)
477
}
478
479
// add "reflected" methods
480
$B.make_rmethods($IntDict)
481
482
var $valid_digits=function(base) {
483
var digits=''
484
if (base === 0) return '0'
485
if (base < 10) {
486
for (var i=0; i < base; i++) digits+=String.fromCharCode(i+48)
487
return digits
488
}
489
490
var digits='0123456789'
491
// A = 65 (10 + 55)
492
for (var i=10; i < base; i++) digits+=String.fromCharCode(i+55)
493
return digits
494
}
495
504
if(base!==undefined){
505
if(!isinstance(value,[_b_.str,_b_.bytes,_b_.bytearray])){
506
throw TypeError("int() can't convert non-string with explicit base")
507
}
508
}
509
510
if(isinstance(value,_b_.complex)){
511
throw TypeError("can't convert complex to int")
512
}
513
520
if(value<$B.min_int || value>$B.max_int){
521
return $B.LongInt.$dict.$from_float(value)
522
}
526
if (!(base >=2 && base <= 36)) {
527
// throw error (base must be 0, or 2-36)
528
if (base != 0) throw _b_.ValueError("invalid base")
529
}
530
531
if (typeof value == 'number'){
532
533
if(base==10){
534
if(value < $B.min_int || value > $B.max_int) return $B.LongInt(value)
535
return value
536
}else if(value.toString().search('e')>-1){
537
// can't convert to another base if value is too big
538
throw _b_.OverflowError("can't convert to base "+base)
539
}else{
540
var res=parseInt(value, base)
541
if(res < $B.min_int || res > $B.max_int) return $B.LongInt(value,base)
542
return res
548
if(value.__class__===$B.LongInt.$dict){
549
var z = parseInt(value.value)
550
if(z>$B.min_int && z<$B.max_int){return z}
551
else{return value}
552
}
555
556
if(isinstance(value, _b_.str)) value=value.valueOf()
557
if(typeof value=="string") {
558
var _value=value.trim() // remove leading/trailing whitespace
559
if (_value.length == 2 && base==0 && (_value=='0b' || _value=='0o' || _value=='0x')) {
564
if (base == 0) {
565
if (_pre == '0B') base=2
566
if (_pre == '0O') base=8
567
if (_pre == '0X') base=16
568
}
569
if (_pre=='0B' || _pre=='0O' || _pre=='0X') {
571
}
572
}
573
var _digits=$valid_digits(base)
574
var _re=new RegExp('^[+-]?['+_digits+']+$', 'i')
583
var res=parseInt(_value, base)
584
if(res < $B.min_int || res > $B.max_int) return $B.LongInt(_value, base)
585
return res
588
if(isinstance(value,[_b_.bytes,_b_.bytearray])){
589
var _digits = $valid_digits(base)
590
for(var i=0;i<value.source.length;i++){
591
if(_digits.indexOf(String.fromCharCode(value.source[i]))==-1){
592
throw _b_.ValueError("invalid literal for int() with base "+
593
base +": "+_b_.repr(value))
594
}
595
}
596
return Number(parseInt(getattr(value,'decode')('latin-1'), base))
597
}
599
if(hasattr(value, '__int__')) return getattr(value,'__int__')()
600
if(hasattr(value, '__index__')) return getattr(value,'__index__')()
601
if(hasattr(value, '__trunc__')) {
602
var res = getattr(value,'__trunc__')(),
603
int_func = _b_.getattr(res, '__int__', null)
604
if(int_func===null){
605
throw TypeError('__trunc__ returned non-Integral (type '+
606
$B.get_class(res).__name__+')')
607
}
608
var res=int_func()
609
if(isinstance(res, int)){return res}
610
throw TypeError('__trunc__ returned non-Integral (type '+
611
$B.get_class(res).__name__+')')
612
}
614
throw _b_.TypeError("int() argument must be a string, a bytes-like "+
615
"object or a number, not '"+$B.get_class(value).__name__+"'")
616
}
617
int.$dict = $IntDict
618
int.__class__ = $B.$factory
619
$IntDict.$factory = int
620
625
// Boolean type
626
var $BoolDict = _b_.bool.$dict
627
628
$BoolDict.__add__ = function(self,other){
630
}
631
632
$BoolDict.__and__ = function(self, other){
633
return bool($IntDict.__and__(self, other))
634
}
635
636
$BoolDict.__eq__ = function(self,other){
642
}
643
644
$BoolDict.__ge__ = function(self,other){
645
return _b_.int.$dict.__ge__($BoolDict.__hash__(self),other)
646
}
647
648
$BoolDict.__gt__ = function(self,other){
649
return _b_.int.$dict.__gt__($BoolDict.__hash__(self),other)
650
}
651
652
$BoolDict.__hash__ = $BoolDict.__index__= $BoolDict.__int__=function(self) {
653
if(self.valueOf()) return 1
654
return 0
655
}
656
657
$BoolDict.__le__ = function(self,other){return !$BoolDict.__gt__(self,other)}
658
659
$BoolDict.__lshift__ = function(self,other){return self.valueOf() << other}
660
661
$BoolDict.__lt__ = function(self,other){return !$BoolDict.__ge__(self,other)}
662
663
$BoolDict.__mul__ = function(self,other){
665
}
666
667
$BoolDict.__neg__ = function(self){return -$B.int_or_bool(self)}
668
669
$BoolDict.__or__ = function(self, other){
670
return bool($IntDict.__or__(self, other))
671
}
672
673
$BoolDict.__pos__ = $B.int_or_bool
674
675
$BoolDict.__repr__ = $BoolDict.__str__ = function(self){
677
}
678
679
$BoolDict.__setattr__ = function(self, attr){
680
return no_set_attr($BoolDict, attr)
681
}
682
683
$BoolDict.__sub__ = function(self,other){
685
}
686
687
$BoolDict.__xor__ = function(self, other) {
688
return self.valueOf() != other.valueOf()
689
}
690
691
692
$BoolDict.__mro__ = [$IntDict, _b_.object.$dict]