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