Skip to content
Permalink
Newer
Older
100644 569 lines (487 sloc) 17.7 KB
Sep 5, 2014
1
;(function($B){
2
3
eval($B.InjectBuiltins())
4
5
var $ObjectDict = _b_.object.$dict, $N = _b_.None
Sep 5, 2014
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
13
// dictionary for built-in class 'int'
Sep 5, 2014
14
var $IntDict = {__class__:$B.$type,
15
__name__:'int',
16
__dir__:$ObjectDict.__dir__,
Sep 5, 2014
17
toString:function(){return '$IntDict'},
18
$native:true
19
}
20
21
$IntDict.from_bytes = function() {
22
var $ns=$B.$MakeArgs1("from_bytes", 3,
23
{x:null, byteorder:null, signed:null}, ['x', 'byteorder', 'signed'],
24
arguments, {signed:False}, 'args', 'kw')
Sep 5, 2014
25
Jan 14, 2015
27
var byteorder = $ns['byteorder']
28
var signed = $ns['signed'] || _b_.dict.$dict.get($ns['kw'],'signed', False)
Sep 5, 2014
29
30
var _bytes, _len
31
if (isinstance(x, [_b_.list, _b_.tuple])) {
32
_bytes=x
33
_len=len(x)
Jan 14, 2015
34
} else if (isinstance(x, [_b_.bytes, _b_.bytearray])) {
35
_bytes=x.source
36
_len=x.source.length
Jan 14, 2015
37
} else {
38
_b_.TypeError("Error! " + _b_.type(x) + " is not supported in int.from_bytes. fix me!")
Sep 5, 2014
39
}
40
41
switch(byteorder) {
42
case 'big':
43
var num = _bytes[_len - 1];
44
var _mult=256
45
for (var i = (_len - 2); i >= 0; i--) {
46
// For operations, use the functions that can take or return
47
// big integers
48
num = $B.add($B.mul(_mult, _bytes[i]), num)
49
_mult = $B.mul(_mult,256)
Jan 14, 2015
51
if (!signed) return num
52
if (_bytes[0] < 128) return num
53
return $B.sub(num, _mult)
54
case 'little':
55
var num = _bytes[0]
56
if (num >= 128) num = num - 256
57
var _mult=256
58
for (var i = 1; i < _len; i++) {
59
num = $B.add($B.mul(_mult, _bytes[i]), num)
60
_mult = $B.mul(_mult,256)
Jan 14, 2015
62
if (!signed) return num
63
if (_bytes[_len - 1] < 128) return num
64
return $B.sub(num, _mult)
Sep 5, 2014
65
}
66
67
throw _b_.ValueError("byteorder must be either 'little' or 'big'");
68
}
69
70
$IntDict.to_bytes = function(length, byteorder, star) {
71
//var len = x.length
72
throw _b_.NotImplementedError("int.to_bytes is not implemented yet")
73
}
74
75
76
//$IntDict.__and__ = function(self,other){return self & other} // bitwise AND
77
78
$IntDict.__abs__ = function(self){return abs(self)}
79
Sep 5, 2014
80
$IntDict.__bool__ = function(self){return new Boolean(self.valueOf())}
81
82
$IntDict.__ceil__ = function(self){return Math.ceil(self)}
83
Sep 5, 2014
84
//is this a duplicate?
85
$IntDict.__class__ = $B.$type
86
87
$IntDict.__divmod__ = function(self, other){return divmod(self, other)}
88
Sep 5, 2014
89
$IntDict.__eq__ = function(self,other){
90
// compare object "self" to class "int"
91
if(other===undefined) return self===int
92
if(isinstance(other,int)) return self.valueOf()==other.valueOf()
93
if(isinstance(other,_b_.float)) return self.valueOf()==other.valueOf()
Sep 5, 2014
94
if(isinstance(other,_b_.complex)){
95
if (other.imag != 0) return False
96
return self.valueOf() == other.real
97
}
98
99
if (hasattr(other, '__eq__')) return getattr(other, '__eq__')(self)
100
Sep 5, 2014
101
return self.valueOf()===other
102
}
103
104
function preformat(self, fmt){
105
if(fmt.empty){return _b_.str(self)}
106
if(fmt.type && 'bcdoxXn'.indexOf(fmt.type)==-1){
107
throw _b_.ValueError("Unknown format code '"+fmt.type+
108
"' for object of type 'int'")
109
}
110
111
switch(fmt.type){
112
case undefined:
113
case 'd':
114
return self.toString()
115
case 'b':
116
return (fmt.alternate ? '0b' : '') + self.toString(2)
117
case 'c':
118
return _b_.chr(self)
119
case 'o':
120
return (fmt.alternate ? '0o' : '') + self.toString(8)
122
return (fmt.alternate ? '0x' : '') + self.toString(16)
124
return (fmt.alternate ? '0X' : '') + self.toString(16).toUpperCase()
125
case 'n':
126
return self // fix me
127
}
128
129
return res
130
}
131
132
Sep 5, 2014
133
$IntDict.__format__ = function(self,format_spec){
134
var fmt = new $B.parse_format_spec(format_spec)
135
fmt.align = fmt.align || '>'
136
var res = preformat(self, fmt)
137
if(fmt.comma){
138
var len = res.length, nb = Math.ceil(res.length/3), chunks = []
139
for(var i=0;i<nb;i++){
140
chunks.push(res.substring(len-3*i-3, len-3*i))
141
}
142
chunks.reverse()
143
res = chunks.join(',')
144
}
145
return $B.format_width(res, fmt)
Sep 5, 2014
146
}
147
148
//$IntDict.__float__ = function(self){return float(self)}
149
Sep 5, 2014
150
$IntDict.__floordiv__ = function(self,other){
151
if(isinstance(other,int)){
152
if(other==0) throw ZeroDivisionError('division by zero')
153
return Math.floor(self/other)
154
}
155
if(isinstance(other,_b_.float)){
156
if(!other.valueOf()) throw ZeroDivisionError('division by zero')
157
return Math.floor(self/other)
Sep 5, 2014
158
}
159
if(hasattr(other,'__rfloordiv__')){
160
return getattr(other,'__rfloordiv__')(self)
161
}
162
$err("//",other)
163
}
164
165
$IntDict.__getitem__ = function(){
166
throw _b_.TypeError("'int' object is not subscriptable")
167
}
168
169
$IntDict.__hash__ = function(self){
170
if (self === undefined) {
171
return $IntDict.__hashvalue__ || $B.$py_next_hash-- // for hash of int type (not instance of int)
172
}
173
174
return self.valueOf()
175
}
Sep 5, 2014
176
177
//$IntDict.__ior__ = function(self,other){return self | other} // bitwise OR
178
179
$IntDict.__index__ = function(self){return self}
180
181
$IntDict.__init__ = function(self,value){
182
if(value===undefined){value=0}
183
self.toString = function(){return value}
184
//self.valueOf = function(){return value}
Sep 5, 2014
186
}
187
188
$IntDict.__int__ = function(self){return self}
189
190
$IntDict.__invert__ = function(self){return ~self}
191
192
// bitwise left shift
193
$IntDict.__lshift__ = function(self,other){
194
if(isinstance(other, int)){
195
return int($B.LongInt.$dict.__lshift__($B.LongInt(self), $B.LongInt(other)))
196
}
197
var rlshift = getattr(other, '__rlshift__', null)
198
if(rlshift!==null){return rlshift(self)}
199
$err('<<', other)
200
}
201
Sep 5, 2014
202
$IntDict.__mod__ = function(self,other) {
203
// can't use Javascript % because it works differently for negative numbers
204
if(isinstance(other,_b_.tuple) && other.length==1) other=other[0]
205
if(isinstance(other,[int, _b_.float, bool])){
206
if(other===false){other=0}else if(other===true){other=1}
207
if(other==0){throw _b_.ZeroDivisionError(
208
"integer division or modulo by zero")}
209
return (self%other+other)%other
Sep 5, 2014
210
}
211
if(hasattr(other,'__rmod__')) return getattr(other,'__rmod__')(self)
212
$err('%',other)
213
}
214
215
$IntDict.__mro__ = [$IntDict,$ObjectDict]
216
217
$IntDict.__mul__ = function(self,other){
218
Sep 5, 2014
219
var val = self.valueOf()
Jan 22, 2015
220
221
// this will be quick check, so lets do it early.
222
if(typeof other==="string") {
223
return other.repeat(val)
224
}
225
226
if(isinstance(other,int)){
227
var res = self*other
228
if(res>$B.min_int && res<$B.max_int){return res}
229
else{return int($B.LongInt.$dict.__mul__($B.LongInt(self),
230
$B.LongInt(other)))}
232
if(isinstance(other,_b_.float)){
233
return new Number(self*other)
Sep 5, 2014
235
if(isinstance(other,_b_.bool)){
236
if (other.valueOf()) return self
Jan 22, 2015
237
return int(0)
Sep 5, 2014
238
}
239
if(isinstance(other,_b_.complex)){
240
return _b_.complex($IntDict.__mul__(self, other.real),
241
$IntDict.__mul__(self, other.imag))
Sep 5, 2014
242
}
243
if(isinstance(other,[_b_.list,_b_.tuple])){
244
var res = []
245
// make temporary copy of list
246
var $temp = other.slice(0,other.length)
247
for(var i=0;i<val;i++) res=res.concat($temp)
248
if(isinstance(other,_b_.tuple)) res=_b_.tuple(res)
249
return res
250
}
251
if(hasattr(other,'__rmul__')) return getattr(other,'__rmul__')(self)
252
$err("*",other)
253
}
254
255
$IntDict.__name__ = 'int'
256
257
$IntDict.__neg__ = function(self){return -self}
258
259
$IntDict.__new__ = function(cls){
260
if(cls===undefined){throw _b_.TypeError('int.__new__(): not enough arguments')}
261
return {__class__:cls.$dict}
262
}
263
264
//$IntDict.__or__ = function(self,other){return self | other} // bitwise OR
265
266
$IntDict.__pow__ = function(self,other){
267
if(isinstance(other, int)) {
Feb 9, 2015
268
switch(other.valueOf()) {
269
case 0:
270
return int(1)
271
case 1:
272
return int(self.valueOf())
273
}
274
var res = Math.pow(self.valueOf(),other.valueOf())
275
if(res>$B.min_int && res<$B.max_int){return res}
276
else{return int($B.LongInt.$dict.__pow__($B.LongInt(self),
277
$B.LongInt(other)))}
Sep 5, 2014
278
}
279
if(isinstance(other, _b_.float)) {
280
return new Number(Math.pow(self.valueOf(), other.valueOf()))
Sep 5, 2014
281
}
282
if(hasattr(other,'__rpow__')) return getattr(other,'__rpow__')(self)
283
$err("**",other)
284
}
285
286
$IntDict.__repr__ = function(self){
287
if(self===int) return "<class 'int'>"
288
return self.toString()
289
}
290
291
// bitwise right shift
292
$IntDict.__rshift__ = function(self,other){
293
if(isinstance(other, int)){
294
return int($B.LongInt.$dict.__rshift__($B.LongInt(self), $B.LongInt(other)))
295
}
296
var rrshift = getattr(other, '__rrshift__', null)
297
if(rrshift!==null){return rrshift(self)}
298
$err('>>', other)
299
}
Sep 5, 2014
300
301
$IntDict.__setattr__ = function(self,attr,value){
302
if(self.__class__===$IntDict){
303
throw _b_.AttributeError("'int' object has no attribute "+attr+"'")
304
}
305
// subclasses of int can have attributes set
306
self[attr] = value
Sep 5, 2014
308
}
309
310
$IntDict.__str__ = $IntDict.__repr__
311
312
$IntDict.__truediv__ = function(self,other){
313
if(isinstance(other,int)){
314
if(other==0) throw ZeroDivisionError('division by zero')
315
if(other.__class__==$B.LongInt.$dict){return new Number(self/parseInt(other.value))}
316
return new Number(self/other)
Sep 5, 2014
317
}
318
if(isinstance(other,_b_.float)){
319
if(!other.valueOf()) throw ZeroDivisionError('division by zero')
320
return new Number(self/other)
Sep 5, 2014
321
}
322
if(isinstance(other,_b_.complex)){
323
var cmod = other.real*other.real+other.imag*other.imag
324
if(cmod==0) throw ZeroDivisionError('division by zero')
325
return _b_.complex(self*other.real/cmod,-self*other.imag/cmod)
326
}
327
if(hasattr(other,'__rtruediv__')) return getattr(other,'__rtruediv__')(self)
328
$err("/",other)
329
}
330
331
//$IntDict.__xor__ = function(self,other){return self ^ other} // bitwise XOR
332
333
$IntDict.bit_length = function(self){
334
s = bin(self)
335
s = getattr(s,'lstrip')('-0b') // remove leading zeros and minus sign
336
return s.length // len('100101') --> 6
337
}
338
339
$IntDict.numerator = function(self){return self}
340
$IntDict.denominator = function(self){return int(1)}
341
342
$B.max_int32= (1<<30) * 2 - 1
343
$B.min_int32= - $B.max_int32
344
345
// code for operands & | ^
Sep 5, 2014
346
var $op_func = function(self,other){
Jun 7, 2015
347
if(isinstance(other,int)) {
348
if (self > $B.max_int32 || self < $B.min_int32 || other > $B.max_int32 || other < $B.min_int32) {
Jun 7, 2015
349
return $B.LongInt.$dict.__sub__($B.LongInt(self), $B.LongInt(other))
350
}
351
return self-other
352
}
Sep 5, 2014
353
if(isinstance(other,_b_.bool)) return self-other
354
if(hasattr(other,'__rsub__')) return getattr(other,'__rsub__')(self)
355
$err("-",other)
356
}
357
358
$op_func += '' // source code
359
var $ops = {'&':'and','|':'or','^':'xor'}
Sep 5, 2014
360
for(var $op in $ops){
361
var opf = $op_func.replace(/-/gm,$op)
362
opf = opf.replace(new RegExp('sub','gm'),$ops[$op])
363
eval('$IntDict.__'+$ops[$op]+'__ = '+opf)
364
}
365
366
// code for + and -
367
var $op_func = function(self,other){
Sep 5, 2014
369
if(isinstance(other,int)){
370
if(typeof other=='number'){
371
var res = self.valueOf()-other.valueOf()
372
if(res>=$B.min_int && res<=$B.max_int){return res}
373
else{return $B.LongInt.$dict.__sub__($B.LongInt(self),
374
$B.LongInt(other))}
375
}else{
376
return $B.LongInt.$dict.__sub__($B.LongInt(self),
377
$B.LongInt(other))
378
}
Sep 5, 2014
379
}
380
if(isinstance(other,_b_.float)){
381
return new Number(self-other)
Sep 5, 2014
382
}
383
if(isinstance(other,_b_.complex)){
384
return _b_.complex(self-other.real,-other.imag)
385
}
386
if(isinstance(other,_b_.bool)){
387
var bool_value=0;
388
if(other.valueOf()) bool_value=1;
Sep 5, 2014
390
}
391
if(isinstance(other,_b_.complex)){
392
return _b_.complex(self.valueOf() - other.real, other.imag)
393
}
394
if(hasattr(other,'__rsub__')) return getattr(other,'__rsub__')(self)
395
throw $err('-',other)
396
}
397
$op_func += '' // source code
398
var $ops = {'+':'add','-':'sub'}
399
for(var $op in $ops){
400
var opf = $op_func.replace(/-/gm,$op)
401
opf = opf.replace(new RegExp('sub','gm'),$ops[$op])
402
eval('$IntDict.__'+$ops[$op]+'__ = '+opf)
403
}
404
405
// comparison methods
406
var $comp_func = function(self,other){
407
if (other.__class__ === $B.LongInt.$dict) return $B.LongInt.$dict.__gt__($B.LongInt(self), other)
Sep 5, 2014
408
if(isinstance(other,int)) return self.valueOf() > other.valueOf()
409
if(isinstance(other,_b_.float)) return self.valueOf() > other.valueOf()
Sep 5, 2014
410
if(isinstance(other,_b_.bool)) {
411
return self.valueOf() > _b_.bool.$dict.__hash__(other)
412
}
413
if (hasattr(other, '__int__') || hasattr(other, '__index__')) {
414
return $IntDict.__gt__(self, $B.$GetInt(other))
415
}
Sep 5, 2014
416
throw _b_.TypeError(
417
"unorderable types: int() > "+$B.get_class(other).__name__+"()")
Sep 5, 2014
418
}
419
$comp_func += '' // source codevar $comps = {'>':'gt','>=':'ge','<':'lt','<=':'le'}
420
for(var $op in $B.$comps){
421
eval("$IntDict.__"+$B.$comps[$op]+'__ = '+
422
$comp_func.replace(/>/gm,$op).replace(/__gt__/gm,'__'+$B.$comps[$op]+'__'))
Sep 5, 2014
423
}
424
425
// add "reflected" methods
426
$B.make_rmethods($IntDict)
427
428
var $valid_digits=function(base) {
429
var digits=''
430
if (base === 0) return '0'
431
if (base < 10) {
432
for (var i=0; i < base; i++) digits+=String.fromCharCode(i+48)
433
return digits
434
}
435
436
var digits='0123456789'
437
// A = 65 (10 + 55)
438
for (var i=10; i < base; i++) digits+=String.fromCharCode(i+55)
439
return digits
440
}
441
Dec 26, 2014
442
var int = function(value, base){
443
// int() with no argument returns 0
444
if(value===undefined){return 0}
445
446
// int() of an integer returns the integer if base is undefined
447
if(typeof value=='number' &&
448
(base===undefined || base==10)){return parseInt(value)}
449
Dec 28, 2014
450
if(base!==undefined){
451
if(!isinstance(value,[_b_.str,_b_.bytes,_b_.bytearray])){
452
throw TypeError("int() can't convert non-string with explicit base")
453
}
454
}
455
456
if(isinstance(value,_b_.complex)){
457
throw TypeError("can't convert complex to int")
458
}
459
460
var $ns=$B.$MakeArgs1('int',2,{x:null,base:null},['x','base'],arguments,
461
{'base':10},'null','null')
462
var value = $ns['x']
463
var base = $ns['base']
464
465
if(isinstance(value, _b_.float) && base===10){
466
var res = parseInt(value)
467
if(res<$B.min_int || res>$B.max_int){return $B.LongInt(res+'')}
468
else{return res}
469
}
Sep 5, 2014
470
Dec 26, 2014
471
if (!(base >=2 && base <= 36)) {
472
// throw error (base must be 0, or 2-36)
473
if (base != 0) throw _b_.ValueError("invalid base")
474
}
475
476
if (typeof value == 'number'){
477
478
if(base==10){
479
if(value < $B.min_int || value > $B.max_int) return $B.LongInt(value)
480
return value
481
}else if(value.toString().search('e')>-1){
Dec 26, 2014
482
// can't convert to another base if value is too big
483
throw _b_.OverflowError("can't convert to base "+base)
484
}else{
485
var res=parseInt(value, base)
486
if(res < $B.min_int || res > $B.max_int) return $B.LongInt(value,base)
487
return res
Dec 26, 2014
488
}
489
}
Sep 5, 2014
490
491
if(value===true) return Number(1)
492
if(value===false) return Number(0)
493
if(value.__class__===$B.LongInt.$dict){
494
var z = parseInt(value.value)
495
if(z>$B.min_int && z<$B.max_int){return z}
496
else{return value}
497
}
Sep 5, 2014
498
Jan 22, 2015
499
base=$B.$GetInt(base)
Sep 5, 2014
500
501
if(isinstance(value, _b_.str)) value=value.valueOf()
502
if(typeof value=="string") {
503
var _value=value.trim() // remove leading/trailing whitespace
504
if (_value.length == 2 && base==0 && (_value=='0b' || _value=='0o' || _value=='0x')) {
Sep 5, 2014
505
throw _b_.ValueError('invalid value')
506
}
507
if (_value.length >2) {
508
var _pre=_value.substr(0,2).toUpperCase()
Sep 5, 2014
509
if (base == 0) {
510
if (_pre == '0B') base=2
511
if (_pre == '0O') base=8
512
if (_pre == '0X') base=16
513
}
514
if (_pre=='0B' || _pre=='0O' || _pre=='0X') {
Sep 5, 2014
516
}
517
}
518
var _digits=$valid_digits(base)
519
var _re=new RegExp('^[+-]?['+_digits+']+$', 'i')
Sep 5, 2014
521
throw _b_.ValueError(
522
"invalid literal for int() with base "+base +": '"+_b_.str(value)+"'")
Sep 5, 2014
523
}
524
if(base <= 10 && !isFinite(value)) {
525
throw _b_.ValueError(
526
"invalid literal for int() with base "+base +": '"+_b_.str(value)+"'")
Sep 5, 2014
527
}
528
var res=parseInt(_value, base)
529
if(res < $B.min_int || res > $B.max_int) return $B.LongInt(_value, base)
530
return res
Sep 5, 2014
531
}
532
533
if(isinstance(value,[_b_.bytes,_b_.bytearray])){
534
var _digits = $valid_digits(base)
535
for(var i=0;i<value.source.length;i++){
536
if(_digits.indexOf(String.fromCharCode(value.source[i]))==-1){
537
throw _b_.ValueError("invalid literal for int() with base "+
538
base +": "+_b_.repr(value))
539
}
540
}
541
return Number(parseInt(getattr(value,'decode')('latin-1'), base))
542
}
Sep 5, 2014
543
544
if(hasattr(value, '__int__')) return getattr(value,'__int__')()
545
if(hasattr(value, '__index__')) return getattr(value,'__index__')()
546
if(hasattr(value, '__trunc__')) {
547
var res = getattr(value,'__trunc__')(),
548
int_func = _b_.getattr(res, '__int__', null)
549
if(int_func===null){
550
throw TypeError('__trunc__ returned non-Integral (type '+
551
$B.get_class(res).__name__+')')
552
}
553
var res=int_func()
554
if(isinstance(res, int)){return res}
555
throw TypeError('__trunc__ returned non-Integral (type '+
556
$B.get_class(res).__name__+')')
557
}
Sep 5, 2014
558
559
throw _b_.ValueError(
560
"invalid literal for int() with base "+base +": '"+_b_.str(value)+"'")
Sep 5, 2014
561
}
562
int.$dict = $IntDict
563
int.__class__ = $B.$factory
564
$IntDict.$factory = int
565
566
_b_.int = int
567
Sep 5, 2014
569
})(__BRYTHON__)