Permalink
Dec 18, 2015
Dec 18, 2015
Dec 14, 2015
Newer
100644
591 lines (510 sloc)
18.4 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
}
142
fmt.align = fmt.align || '>'
143
var res = preformat(self, fmt)
144
if(fmt.comma){
145
var len = res.length, nb = Math.ceil(res.length/3), chunks = []
146
for(var i=0;i<nb;i++){
147
chunks.push(res.substring(len-3*i-3, len-3*i))
148
}
149
chunks.reverse()
150
res = chunks.join(',')
151
}
152
return $B.format_width(res, fmt)
157
$IntDict.__floordiv__ = function(self,other){
158
if(isinstance(other,int)){
159
if(other==0) throw ZeroDivisionError('division by zero')
160
return Math.floor(self/other)
161
}
162
if(isinstance(other,_b_.float)){
163
if(!other.valueOf()) throw ZeroDivisionError('division by zero')
164
return Math.floor(self/other)
165
}
166
if(hasattr(other,'__rfloordiv__')){
167
return getattr(other,'__rfloordiv__')(self)
168
}
169
$err("//",other)
170
}
171
172
$IntDict.__hash__ = function(self){
173
if (self === undefined) {
174
return $IntDict.__hashvalue__ || $B.$py_next_hash-- // for hash of int type (not instance of int)
175
}
176
177
return self.valueOf()
178
}
179
180
//$IntDict.__ior__ = function(self,other){return self | other} // bitwise OR
181
182
$IntDict.__index__ = function(self){return self}
183
184
$IntDict.__init__ = function(self,value){
185
if(value===undefined){value=0}
186
self.toString = function(){return value}
187
//self.valueOf = function(){return value}
189
}
190
191
$IntDict.__int__ = function(self){return self}
192
193
$IntDict.__invert__ = function(self){return ~self}
194
195
// bitwise left shift
196
$IntDict.__lshift__ = function(self,other){
197
if(isinstance(other, int)){
198
return int($B.LongInt.$dict.__lshift__($B.LongInt(self), $B.LongInt(other)))
199
}
200
var rlshift = getattr(other, '__rlshift__', null)
201
if(rlshift!==null){return rlshift(self)}
202
$err('<<', other)
203
}
204
205
$IntDict.__mod__ = function(self,other) {
206
// can't use Javascript % because it works differently for negative numbers
207
if(isinstance(other,_b_.tuple) && other.length==1) other=other[0]
208
if(isinstance(other,[int, _b_.float, bool])){
209
if(other===false){other=0}else if(other===true){other=1}
210
if(other==0){throw _b_.ZeroDivisionError(
211
"integer division or modulo by zero")}
212
return (self%other+other)%other
213
}
214
if(hasattr(other,'__rmod__')) return getattr(other,'__rmod__')(self)
215
$err('%',other)
216
}
217
218
$IntDict.__mro__ = [$IntDict,$ObjectDict]
219
220
$IntDict.__mul__ = function(self,other){
223
224
// this will be quick check, so lets do it early.
225
if(typeof other==="string") {
226
return other.repeat(val)
227
}
228
229
if(isinstance(other,int)){
230
var res = self*other
231
if(res>$B.min_int && res<$B.max_int){return res}
243
return _b_.complex($IntDict.__mul__(self, other.real),
244
$IntDict.__mul__(self, other.imag))
245
}
246
if(isinstance(other,[_b_.list,_b_.tuple])){
247
var res = []
248
// make temporary copy of list
249
var $temp = other.slice(0,other.length)
250
for(var i=0;i<val;i++) res=res.concat($temp)
251
if(isinstance(other,_b_.tuple)) res=_b_.tuple(res)
252
return res
253
}
254
if(hasattr(other,'__rmul__')) return getattr(other,'__rmul__')(self)
255
$err("*",other)
256
}
257
258
$IntDict.__name__ = 'int'
259
260
$IntDict.__neg__ = function(self){return -self}
261
262
$IntDict.__new__ = function(cls){
263
if(cls===undefined){throw _b_.TypeError('int.__new__(): not enough arguments')}
264
return {__class__:cls.$dict}
265
}
266
271
switch(other.valueOf()) {
272
case 0:
273
return int(1)
274
case 1:
275
return int(self.valueOf())
276
}
280
else{
281
return int($B.LongInt.$dict.__pow__($B.LongInt(self),
282
$B.LongInt(other)))}
285
if(self>=0){return new Number(Math.pow(self, other.valueOf()))}
286
else{
287
// use complex power
288
return _b_.complex.$dict.__pow__(_b_.complex(self, 0), other)
289
}
290
}
291
if(hasattr(other,'__rpow__')) return getattr(other,'__rpow__')(self)
292
$err("**",other)
293
}
294
295
$IntDict.__repr__ = function(self){
296
if(self===int) return "<class 'int'>"
297
return self.toString()
298
}
299
300
// bitwise right shift
301
$IntDict.__rshift__ = function(self,other){
302
if(isinstance(other, int)){
303
return int($B.LongInt.$dict.__rshift__($B.LongInt(self), $B.LongInt(other)))
304
}
305
var rrshift = getattr(other, '__rrshift__', null)
306
if(rrshift!==null){return rrshift(self)}
307
$err('>>', other)
308
}
311
if(typeof self=="number"){
312
if($IntDict[attr]===undefined){
313
throw _b_.AttributeError("'int' object has no attribute '"+attr+"'")
314
}else{
315
throw _b_.AttributeError("'int' object attribute '"+attr+"' is read-only")
316
}
321
}
322
323
$IntDict.__str__ = $IntDict.__repr__
324
325
$IntDict.__truediv__ = function(self,other){
326
if(isinstance(other,int)){
327
if(other==0) throw ZeroDivisionError('division by zero')
328
if(other.__class__==$B.LongInt.$dict){return new Number(self/parseInt(other.value))}
332
if(!other.valueOf()) throw ZeroDivisionError('division by zero')
333
return new Number(self/other)
334
}
335
if(isinstance(other,_b_.complex)){
336
var cmod = other.real*other.real+other.imag*other.imag
337
if(cmod==0) throw ZeroDivisionError('division by zero')
338
return _b_.complex(self*other.real/cmod,-self*other.imag/cmod)
339
}
340
if(hasattr(other,'__rtruediv__')) return getattr(other,'__rtruediv__')(self)
341
$err("/",other)
342
}
343
344
//$IntDict.__xor__ = function(self,other){return self ^ other} // bitwise XOR
345
346
$IntDict.bit_length = function(self){
347
s = bin(self)
348
s = getattr(s,'lstrip')('-0b') // remove leading zeros and minus sign
349
return s.length // len('100101') --> 6
350
}
351
353
$IntDict.numerator = function(self){return self}
354
$IntDict.denominator = function(self){return int(1)}
355
$IntDict.imag = function(self){return int(0)}
356
$IntDict.real = function(self){return self}
357
365
if(other.__class__===$B.LongInt.$dict){
366
return $B.LongInt.$dict.__sub__($B.LongInt(self), $B.LongInt(other))
367
}
368
if (self > $B.max_int32 || self < $B.min_int32 ||
369
other > $B.max_int32 || other < $B.min_int32) {
370
return $B.LongInt.$dict.__sub__($B.LongInt(self), $B.LongInt(other))
371
}
372
return self-other
374
if(isinstance(other,_b_.bool)) return self-other
375
if(hasattr(other,'__rsub__')) return getattr(other,'__rsub__')(self)
376
$err("-",other)
377
}
378
379
$op_func += '' // source code
381
for(var $op in $ops){
382
var opf = $op_func.replace(/-/gm,$op)
383
opf = opf.replace(new RegExp('sub','gm'),$ops[$op])
384
eval('$IntDict.__'+$ops[$op]+'__ = '+opf)
385
}
386
387
// code for + and -
388
var $op_func = function(self,other){
391
if(typeof other=='number'){
392
var res = self.valueOf()-other.valueOf()
393
if(res>=$B.min_int && res<=$B.max_int){return res}
394
else{return $B.LongInt.$dict.__sub__($B.LongInt(self),
395
$B.LongInt(other))}
396
}else{
397
return $B.LongInt.$dict.__sub__($B.LongInt(self),
398
$B.LongInt(other))
399
}
403
}
404
if(isinstance(other,_b_.complex)){
405
return _b_.complex(self-other.real,-other.imag)
406
}
407
if(isinstance(other,_b_.bool)){
408
var bool_value=0;
409
if(other.valueOf()) bool_value=1;
411
}
412
if(isinstance(other,_b_.complex)){
413
return _b_.complex(self.valueOf() - other.real, other.imag)
414
}
415
if(hasattr(other,'__rsub__')) return getattr(other,'__rsub__')(self)
416
throw $err('-',other)
417
}
418
$op_func += '' // source code
419
var $ops = {'+':'add','-':'sub'}
420
for(var $op in $ops){
421
var opf = $op_func.replace(/-/gm,$op)
422
opf = opf.replace(new RegExp('sub','gm'),$ops[$op])
423
eval('$IntDict.__'+$ops[$op]+'__ = '+opf)
424
}
425
426
// comparison methods
427
var $comp_func = function(self,other){
428
if (other.__class__ === $B.LongInt.$dict) return $B.LongInt.$dict.__gt__($B.LongInt(self), other)
431
if(isinstance(other,_b_.bool)) {
432
return self.valueOf() > _b_.bool.$dict.__hash__(other)
433
}
434
if (hasattr(other, '__int__') || hasattr(other, '__index__')) {
435
return $IntDict.__gt__(self, $B.$GetInt(other))
436
}
439
}
440
$comp_func += '' // source codevar $comps = {'>':'gt','>=':'ge','<':'lt','<=':'le'}
441
for(var $op in $B.$comps){
442
eval("$IntDict.__"+$B.$comps[$op]+'__ = '+
443
$comp_func.replace(/>/gm,$op).replace(/__gt__/gm,'__'+$B.$comps[$op]+'__'))
444
}
445
446
// add "reflected" methods
447
$B.make_rmethods($IntDict)
448
449
var $valid_digits=function(base) {
450
var digits=''
451
if (base === 0) return '0'
452
if (base < 10) {
453
for (var i=0; i < base; i++) digits+=String.fromCharCode(i+48)
454
return digits
455
}
456
457
var digits='0123456789'
458
// A = 65 (10 + 55)
459
for (var i=10; i < base; i++) digits+=String.fromCharCode(i+55)
460
return digits
461
}
462
464
// int() with no argument returns 0
465
if(value===undefined){return 0}
466
467
// int() of an integer returns the integer if base is undefined
468
if(typeof value=='number' &&
469
(base===undefined || base==10)){return parseInt(value)}
470
471
if(base!==undefined){
472
if(!isinstance(value,[_b_.str,_b_.bytes,_b_.bytearray])){
473
throw TypeError("int() can't convert non-string with explicit base")
474
}
475
}
476
477
if(isinstance(value,_b_.complex)){
478
throw TypeError("can't convert complex to int")
479
}
480
487
if(value<$B.min_int || value>$B.max_int){
488
return $B.LongInt.$dict.$from_float(value)
489
}
493
if (!(base >=2 && base <= 36)) {
494
// throw error (base must be 0, or 2-36)
495
if (base != 0) throw _b_.ValueError("invalid base")
496
}
497
498
if (typeof value == 'number'){
499
500
if(base==10){
501
if(value < $B.min_int || value > $B.max_int) return $B.LongInt(value)
502
return value
503
}else if(value.toString().search('e')>-1){
504
// can't convert to another base if value is too big
505
throw _b_.OverflowError("can't convert to base "+base)
506
}else{
507
var res=parseInt(value, base)
508
if(res < $B.min_int || res > $B.max_int) return $B.LongInt(value,base)
509
return res
515
if(value.__class__===$B.LongInt.$dict){
516
var z = parseInt(value.value)
517
if(z>$B.min_int && z<$B.max_int){return z}
518
else{return value}
519
}
522
523
if(isinstance(value, _b_.str)) value=value.valueOf()
524
if(typeof value=="string") {
525
var _value=value.trim() // remove leading/trailing whitespace
526
if (_value.length == 2 && base==0 && (_value=='0b' || _value=='0o' || _value=='0x')) {
531
if (base == 0) {
532
if (_pre == '0B') base=2
533
if (_pre == '0O') base=8
534
if (_pre == '0X') base=16
535
}
536
if (_pre=='0B' || _pre=='0O' || _pre=='0X') {
538
}
539
}
540
var _digits=$valid_digits(base)
541
var _re=new RegExp('^[+-]?['+_digits+']+$', 'i')
550
var res=parseInt(_value, base)
551
if(res < $B.min_int || res > $B.max_int) return $B.LongInt(_value, base)
552
return res
555
if(isinstance(value,[_b_.bytes,_b_.bytearray])){
556
var _digits = $valid_digits(base)
557
for(var i=0;i<value.source.length;i++){
558
if(_digits.indexOf(String.fromCharCode(value.source[i]))==-1){
559
throw _b_.ValueError("invalid literal for int() with base "+
560
base +": "+_b_.repr(value))
561
}
562
}
563
return Number(parseInt(getattr(value,'decode')('latin-1'), base))
564
}
566
if(hasattr(value, '__int__')) return getattr(value,'__int__')()
567
if(hasattr(value, '__index__')) return getattr(value,'__index__')()
568
if(hasattr(value, '__trunc__')) {
569
var res = getattr(value,'__trunc__')(),
570
int_func = _b_.getattr(res, '__int__', null)
571
if(int_func===null){
572
throw TypeError('__trunc__ returned non-Integral (type '+
573
$B.get_class(res).__name__+')')
574
}
575
var res=int_func()
576
if(isinstance(res, int)){return res}
577
throw TypeError('__trunc__ returned non-Integral (type '+
578
$B.get_class(res).__name__+')')
579
}
583
}
584
int.$dict = $IntDict
585
int.__class__ = $B.$factory
586
$IntDict.$factory = int
587
588
_b_.int = int
589