Permalink
Dec 14, 2015
Newer
100644
585 lines (504 sloc)
18.2 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
}
277
var res = Math.pow(self.valueOf(),other.valueOf())
278
if(res>$B.min_int && res<$B.max_int){return res}
279
else{return int($B.LongInt.$dict.__pow__($B.LongInt(self),
280
$B.LongInt(other)))}
284
}
285
if(hasattr(other,'__rpow__')) return getattr(other,'__rpow__')(self)
286
$err("**",other)
287
}
288
289
$IntDict.__repr__ = function(self){
290
if(self===int) return "<class 'int'>"
291
return self.toString()
292
}
293
294
// bitwise right shift
295
$IntDict.__rshift__ = function(self,other){
296
if(isinstance(other, int)){
297
return int($B.LongInt.$dict.__rshift__($B.LongInt(self), $B.LongInt(other)))
298
}
299
var rrshift = getattr(other, '__rrshift__', null)
300
if(rrshift!==null){return rrshift(self)}
301
$err('>>', other)
302
}
305
if(typeof self=="number"){
306
if($IntDict[attr]===undefined){
307
throw _b_.AttributeError("'int' object has no attribute '"+attr+"'")
308
}else{
309
throw _b_.AttributeError("'int' object attribute '"+attr+"' is read-only")
310
}
315
}
316
317
$IntDict.__str__ = $IntDict.__repr__
318
319
$IntDict.__truediv__ = function(self,other){
320
if(isinstance(other,int)){
321
if(other==0) throw ZeroDivisionError('division by zero')
322
if(other.__class__==$B.LongInt.$dict){return new Number(self/parseInt(other.value))}
326
if(!other.valueOf()) throw ZeroDivisionError('division by zero')
327
return new Number(self/other)
328
}
329
if(isinstance(other,_b_.complex)){
330
var cmod = other.real*other.real+other.imag*other.imag
331
if(cmod==0) throw ZeroDivisionError('division by zero')
332
return _b_.complex(self*other.real/cmod,-self*other.imag/cmod)
333
}
334
if(hasattr(other,'__rtruediv__')) return getattr(other,'__rtruediv__')(self)
335
$err("/",other)
336
}
337
338
//$IntDict.__xor__ = function(self,other){return self ^ other} // bitwise XOR
339
340
$IntDict.bit_length = function(self){
341
s = bin(self)
342
s = getattr(s,'lstrip')('-0b') // remove leading zeros and minus sign
343
return s.length // len('100101') --> 6
344
}
345
347
$IntDict.numerator = function(self){return self}
348
$IntDict.denominator = function(self){return int(1)}
349
$IntDict.imag = function(self){return int(0)}
350
$IntDict.real = function(self){return self}
351
359
if(other.__class__===$B.LongInt.$dict){
360
return $B.LongInt.$dict.__sub__($B.LongInt(self), $B.LongInt(other))
361
}
362
if (self > $B.max_int32 || self < $B.min_int32 ||
363
other > $B.max_int32 || other < $B.min_int32) {
364
return $B.LongInt.$dict.__sub__($B.LongInt(self), $B.LongInt(other))
365
}
366
return self-other
368
if(isinstance(other,_b_.bool)) return self-other
369
if(hasattr(other,'__rsub__')) return getattr(other,'__rsub__')(self)
370
$err("-",other)
371
}
372
373
$op_func += '' // source code
375
for(var $op in $ops){
376
var opf = $op_func.replace(/-/gm,$op)
377
opf = opf.replace(new RegExp('sub','gm'),$ops[$op])
378
eval('$IntDict.__'+$ops[$op]+'__ = '+opf)
379
}
380
381
// code for + and -
382
var $op_func = function(self,other){
385
if(typeof other=='number'){
386
var res = self.valueOf()-other.valueOf()
387
if(res>=$B.min_int && res<=$B.max_int){return res}
388
else{return $B.LongInt.$dict.__sub__($B.LongInt(self),
389
$B.LongInt(other))}
390
}else{
391
return $B.LongInt.$dict.__sub__($B.LongInt(self),
392
$B.LongInt(other))
393
}
397
}
398
if(isinstance(other,_b_.complex)){
399
return _b_.complex(self-other.real,-other.imag)
400
}
401
if(isinstance(other,_b_.bool)){
402
var bool_value=0;
403
if(other.valueOf()) bool_value=1;
405
}
406
if(isinstance(other,_b_.complex)){
407
return _b_.complex(self.valueOf() - other.real, other.imag)
408
}
409
if(hasattr(other,'__rsub__')) return getattr(other,'__rsub__')(self)
410
throw $err('-',other)
411
}
412
$op_func += '' // source code
413
var $ops = {'+':'add','-':'sub'}
414
for(var $op in $ops){
415
var opf = $op_func.replace(/-/gm,$op)
416
opf = opf.replace(new RegExp('sub','gm'),$ops[$op])
417
eval('$IntDict.__'+$ops[$op]+'__ = '+opf)
418
}
419
420
// comparison methods
421
var $comp_func = function(self,other){
422
if (other.__class__ === $B.LongInt.$dict) return $B.LongInt.$dict.__gt__($B.LongInt(self), other)
425
if(isinstance(other,_b_.bool)) {
426
return self.valueOf() > _b_.bool.$dict.__hash__(other)
427
}
428
if (hasattr(other, '__int__') || hasattr(other, '__index__')) {
429
return $IntDict.__gt__(self, $B.$GetInt(other))
430
}
433
}
434
$comp_func += '' // source codevar $comps = {'>':'gt','>=':'ge','<':'lt','<=':'le'}
435
for(var $op in $B.$comps){
436
eval("$IntDict.__"+$B.$comps[$op]+'__ = '+
437
$comp_func.replace(/>/gm,$op).replace(/__gt__/gm,'__'+$B.$comps[$op]+'__'))
438
}
439
440
// add "reflected" methods
441
$B.make_rmethods($IntDict)
442
443
var $valid_digits=function(base) {
444
var digits=''
445
if (base === 0) return '0'
446
if (base < 10) {
447
for (var i=0; i < base; i++) digits+=String.fromCharCode(i+48)
448
return digits
449
}
450
451
var digits='0123456789'
452
// A = 65 (10 + 55)
453
for (var i=10; i < base; i++) digits+=String.fromCharCode(i+55)
454
return digits
455
}
456
458
// int() with no argument returns 0
459
if(value===undefined){return 0}
460
461
// int() of an integer returns the integer if base is undefined
462
if(typeof value=='number' &&
463
(base===undefined || base==10)){return parseInt(value)}
464
465
if(base!==undefined){
466
if(!isinstance(value,[_b_.str,_b_.bytes,_b_.bytearray])){
467
throw TypeError("int() can't convert non-string with explicit base")
468
}
469
}
470
471
if(isinstance(value,_b_.complex)){
472
throw TypeError("can't convert complex to int")
473
}
474
481
if(value<$B.min_int || value>$B.max_int){
482
return $B.LongInt.$dict.$from_float(value)
483
}
487
if (!(base >=2 && base <= 36)) {
488
// throw error (base must be 0, or 2-36)
489
if (base != 0) throw _b_.ValueError("invalid base")
490
}
491
492
if (typeof value == 'number'){
493
494
if(base==10){
495
if(value < $B.min_int || value > $B.max_int) return $B.LongInt(value)
496
return value
497
}else if(value.toString().search('e')>-1){
498
// can't convert to another base if value is too big
499
throw _b_.OverflowError("can't convert to base "+base)
500
}else{
501
var res=parseInt(value, base)
502
if(res < $B.min_int || res > $B.max_int) return $B.LongInt(value,base)
503
return res
509
if(value.__class__===$B.LongInt.$dict){
510
var z = parseInt(value.value)
511
if(z>$B.min_int && z<$B.max_int){return z}
512
else{return value}
513
}
516
517
if(isinstance(value, _b_.str)) value=value.valueOf()
518
if(typeof value=="string") {
519
var _value=value.trim() // remove leading/trailing whitespace
520
if (_value.length == 2 && base==0 && (_value=='0b' || _value=='0o' || _value=='0x')) {
525
if (base == 0) {
526
if (_pre == '0B') base=2
527
if (_pre == '0O') base=8
528
if (_pre == '0X') base=16
529
}
530
if (_pre=='0B' || _pre=='0O' || _pre=='0X') {
532
}
533
}
534
var _digits=$valid_digits(base)
535
var _re=new RegExp('^[+-]?['+_digits+']+$', 'i')
544
var res=parseInt(_value, base)
545
if(res < $B.min_int || res > $B.max_int) return $B.LongInt(_value, base)
546
return res
549
if(isinstance(value,[_b_.bytes,_b_.bytearray])){
550
var _digits = $valid_digits(base)
551
for(var i=0;i<value.source.length;i++){
552
if(_digits.indexOf(String.fromCharCode(value.source[i]))==-1){
553
throw _b_.ValueError("invalid literal for int() with base "+
554
base +": "+_b_.repr(value))
555
}
556
}
557
return Number(parseInt(getattr(value,'decode')('latin-1'), base))
558
}
560
if(hasattr(value, '__int__')) return getattr(value,'__int__')()
561
if(hasattr(value, '__index__')) return getattr(value,'__index__')()
562
if(hasattr(value, '__trunc__')) {
563
var res = getattr(value,'__trunc__')(),
564
int_func = _b_.getattr(res, '__int__', null)
565
if(int_func===null){
566
throw TypeError('__trunc__ returned non-Integral (type '+
567
$B.get_class(res).__name__+')')
568
}
569
var res=int_func()
570
if(isinstance(res, int)){return res}
571
throw TypeError('__trunc__ returned non-Integral (type '+
572
$B.get_class(res).__name__+')')
573
}
577
}
578
int.$dict = $IntDict
579
int.__class__ = $B.$factory
580
$IntDict.$factory = int
581
582
_b_.int = int
583