Permalink
Nov 20, 2016
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
687 lines (584 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
var $=$B.args("from_bytes", 3,
27
{bytes:null, byteorder:null, signed:null}, ['bytes', 'byteorder', 'signed'],
28
arguments, {signed:False}, null, null)
33
var _bytes, _len
34
if (isinstance(x, [_b_.list, _b_.tuple])) {
35
_bytes=x
36
_len=len(x)
40
} else {
41
_b_.TypeError("Error! " + _b_.type(x) + " is not supported in int.from_bytes. fix me!")
44
switch(byteorder) {
45
case 'big':
46
var num = _bytes[_len - 1];
47
var _mult=256
48
for (var i = (_len - 2); i >= 0; i--) {
49
// For operations, use the functions that can take or return
50
// big integers
51
num = $B.add($B.mul(_mult, _bytes[i]), num)
52
_mult = $B.mul(_mult,256)
57
case 'little':
58
var num = _bytes[0]
59
if (num >= 128) num = num - 256
60
var _mult=256
61
for (var i = 1; i < _len; i++) {
68
}
69
70
throw _b_.ValueError("byteorder must be either 'little' or 'big'");
71
}
72
73
$IntDict.to_bytes = function(length, byteorder, star) {
74
//var len = x.length
75
throw _b_.NotImplementedError("int.to_bytes is not implemented yet")
76
}
77
78
79
//$IntDict.__and__ = function(self,other){return self & other} // bitwise AND
80
92
$IntDict.__eq__ = function(self,other){
93
// compare object "self" to class "int"
94
if(other===undefined) return self===int
95
if(isinstance(other,int)) return self.valueOf()==other.valueOf()
97
if(isinstance(other,_b_.complex)){
98
if (other.imag != 0) return False
99
return self.valueOf() == other.real
100
}
107
function preformat(self, fmt){
108
if(fmt.empty){return _b_.str(self)}
109
if(fmt.type && 'bcdoxXn'.indexOf(fmt.type)==-1){
110
throw _b_.ValueError("Unknown format code '"+fmt.type+
111
"' for object of type 'int'")
112
}
113
114
switch(fmt.type){
115
case undefined:
116
case 'd':
117
return self.toString()
118
case 'b':
138
if(fmt.type && 'eEfFgG%'.indexOf(fmt.type)!=-1){
139
// Call __format__ on float(self)
140
return _b_.float.$dict.__format__(self, format_spec)
141
}
145
var sign = res[0]=='-' ? '-' : '',
146
rest = res.substr(sign.length),
147
len = rest.length,
148
nb = Math.ceil(rest.length/3),
149
chunks = []
161
$IntDict.__floordiv__ = function(self,other){
162
if(isinstance(other,int)){
163
if(other==0) throw ZeroDivisionError('division by zero')
164
return Math.floor(self/other)
165
}
166
if(isinstance(other,_b_.float)){
167
if(!other.valueOf()) throw ZeroDivisionError('division by zero')
168
return Math.floor(self/other)
169
}
170
if(hasattr(other,'__rfloordiv__')){
171
return getattr(other,'__rfloordiv__')(self)
172
}
173
$err("//",other)
174
}
175
176
$IntDict.__hash__ = function(self){
177
if (self === undefined) {
178
return $IntDict.__hashvalue__ || $B.$py_next_hash-- // for hash of int type (not instance of int)
179
}
180
181
return self.valueOf()
182
}
183
184
//$IntDict.__ior__ = function(self,other){return self | other} // bitwise OR
185
186
$IntDict.__index__ = function(self){return self}
187
188
$IntDict.__init__ = function(self,value){
189
if(value===undefined){value=0}
190
self.toString = function(){return value}
191
//self.valueOf = function(){return value}
193
}
194
195
$IntDict.__int__ = function(self){return self}
196
197
$IntDict.__invert__ = function(self){return ~self}
198
199
// bitwise left shift
200
$IntDict.__lshift__ = function(self,other){
201
if(isinstance(other, int)){
202
return int($B.LongInt.$dict.__lshift__($B.LongInt(self), $B.LongInt(other)))
203
}
204
var rlshift = getattr(other, '__rlshift__', null)
205
if(rlshift!==null){return rlshift(self)}
206
$err('<<', other)
207
}
208
209
$IntDict.__mod__ = function(self,other) {
210
// can't use Javascript % because it works differently for negative numbers
211
if(isinstance(other,_b_.tuple) && other.length==1) other=other[0]
212
if(isinstance(other,[int, _b_.float, bool])){
213
if(other===false){other=0}else if(other===true){other=1}
214
if(other==0){throw _b_.ZeroDivisionError(
215
"integer division or modulo by zero")}
216
return (self%other+other)%other
217
}
218
if(hasattr(other,'__rmod__')) return getattr(other,'__rmod__')(self)
219
$err('%',other)
220
}
221
227
228
// this will be quick check, so lets do it early.
229
if(typeof other==="string") {
230
return other.repeat(val)
231
}
232
233
if(isinstance(other,int)){
234
var res = self*other
235
if(res>$B.min_int && res<$B.max_int){return res}
247
return _b_.complex($IntDict.__mul__(self, other.real),
248
$IntDict.__mul__(self, other.imag))
249
}
250
if(isinstance(other,[_b_.list,_b_.tuple])){
251
var res = []
252
// make temporary copy of list
253
var $temp = other.slice(0,other.length)
254
for(var i=0;i<val;i++) res=res.concat($temp)
255
if(isinstance(other,_b_.tuple)) res=_b_.tuple(res)
256
return res
257
}
258
if(hasattr(other,'__rmul__')) return getattr(other,'__rmul__')(self)
259
$err("*",other)
260
}
261
262
$IntDict.__name__ = 'int'
263
264
$IntDict.__neg__ = function(self){return -self}
265
266
$IntDict.__new__ = function(cls){
267
if(cls===undefined){throw _b_.TypeError('int.__new__(): not enough arguments')}
268
return {__class__:cls.$dict}
269
}
270
275
switch(other.valueOf()) {
276
case 0:
277
return int(1)
278
case 1:
279
return int(self.valueOf())
280
}
281
if(z !== undefined && z !== null){
282
// If z is provided, the algorithm is faster than computing
283
// self ** other then applying the modulo z
284
var res = (self % z + z) % z
285
for(var i=1; i<other; i++){
286
res *= self
287
res = (res % z + z) % z
288
}
289
return res
290
}
291
var res = Math.pow(self.valueOf(),other.valueOf())
292
if(res>$B.min_int && res<$B.max_int){return res}
300
if(self>=0){return new Number(Math.pow(self, other.valueOf()))}
301
else{
302
// use complex power
303
return _b_.complex.$dict.__pow__(_b_.complex(self, 0), other)
304
}
309
}
310
if(hasattr(other,'__rpow__')) return getattr(other,'__rpow__')(self)
311
$err("**",other)
312
}
313
314
$IntDict.__repr__ = function(self){
315
if(self===int) return "<class 'int'>"
316
return self.toString()
317
}
318
319
// bitwise right shift
320
$IntDict.__rshift__ = function(self,other){
321
if(isinstance(other, int)){
322
return int($B.LongInt.$dict.__rshift__($B.LongInt(self), $B.LongInt(other)))
323
}
324
var rrshift = getattr(other, '__rrshift__', null)
325
if(rrshift!==null){return rrshift(self)}
326
$err('>>', other)
327
}
330
if(typeof self=="number"){
331
if($IntDict[attr]===undefined){
332
throw _b_.AttributeError("'int' object has no attribute '"+attr+"'")
333
}else{
334
throw _b_.AttributeError("'int' object attribute '"+attr+"' is read-only")
335
}
340
}
341
342
$IntDict.__str__ = $IntDict.__repr__
343
344
$IntDict.__truediv__ = function(self,other){
345
if(isinstance(other,int)){
346
if(other==0) throw ZeroDivisionError('division by zero')
347
if(other.__class__==$B.LongInt.$dict){return new Number(self/parseInt(other.value))}
351
if(!other.valueOf()) throw ZeroDivisionError('division by zero')
352
return new Number(self/other)
353
}
354
if(isinstance(other,_b_.complex)){
355
var cmod = other.real*other.real+other.imag*other.imag
356
if(cmod==0) throw ZeroDivisionError('division by zero')
357
return _b_.complex(self*other.real/cmod,-self*other.imag/cmod)
358
}
359
if(hasattr(other,'__rtruediv__')) return getattr(other,'__rtruediv__')(self)
360
$err("/",other)
361
}
362
363
//$IntDict.__xor__ = function(self,other){return self ^ other} // bitwise XOR
364
365
$IntDict.bit_length = function(self){
366
s = bin(self)
367
s = getattr(s,'lstrip')('-0b') // remove leading zeros and minus sign
368
return s.length // len('100101') --> 6
369
}
370
372
$IntDict.numerator = function(self){return self}
373
$IntDict.denominator = function(self){return int(1)}
374
$IntDict.imag = function(self){return int(0)}
375
$IntDict.real = function(self){return self}
376
384
if(other.__class__===$B.LongInt.$dict){
385
return $B.LongInt.$dict.__sub__($B.LongInt(self), $B.LongInt(other))
386
}
387
if (self > $B.max_int32 || self < $B.min_int32 ||
388
other > $B.max_int32 || other < $B.min_int32) {
389
return $B.LongInt.$dict.__sub__($B.LongInt(self), $B.LongInt(other))
390
}
391
return self-other
393
if(isinstance(other,_b_.bool)) return self-other
394
if(hasattr(other,'__rsub__')) return getattr(other,'__rsub__')(self)
395
$err("-",other)
396
}
397
398
$op_func += '' // source code
400
for(var $op in $ops){
401
var opf = $op_func.replace(/-/gm,$op)
402
opf = opf.replace(new RegExp('sub','gm'),$ops[$op])
403
eval('$IntDict.__'+$ops[$op]+'__ = '+opf)
404
}
405
406
// code for + and -
407
var $op_func = function(self,other){
408
if(isinstance(other,int)){
409
if(typeof other=='number'){
410
var res = self.valueOf()-other.valueOf()
411
if(res>=$B.min_int && res<=$B.max_int){return res}
412
else{return $B.LongInt.$dict.__sub__($B.LongInt(self),
413
$B.LongInt(other))}
416
}else{
417
return $B.LongInt.$dict.__sub__($B.LongInt(self),
418
$B.LongInt(other))
419
}
423
}
424
if(isinstance(other,_b_.complex)){
425
return _b_.complex(self-other.real,-other.imag)
426
}
427
if(isinstance(other,_b_.bool)){
428
var bool_value=0;
429
if(other.valueOf()) bool_value=1;
431
}
432
if(isinstance(other,_b_.complex)){
433
return _b_.complex(self.valueOf() - other.real, other.imag)
434
}
435
if(hasattr(other,'__rsub__')) return getattr(other,'__rsub__')(self)
436
throw $err('-',other)
437
}
438
$op_func += '' // source code
439
var $ops = {'+':'add','-':'sub'}
440
for(var $op in $ops){
441
var opf = $op_func.replace(/-/gm,$op)
442
opf = opf.replace(new RegExp('sub','gm'),$ops[$op])
443
eval('$IntDict.__'+$ops[$op]+'__ = '+opf)
444
}
445
446
// comparison methods
447
var $comp_func = function(self,other){
448
if (other.__class__ === $B.LongInt.$dict) {return $B.LongInt.$dict.__lt__(other, $B.LongInt(self))}
451
if(isinstance(other,_b_.bool)) {
452
return self.valueOf() > _b_.bool.$dict.__hash__(other)
453
}
454
if (hasattr(other, '__int__') || hasattr(other, '__index__')) {
455
return $IntDict.__gt__(self, $B.$GetInt(other))
456
}
458
// See if other has the opposite operator, eg < for >
459
var inv_op = getattr(other, '__lt__', null)
464
}
465
$comp_func += '' // source codevar $comps = {'>':'gt','>=':'ge','<':'lt','<=':'le'}
472
}
473
474
// add "reflected" methods
475
$B.make_rmethods($IntDict)
476
477
var $valid_digits=function(base) {
478
var digits=''
479
if (base === 0) return '0'
480
if (base < 10) {
481
for (var i=0; i < base; i++) digits+=String.fromCharCode(i+48)
482
return digits
483
}
484
485
var digits='0123456789'
486
// A = 65 (10 + 55)
487
for (var i=10; i < base; i++) digits+=String.fromCharCode(i+55)
488
return digits
489
}
490
492
// int() with no argument returns 0
493
if(value===undefined){return 0}
494
495
// int() of an integer returns the integer if base is undefined
496
if(typeof value=='number' &&
497
(base===undefined || base==10)){return parseInt(value)}
498
499
if(base!==undefined){
500
if(!isinstance(value,[_b_.str,_b_.bytes,_b_.bytearray])){
501
throw TypeError("int() can't convert non-string with explicit base")
502
}
503
}
504
505
if(isinstance(value,_b_.complex)){
506
throw TypeError("can't convert complex to int")
507
}
508
515
if(value<$B.min_int || value>$B.max_int){
516
return $B.LongInt.$dict.$from_float(value)
517
}
521
if (!(base >=2 && base <= 36)) {
522
// throw error (base must be 0, or 2-36)
523
if (base != 0) throw _b_.ValueError("invalid base")
524
}
525
526
if (typeof value == 'number'){
527
528
if(base==10){
529
if(value < $B.min_int || value > $B.max_int) return $B.LongInt(value)
530
return value
531
}else if(value.toString().search('e')>-1){
532
// can't convert to another base if value is too big
533
throw _b_.OverflowError("can't convert to base "+base)
534
}else{
535
var res=parseInt(value, base)
536
if(res < $B.min_int || res > $B.max_int) return $B.LongInt(value,base)
537
return res
543
if(value.__class__===$B.LongInt.$dict){
544
var z = parseInt(value.value)
545
if(z>$B.min_int && z<$B.max_int){return z}
546
else{return value}
547
}
550
551
if(isinstance(value, _b_.str)) value=value.valueOf()
552
if(typeof value=="string") {
553
var _value=value.trim() // remove leading/trailing whitespace
554
if (_value.length == 2 && base==0 && (_value=='0b' || _value=='0o' || _value=='0x')) {
559
if (base == 0) {
560
if (_pre == '0B') base=2
561
if (_pre == '0O') base=8
562
if (_pre == '0X') base=16
563
}
564
if (_pre=='0B' || _pre=='0O' || _pre=='0X') {
566
}
567
}
568
var _digits=$valid_digits(base)
569
var _re=new RegExp('^[+-]?['+_digits+']+$', 'i')
578
var res=parseInt(_value, base)
579
if(res < $B.min_int || res > $B.max_int) return $B.LongInt(_value, base)
580
return res
583
if(isinstance(value,[_b_.bytes,_b_.bytearray])){
584
var _digits = $valid_digits(base)
585
for(var i=0;i<value.source.length;i++){
586
if(_digits.indexOf(String.fromCharCode(value.source[i]))==-1){
587
throw _b_.ValueError("invalid literal for int() with base "+
588
base +": "+_b_.repr(value))
589
}
590
}
591
return Number(parseInt(getattr(value,'decode')('latin-1'), base))
592
}
594
if(hasattr(value, '__int__')) return getattr(value,'__int__')()
595
if(hasattr(value, '__index__')) return getattr(value,'__index__')()
596
if(hasattr(value, '__trunc__')) {
597
var res = getattr(value,'__trunc__')(),
598
int_func = _b_.getattr(res, '__int__', null)
599
if(int_func===null){
600
throw TypeError('__trunc__ returned non-Integral (type '+
601
$B.get_class(res).__name__+')')
602
}
603
var res=int_func()
604
if(isinstance(res, int)){return res}
605
throw TypeError('__trunc__ returned non-Integral (type '+
606
$B.get_class(res).__name__+')')
607
}
611
}
612
int.$dict = $IntDict
613
int.__class__ = $B.$factory
614
$IntDict.$factory = int
615
616
_b_.int = int
617
618
// Boolean type
619
var $BoolDict = _b_.bool.$dict
620
621
$BoolDict.__add__ = function(self,other){
623
}
624
625
$BoolDict.__and__ = function(self, other){
626
return bool($IntDict.__and__(self, other))
627
}
628
629
$BoolDict.__eq__ = function(self,other){
635
}
636
637
$BoolDict.__ge__ = function(self,other){
638
return _b_.int.$dict.__ge__($BoolDict.__hash__(self),other)
639
}
640
641
$BoolDict.__gt__ = function(self,other){
642
return _b_.int.$dict.__gt__($BoolDict.__hash__(self),other)
643
}
644
645
$BoolDict.__hash__ = $BoolDict.__index__= $BoolDict.__int__=function(self) {
646
if(self.valueOf()) return 1
647
return 0
648
}
649
650
$BoolDict.__le__ = function(self,other){return !$BoolDict.__gt__(self,other)}
651
652
$BoolDict.__lshift__ = function(self,other){return self.valueOf() << other}
653
654
$BoolDict.__lt__ = function(self,other){return !$BoolDict.__ge__(self,other)}
655
656
$BoolDict.__mul__ = function(self,other){
658
}
659
660
$BoolDict.__neg__ = function(self){return -$B.int_or_bool(self)}
661
662
$BoolDict.__or__ = function(self, other){
663
return bool($IntDict.__or__(self, other))
664
}
665
666
$BoolDict.__pos__ = $B.int_or_bool
667
668
$BoolDict.__repr__ = $BoolDict.__str__ = function(self){
670
}
671
672
$BoolDict.__setattr__ = function(self, attr){
673
return no_set_attr($BoolDict, attr)
674
}
675
676
$BoolDict.__sub__ = function(self,other){
678
}
679
680
$BoolDict.__xor__ = function(self, other) {
681
return self.valueOf() != other.valueOf()
682
}
683
684
685
$BoolDict.__mro__ = [$IntDict, _b_.object.$dict]