Permalink
Dec 18, 2015
Dec 18, 2015
Dec 14, 2015
Feb 23, 2016
Feb 23, 2016
Newer
100644
600 lines (517 sloc)
18.7 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){
389
if(isinstance(other,int)){
390
if(typeof other=='number'){
391
var res = self.valueOf()-other.valueOf()
392
if(res>=$B.min_int && res<=$B.max_int){return res}
393
else{return $B.LongInt.$dict.__sub__($B.LongInt(self),
394
$B.LongInt(other))}
397
}else{
398
return $B.LongInt.$dict.__sub__($B.LongInt(self),
399
$B.LongInt(other))
400
}
404
}
405
if(isinstance(other,_b_.complex)){
406
return _b_.complex(self-other.real,-other.imag)
407
}
408
if(isinstance(other,_b_.bool)){
409
var bool_value=0;
410
if(other.valueOf()) bool_value=1;
412
}
413
if(isinstance(other,_b_.complex)){
414
return _b_.complex(self.valueOf() - other.real, other.imag)
415
}
416
if(hasattr(other,'__rsub__')) return getattr(other,'__rsub__')(self)
417
throw $err('-',other)
418
}
419
$op_func += '' // source code
420
var $ops = {'+':'add','-':'sub'}
421
for(var $op in $ops){
422
var opf = $op_func.replace(/-/gm,$op)
423
opf = opf.replace(new RegExp('sub','gm'),$ops[$op])
424
eval('$IntDict.__'+$ops[$op]+'__ = '+opf)
425
}
426
427
// comparison methods
428
var $comp_func = function(self,other){
429
if (other.__class__ === $B.LongInt.$dict) return $B.LongInt.$dict.__gt__($B.LongInt(self), other)
432
if(isinstance(other,_b_.bool)) {
433
return self.valueOf() > _b_.bool.$dict.__hash__(other)
434
}
435
if (hasattr(other, '__int__') || hasattr(other, '__index__')) {
436
return $IntDict.__gt__(self, $B.$GetInt(other))
437
}
438
439
// See if other has the opposite operator, eg <= for >
440
var inv_op = getattr(other, '__le__', null)
441
if(inv_op !== null){return inv_op(self)}
442
445
}
446
$comp_func += '' // source codevar $comps = {'>':'gt','>=':'ge','<':'lt','<=':'le'}
450
$comp_func.replace(/>/gm,$op).
451
replace(/__gt__/gm,'__'+$B.$comps[$op]+'__').
452
replace(/__le__/, '__'+$B.$inv_comps[$op]+'__'))
453
}
454
455
// add "reflected" methods
456
$B.make_rmethods($IntDict)
457
458
var $valid_digits=function(base) {
459
var digits=''
460
if (base === 0) return '0'
461
if (base < 10) {
462
for (var i=0; i < base; i++) digits+=String.fromCharCode(i+48)
463
return digits
464
}
465
466
var digits='0123456789'
467
// A = 65 (10 + 55)
468
for (var i=10; i < base; i++) digits+=String.fromCharCode(i+55)
469
return digits
470
}
471
473
// int() with no argument returns 0
474
if(value===undefined){return 0}
475
476
// int() of an integer returns the integer if base is undefined
477
if(typeof value=='number' &&
478
(base===undefined || base==10)){return parseInt(value)}
479
480
if(base!==undefined){
481
if(!isinstance(value,[_b_.str,_b_.bytes,_b_.bytearray])){
482
throw TypeError("int() can't convert non-string with explicit base")
483
}
484
}
485
486
if(isinstance(value,_b_.complex)){
487
throw TypeError("can't convert complex to int")
488
}
489
496
if(value<$B.min_int || value>$B.max_int){
497
return $B.LongInt.$dict.$from_float(value)
498
}
502
if (!(base >=2 && base <= 36)) {
503
// throw error (base must be 0, or 2-36)
504
if (base != 0) throw _b_.ValueError("invalid base")
505
}
506
507
if (typeof value == 'number'){
508
509
if(base==10){
510
if(value < $B.min_int || value > $B.max_int) return $B.LongInt(value)
511
return value
512
}else if(value.toString().search('e')>-1){
513
// can't convert to another base if value is too big
514
throw _b_.OverflowError("can't convert to base "+base)
515
}else{
516
var res=parseInt(value, base)
517
if(res < $B.min_int || res > $B.max_int) return $B.LongInt(value,base)
518
return res
524
if(value.__class__===$B.LongInt.$dict){
525
var z = parseInt(value.value)
526
if(z>$B.min_int && z<$B.max_int){return z}
527
else{return value}
528
}
531
532
if(isinstance(value, _b_.str)) value=value.valueOf()
533
if(typeof value=="string") {
534
var _value=value.trim() // remove leading/trailing whitespace
535
if (_value.length == 2 && base==0 && (_value=='0b' || _value=='0o' || _value=='0x')) {
540
if (base == 0) {
541
if (_pre == '0B') base=2
542
if (_pre == '0O') base=8
543
if (_pre == '0X') base=16
544
}
545
if (_pre=='0B' || _pre=='0O' || _pre=='0X') {
547
}
548
}
549
var _digits=$valid_digits(base)
550
var _re=new RegExp('^[+-]?['+_digits+']+$', 'i')
559
var res=parseInt(_value, base)
560
if(res < $B.min_int || res > $B.max_int) return $B.LongInt(_value, base)
561
return res
564
if(isinstance(value,[_b_.bytes,_b_.bytearray])){
565
var _digits = $valid_digits(base)
566
for(var i=0;i<value.source.length;i++){
567
if(_digits.indexOf(String.fromCharCode(value.source[i]))==-1){
568
throw _b_.ValueError("invalid literal for int() with base "+
569
base +": "+_b_.repr(value))
570
}
571
}
572
return Number(parseInt(getattr(value,'decode')('latin-1'), base))
573
}
575
if(hasattr(value, '__int__')) return getattr(value,'__int__')()
576
if(hasattr(value, '__index__')) return getattr(value,'__index__')()
577
if(hasattr(value, '__trunc__')) {
578
var res = getattr(value,'__trunc__')(),
579
int_func = _b_.getattr(res, '__int__', null)
580
if(int_func===null){
581
throw TypeError('__trunc__ returned non-Integral (type '+
582
$B.get_class(res).__name__+')')
583
}
584
var res=int_func()
585
if(isinstance(res, int)){return res}
586
throw TypeError('__trunc__ returned non-Integral (type '+
587
$B.get_class(res).__name__+')')
588
}
592
}
593
int.$dict = $IntDict
594
int.__class__ = $B.$factory
595
$IntDict.$factory = int
596
597
_b_.int = int
598