Permalink
Nov 20, 2016
Dec 18, 2015
Dec 18, 2015
Dec 14, 2015
Feb 23, 2016
Feb 23, 2016
Newer
100644
608 lines (525 sloc)
19 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
}
284
else{
285
return int($B.LongInt.$dict.__pow__($B.LongInt(self),
286
$B.LongInt(other)))}
289
if(self>=0){return new Number(Math.pow(self, other.valueOf()))}
290
else{
291
// use complex power
292
return _b_.complex.$dict.__pow__(_b_.complex(self, 0), other)
293
}
298
}
299
if(hasattr(other,'__rpow__')) return getattr(other,'__rpow__')(self)
300
$err("**",other)
301
}
302
303
$IntDict.__repr__ = function(self){
304
if(self===int) return "<class 'int'>"
305
return self.toString()
306
}
307
308
// bitwise right shift
309
$IntDict.__rshift__ = function(self,other){
310
if(isinstance(other, int)){
311
return int($B.LongInt.$dict.__rshift__($B.LongInt(self), $B.LongInt(other)))
312
}
313
var rrshift = getattr(other, '__rrshift__', null)
314
if(rrshift!==null){return rrshift(self)}
315
$err('>>', other)
316
}
319
if(typeof self=="number"){
320
if($IntDict[attr]===undefined){
321
throw _b_.AttributeError("'int' object has no attribute '"+attr+"'")
322
}else{
323
throw _b_.AttributeError("'int' object attribute '"+attr+"' is read-only")
324
}
329
}
330
331
$IntDict.__str__ = $IntDict.__repr__
332
333
$IntDict.__truediv__ = function(self,other){
334
if(isinstance(other,int)){
335
if(other==0) throw ZeroDivisionError('division by zero')
336
if(other.__class__==$B.LongInt.$dict){return new Number(self/parseInt(other.value))}
340
if(!other.valueOf()) throw ZeroDivisionError('division by zero')
341
return new Number(self/other)
342
}
343
if(isinstance(other,_b_.complex)){
344
var cmod = other.real*other.real+other.imag*other.imag
345
if(cmod==0) throw ZeroDivisionError('division by zero')
346
return _b_.complex(self*other.real/cmod,-self*other.imag/cmod)
347
}
348
if(hasattr(other,'__rtruediv__')) return getattr(other,'__rtruediv__')(self)
349
$err("/",other)
350
}
351
352
//$IntDict.__xor__ = function(self,other){return self ^ other} // bitwise XOR
353
354
$IntDict.bit_length = function(self){
355
s = bin(self)
356
s = getattr(s,'lstrip')('-0b') // remove leading zeros and minus sign
357
return s.length // len('100101') --> 6
358
}
359
361
$IntDict.numerator = function(self){return self}
362
$IntDict.denominator = function(self){return int(1)}
363
$IntDict.imag = function(self){return int(0)}
364
$IntDict.real = function(self){return self}
365
373
if(other.__class__===$B.LongInt.$dict){
374
return $B.LongInt.$dict.__sub__($B.LongInt(self), $B.LongInt(other))
375
}
376
if (self > $B.max_int32 || self < $B.min_int32 ||
377
other > $B.max_int32 || other < $B.min_int32) {
378
return $B.LongInt.$dict.__sub__($B.LongInt(self), $B.LongInt(other))
379
}
380
return self-other
382
if(isinstance(other,_b_.bool)) return self-other
383
if(hasattr(other,'__rsub__')) return getattr(other,'__rsub__')(self)
384
$err("-",other)
385
}
386
387
$op_func += '' // source code
389
for(var $op in $ops){
390
var opf = $op_func.replace(/-/gm,$op)
391
opf = opf.replace(new RegExp('sub','gm'),$ops[$op])
392
eval('$IntDict.__'+$ops[$op]+'__ = '+opf)
393
}
394
395
// code for + and -
396
var $op_func = function(self,other){
397
if(isinstance(other,int)){
398
if(typeof other=='number'){
399
var res = self.valueOf()-other.valueOf()
400
if(res>=$B.min_int && res<=$B.max_int){return res}
401
else{return $B.LongInt.$dict.__sub__($B.LongInt(self),
402
$B.LongInt(other))}
405
}else{
406
return $B.LongInt.$dict.__sub__($B.LongInt(self),
407
$B.LongInt(other))
408
}
412
}
413
if(isinstance(other,_b_.complex)){
414
return _b_.complex(self-other.real,-other.imag)
415
}
416
if(isinstance(other,_b_.bool)){
417
var bool_value=0;
418
if(other.valueOf()) bool_value=1;
420
}
421
if(isinstance(other,_b_.complex)){
422
return _b_.complex(self.valueOf() - other.real, other.imag)
423
}
424
if(hasattr(other,'__rsub__')) return getattr(other,'__rsub__')(self)
425
throw $err('-',other)
426
}
427
$op_func += '' // source code
428
var $ops = {'+':'add','-':'sub'}
429
for(var $op in $ops){
430
var opf = $op_func.replace(/-/gm,$op)
431
opf = opf.replace(new RegExp('sub','gm'),$ops[$op])
432
eval('$IntDict.__'+$ops[$op]+'__ = '+opf)
433
}
434
435
// comparison methods
436
var $comp_func = function(self,other){
437
if (other.__class__ === $B.LongInt.$dict) return $B.LongInt.$dict.__gt__($B.LongInt(self), other)
440
if(isinstance(other,_b_.bool)) {
441
return self.valueOf() > _b_.bool.$dict.__hash__(other)
442
}
443
if (hasattr(other, '__int__') || hasattr(other, '__index__')) {
444
return $IntDict.__gt__(self, $B.$GetInt(other))
445
}
446
447
// See if other has the opposite operator, eg <= for >
448
var inv_op = getattr(other, '__le__', null)
449
if(inv_op !== null){return inv_op(self)}
450
453
}
454
$comp_func += '' // source codevar $comps = {'>':'gt','>=':'ge','<':'lt','<=':'le'}
458
$comp_func.replace(/>/gm,$op).
459
replace(/__gt__/gm,'__'+$B.$comps[$op]+'__').
460
replace(/__le__/, '__'+$B.$inv_comps[$op]+'__'))
461
}
462
463
// add "reflected" methods
464
$B.make_rmethods($IntDict)
465
466
var $valid_digits=function(base) {
467
var digits=''
468
if (base === 0) return '0'
469
if (base < 10) {
470
for (var i=0; i < base; i++) digits+=String.fromCharCode(i+48)
471
return digits
472
}
473
474
var digits='0123456789'
475
// A = 65 (10 + 55)
476
for (var i=10; i < base; i++) digits+=String.fromCharCode(i+55)
477
return digits
478
}
479
481
// int() with no argument returns 0
482
if(value===undefined){return 0}
483
484
// int() of an integer returns the integer if base is undefined
485
if(typeof value=='number' &&
486
(base===undefined || base==10)){return parseInt(value)}
487
488
if(base!==undefined){
489
if(!isinstance(value,[_b_.str,_b_.bytes,_b_.bytearray])){
490
throw TypeError("int() can't convert non-string with explicit base")
491
}
492
}
493
494
if(isinstance(value,_b_.complex)){
495
throw TypeError("can't convert complex to int")
496
}
497
504
if(value<$B.min_int || value>$B.max_int){
505
return $B.LongInt.$dict.$from_float(value)
506
}
510
if (!(base >=2 && base <= 36)) {
511
// throw error (base must be 0, or 2-36)
512
if (base != 0) throw _b_.ValueError("invalid base")
513
}
514
515
if (typeof value == 'number'){
516
517
if(base==10){
518
if(value < $B.min_int || value > $B.max_int) return $B.LongInt(value)
519
return value
520
}else if(value.toString().search('e')>-1){
521
// can't convert to another base if value is too big
522
throw _b_.OverflowError("can't convert to base "+base)
523
}else{
524
var res=parseInt(value, base)
525
if(res < $B.min_int || res > $B.max_int) return $B.LongInt(value,base)
526
return res
532
if(value.__class__===$B.LongInt.$dict){
533
var z = parseInt(value.value)
534
if(z>$B.min_int && z<$B.max_int){return z}
535
else{return value}
536
}
539
540
if(isinstance(value, _b_.str)) value=value.valueOf()
541
if(typeof value=="string") {
542
var _value=value.trim() // remove leading/trailing whitespace
543
if (_value.length == 2 && base==0 && (_value=='0b' || _value=='0o' || _value=='0x')) {
548
if (base == 0) {
549
if (_pre == '0B') base=2
550
if (_pre == '0O') base=8
551
if (_pre == '0X') base=16
552
}
553
if (_pre=='0B' || _pre=='0O' || _pre=='0X') {
555
}
556
}
557
var _digits=$valid_digits(base)
558
var _re=new RegExp('^[+-]?['+_digits+']+$', 'i')
567
var res=parseInt(_value, base)
568
if(res < $B.min_int || res > $B.max_int) return $B.LongInt(_value, base)
569
return res
572
if(isinstance(value,[_b_.bytes,_b_.bytearray])){
573
var _digits = $valid_digits(base)
574
for(var i=0;i<value.source.length;i++){
575
if(_digits.indexOf(String.fromCharCode(value.source[i]))==-1){
576
throw _b_.ValueError("invalid literal for int() with base "+
577
base +": "+_b_.repr(value))
578
}
579
}
580
return Number(parseInt(getattr(value,'decode')('latin-1'), base))
581
}
583
if(hasattr(value, '__int__')) return getattr(value,'__int__')()
584
if(hasattr(value, '__index__')) return getattr(value,'__index__')()
585
if(hasattr(value, '__trunc__')) {
586
var res = getattr(value,'__trunc__')(),
587
int_func = _b_.getattr(res, '__int__', null)
588
if(int_func===null){
589
throw TypeError('__trunc__ returned non-Integral (type '+
590
$B.get_class(res).__name__+')')
591
}
592
var res=int_func()
593
if(isinstance(res, int)){return res}
594
throw TypeError('__trunc__ returned non-Integral (type '+
595
$B.get_class(res).__name__+')')
596
}
600
}
601
int.$dict = $IntDict
602
int.__class__ = $B.$factory
603
$IntDict.$factory = int
604
605
_b_.int = int
606