Permalink
Sep 2, 2017
May 19, 2017
Dec 18, 2015
Dec 14, 2015
Jan 25, 2017
Jan 25, 2017
Jan 13, 2017
Jan 13, 2017
Jan 13, 2017
Jan 13, 2017
Jan 13, 2017
Jan 13, 2017
Newer
100644
690 lines (586 sloc)
21 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')}
271
return {__class__:cls.$dict}
272
}
273
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) {return $B.LongInt.$dict.__lt__(other, $B.LongInt(self))}
454
if(isinstance(other,_b_.bool)) {
455
return self.valueOf() > _b_.bool.$dict.__hash__(other)
456
}
457
if (hasattr(other, '__int__') || hasattr(other, '__index__')) {
458
return $IntDict.__gt__(self, $B.$GetInt(other))
459
}
461
// See if other has the opposite operator, eg < for >
462
var inv_op = getattr(other, '__lt__', null)
467
}
468
$comp_func += '' // source codevar $comps = {'>':'gt','>=':'ge','<':'lt','<=':'le'}
475
}
476
477
// add "reflected" methods
478
$B.make_rmethods($IntDict)
479
480
var $valid_digits=function(base) {
481
var digits=''
482
if (base === 0) return '0'
483
if (base < 10) {
484
for (var i=0; i < base; i++) digits+=String.fromCharCode(i+48)
485
return digits
486
}
487
488
var digits='0123456789'
489
// A = 65 (10 + 55)
490
for (var i=10; i < base; i++) digits+=String.fromCharCode(i+55)
491
return digits
492
}
493
502
if(base!==undefined){
503
if(!isinstance(value,[_b_.str,_b_.bytes,_b_.bytearray])){
504
throw TypeError("int() can't convert non-string with explicit base")
505
}
506
}
507
508
if(isinstance(value,_b_.complex)){
509
throw TypeError("can't convert complex to int")
510
}
511
518
if(value<$B.min_int || value>$B.max_int){
519
return $B.LongInt.$dict.$from_float(value)
520
}
524
if (!(base >=2 && base <= 36)) {
525
// throw error (base must be 0, or 2-36)
526
if (base != 0) throw _b_.ValueError("invalid base")
527
}
528
529
if (typeof value == 'number'){
530
531
if(base==10){
532
if(value < $B.min_int || value > $B.max_int) return $B.LongInt(value)
533
return value
534
}else if(value.toString().search('e')>-1){
535
// can't convert to another base if value is too big
536
throw _b_.OverflowError("can't convert to base "+base)
537
}else{
538
var res=parseInt(value, base)
539
if(res < $B.min_int || res > $B.max_int) return $B.LongInt(value,base)
540
return res
546
if(value.__class__===$B.LongInt.$dict){
547
var z = parseInt(value.value)
548
if(z>$B.min_int && z<$B.max_int){return z}
549
else{return value}
550
}
553
554
if(isinstance(value, _b_.str)) value=value.valueOf()
555
if(typeof value=="string") {
556
var _value=value.trim() // remove leading/trailing whitespace
557
if (_value.length == 2 && base==0 && (_value=='0b' || _value=='0o' || _value=='0x')) {
562
if (base == 0) {
563
if (_pre == '0B') base=2
564
if (_pre == '0O') base=8
565
if (_pre == '0X') base=16
566
}
567
if (_pre=='0B' || _pre=='0O' || _pre=='0X') {
569
}
570
}
571
var _digits=$valid_digits(base)
572
var _re=new RegExp('^[+-]?['+_digits+']+$', 'i')
581
var res=parseInt(_value, base)
582
if(res < $B.min_int || res > $B.max_int) return $B.LongInt(_value, base)
583
return res
586
if(isinstance(value,[_b_.bytes,_b_.bytearray])){
587
var _digits = $valid_digits(base)
588
for(var i=0;i<value.source.length;i++){
589
if(_digits.indexOf(String.fromCharCode(value.source[i]))==-1){
590
throw _b_.ValueError("invalid literal for int() with base "+
591
base +": "+_b_.repr(value))
592
}
593
}
594
return Number(parseInt(getattr(value,'decode')('latin-1'), base))
595
}
597
if(hasattr(value, '__int__')) return getattr(value,'__int__')()
598
if(hasattr(value, '__index__')) return getattr(value,'__index__')()
599
if(hasattr(value, '__trunc__')) {
600
var res = getattr(value,'__trunc__')(),
601
int_func = _b_.getattr(res, '__int__', null)
602
if(int_func===null){
603
throw TypeError('__trunc__ returned non-Integral (type '+
604
$B.get_class(res).__name__+')')
605
}
606
var res=int_func()
607
if(isinstance(res, int)){return res}
608
throw TypeError('__trunc__ returned non-Integral (type '+
609
$B.get_class(res).__name__+')')
610
}
614
}
615
int.$dict = $IntDict
616
int.__class__ = $B.$factory
617
$IntDict.$factory = int
618
619
_b_.int = int
620
621
// Boolean type
622
var $BoolDict = _b_.bool.$dict
623
624
$BoolDict.__add__ = function(self,other){
626
}
627
628
$BoolDict.__and__ = function(self, other){
629
return bool($IntDict.__and__(self, other))
630
}
631
632
$BoolDict.__eq__ = function(self,other){
638
}
639
640
$BoolDict.__ge__ = function(self,other){
641
return _b_.int.$dict.__ge__($BoolDict.__hash__(self),other)
642
}
643
644
$BoolDict.__gt__ = function(self,other){
645
return _b_.int.$dict.__gt__($BoolDict.__hash__(self),other)
646
}
647
648
$BoolDict.__hash__ = $BoolDict.__index__= $BoolDict.__int__=function(self) {
649
if(self.valueOf()) return 1
650
return 0
651
}
652
653
$BoolDict.__le__ = function(self,other){return !$BoolDict.__gt__(self,other)}
654
655
$BoolDict.__lshift__ = function(self,other){return self.valueOf() << other}
656
657
$BoolDict.__lt__ = function(self,other){return !$BoolDict.__ge__(self,other)}
658
659
$BoolDict.__mul__ = function(self,other){
661
}
662
663
$BoolDict.__neg__ = function(self){return -$B.int_or_bool(self)}
664
665
$BoolDict.__or__ = function(self, other){
666
return bool($IntDict.__or__(self, other))
667
}
668
669
$BoolDict.__pos__ = $B.int_or_bool
670
671
$BoolDict.__repr__ = $BoolDict.__str__ = function(self){
673
}
674
675
$BoolDict.__setattr__ = function(self, attr){
676
return no_set_attr($BoolDict, attr)
677
}
678
679
$BoolDict.__sub__ = function(self,other){
681
}
682
683
$BoolDict.__xor__ = function(self, other) {
684
return self.valueOf() != other.valueOf()
685
}
686
687
688
$BoolDict.__mro__ = [$IntDict, _b_.object.$dict]