Skip to content
Permalink
Newer
Older
100644 501 lines (422 sloc) 15.4 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{
190
console.log('res is big int',
191
$B.LongInt.$dict.__mul__($B.LongInt(self),
192
$B.LongInt(other)))
193
var res = int($B.LongInt.$dict.__mul__($B.LongInt(self),
194
$B.LongInt(other)))
195
console.log('res', res)
196
return res
197
}
199
if(isinstance(other,_b_.float)){
200
return _b_.float(self*other.value)
201
}
Sep 5, 2014
202
if(isinstance(other,_b_.bool)){
203
if (other.valueOf()) return self
Jan 22, 2015
204
return int(0)
Sep 5, 2014
205
}
206
if(isinstance(other,_b_.complex)){
207
return _b_.complex($IntDict.__mul__(self, other.real),
208
$IntDict.__mul__(self, other.imag))
Sep 5, 2014
209
}
210
if(isinstance(other,[_b_.list,_b_.tuple])){
211
var res = []
212
// make temporary copy of list
213
var $temp = other.slice(0,other.length)
214
for(var i=0;i<val;i++) res=res.concat($temp)
215
if(isinstance(other,_b_.tuple)) res=_b_.tuple(res)
216
return res
217
}
218
if(hasattr(other,'__rmul__')) return getattr(other,'__rmul__')(self)
219
$err("*",other)
220
}
221
222
$IntDict.__name__ = 'int'
223
224
$IntDict.__ne__ = function(self,other){return !$IntDict.__eq__(self,other)}
225
226
$IntDict.__neg__ = function(self){return -self}
227
228
$IntDict.__new__ = function(cls){
229
if(cls===undefined){throw _b_.TypeError('int.__new__(): not enough arguments')}
230
return {__class__:cls.$dict}
231
}
232
233
//$IntDict.__or__ = function(self,other){return self | other} // bitwise OR
234
235
$IntDict.__pow__ = function(self,other){
236
if(isinstance(other, int)) {
Feb 9, 2015
237
switch(other.valueOf()) {
238
case 0:
239
return int(1)
240
case 1:
241
return int(self.valueOf())
242
}
243
var res = Math.pow(self.valueOf(),other.valueOf())
244
if(res>$B.min_int && res<$B.max_int){return res}
245
else{return int($B.LongInt.$dict.__pow__($B.LongInt(self),
246
$B.LongInt(other)))}
Sep 5, 2014
247
}
248
if(isinstance(other, _b_.float)) {
249
return _b_.float(Math.pow(self.valueOf(), other.valueOf()))
250
}
251
if(hasattr(other,'__rpow__')) return getattr(other,'__rpow__')(self)
252
$err("**",other)
253
}
254
255
$IntDict.__repr__ = function(self){
256
if(self===int) return "<class 'int'>"
257
return self.toString()
258
}
259
260
// bitwise right shift
261
$IntDict.__rshift__ = function(self,other){
262
if(isinstance(other, int)){
263
return int($B.LongInt.$dict.__rshift__($B.LongInt(self), $B.LongInt(other)))
264
}
265
var rrshift = getattr(other, '__rrshift__', null)
266
if(rrshift!==null){return rrshift(self)}
267
$err('>>', other)
268
}
Sep 5, 2014
269
270
$IntDict.__setattr__ = function(self,attr,value){
271
if(self.__class__===$IntDict){
272
throw _b_.AttributeError("'int' object has no attribute "+attr+"'")
273
}
274
// subclasses of int can have attributes set
275
self[attr] = value
276
}
277
278
$IntDict.__str__ = $IntDict.__repr__
279
280
$IntDict.__truediv__ = function(self,other){
281
if(isinstance(other,int)){
282
if(other==0) throw ZeroDivisionError('division by zero')
283
return _b_.float(self/other)
284
}
285
if(isinstance(other,_b_.float)){
286
if(!other.value) throw ZeroDivisionError('division by zero')
287
return _b_.float(self/other.value)
288
}
289
if(isinstance(other,_b_.complex)){
290
var cmod = other.real*other.real+other.imag*other.imag
291
if(cmod==0) throw ZeroDivisionError('division by zero')
292
return _b_.complex(self*other.real/cmod,-self*other.imag/cmod)
293
}
294
if(hasattr(other,'__rtruediv__')) return getattr(other,'__rtruediv__')(self)
295
$err("/",other)
296
}
297
298
//$IntDict.__xor__ = function(self,other){return self ^ other} // bitwise XOR
299
300
$IntDict.bit_length = function(self){
301
s = bin(self)
302
s = getattr(s,'lstrip')('-0b') // remove leading zeros and minus sign
303
return s.length // len('100101') --> 6
304
}
305
306
$IntDict.numerator = function(self){return self}
307
$IntDict.denominator = function(self){return int(1)}
308
309
// code for operands & | ^
Sep 5, 2014
310
var $op_func = function(self,other){
311
if(isinstance(other,int)) return self-other
312
if(isinstance(other,_b_.bool)) return self-other
313
if(hasattr(other,'__rsub__')) return getattr(other,'__rsub__')(self)
314
$err("-",other)
315
}
316
317
$op_func += '' // source code
318
var $ops = {'&':'and','|':'or','^':'xor'}
Sep 5, 2014
319
for(var $op in $ops){
320
var opf = $op_func.replace(/-/gm,$op)
321
opf = opf.replace(new RegExp('sub','gm'),$ops[$op])
322
eval('$IntDict.__'+$ops[$op]+'__ = '+opf)
323
}
324
325
// code for + and -
326
var $op_func = function(self,other){
327
if(isinstance(other,int)){
328
var res = self.valueOf()-other.valueOf()
329
if(isinstance(res,int)) return res
330
return _b_.float(res)
331
}
332
if(isinstance(other,_b_.float)){
333
return _b_.float(self.valueOf()-other.value)
334
}
335
if(isinstance(other,_b_.complex)){
336
return _b_.complex(self-other.real,-other.imag)
337
}
338
if(isinstance(other,_b_.bool)){
339
var bool_value=0;
340
if(other.valueOf()) bool_value=1;
341
return self.valueOf()-bool_value
342
}
343
if(isinstance(other,_b_.complex)){
344
return _b_.complex(self.valueOf() - other.real, other.imag)
345
}
346
if(hasattr(other,'__rsub__')) return getattr(other,'__rsub__')(self)
347
throw $err('-',other)
348
}
349
$op_func += '' // source code
350
var $ops = {'+':'add','-':'sub'}
351
for(var $op in $ops){
352
var opf = $op_func.replace(/-/gm,$op)
353
opf = opf.replace(new RegExp('sub','gm'),$ops[$op])
354
eval('$IntDict.__'+$ops[$op]+'__ = '+opf)
355
}
356
357
// comparison methods
358
var $comp_func = function(self,other){
359
if(isinstance(other,int)) return self.valueOf() > other.valueOf()
360
if(isinstance(other,_b_.float)) return self.valueOf() > other.value
361
if(isinstance(other,_b_.bool)) {
362
return self.valueOf() > _b_.bool.$dict.__hash__(other)
363
}
364
if (hasattr(other, '__int__') || hasattr(other, '__index__')) {
365
return $IntDict.__gt__(self, $B.$GetInt(other))
366
}
Sep 5, 2014
367
throw _b_.TypeError(
368
"unorderable types: int() > "+$B.get_class(other).__name__+"()")
Sep 5, 2014
369
}
370
$comp_func += '' // source codevar $comps = {'>':'gt','>=':'ge','<':'lt','<=':'le'}
371
for(var $op in $B.$comps){
372
eval("$IntDict.__"+$B.$comps[$op]+'__ = '+
373
$comp_func.replace(/>/gm,$op).replace(/__gt__/gm,'__'+$B.$comps[$op]+'__'))
Sep 5, 2014
374
}
375
376
// add "reflected" methods
377
$B.make_rmethods($IntDict)
378
379
var $valid_digits=function(base) {
380
var digits=''
381
if (base === 0) return '0'
382
if (base < 10) {
383
for (var i=0; i < base; i++) digits+=String.fromCharCode(i+48)
384
return digits
385
}
386
387
var digits='0123456789'
388
// A = 65 (10 + 55)
389
for (var i=10; i < base; i++) digits+=String.fromCharCode(i+55)
390
return digits
391
}
392
Dec 26, 2014
393
var int = function(value, base){
Jan 22, 2015
394
395
// int() with no argument returns 0
396
if(value===undefined){return 0}
397
398
// int() of an integer returns the integer if base is undefined
399
if(typeof value=='number' &&
400
(base===undefined || base==10)){return parseInt(value)}
401
Dec 28, 2014
402
if(base!==undefined){
403
if(!isinstance(value,[_b_.str,_b_.bytes,_b_.bytearray])){
404
throw TypeError("int() can't convert non-string with explicit base")
405
}
406
}
407
408
if(isinstance(value,_b_.complex)){
409
throw TypeError("can't convert complex to int")
410
}
411
412
var $ns=$B.$MakeArgs1('int',2,{x:null,base:null},['x','base'],arguments,
413
{'base':10},'null','null')
414
var value = $ns['x']
415
var base = $ns['base']
416
417
if(value.__class__==_b_.float.$dict && base===10){return parseInt(value.value)}
Sep 5, 2014
418
Dec 26, 2014
419
if (!(base >=2 && base <= 36)) {
420
// throw error (base must be 0, or 2-36)
421
if (base != 0) throw _b_.ValueError("invalid base")
422
}
423
424
if (typeof value == 'number'){
Dec 28, 2014
425
if(base==10){return value}
Dec 26, 2014
426
else if(value.toString().search('e')>-1){
427
// can't convert to another base if value is too big
428
throw _b_.OverflowError("can't convert to base "+base)
429
}else{
430
return parseInt(value, base)
431
}
432
}
Sep 5, 2014
433
434
if(value===true) return Number(1)
435
if(value===false) return Number(0)
436
if(value.__class__===$B.LongInt.$dict){
437
var z = parseInt(value.value)
438
if(z>$B.min_int && z<$B.max_int){return z}
439
else{return value}
440
}
Sep 5, 2014
441
Jan 22, 2015
442
base=$B.$GetInt(base)
Sep 5, 2014
443
444
if(isinstance(value, _b_.str)) value=value.valueOf()
445
446
if(typeof value=="string") {
447
var _value=value.trim() // remove leading/trailing whitespace
448
if (_value.length == 2 && base==0 && (_value=='0b' || _value=='0o' || _value=='0x')) {
Sep 5, 2014
449
throw _b_.ValueError('invalid value')
450
}
451
if (_value.length >2) {
452
var _pre=_value.substr(0,2).toUpperCase()
Sep 5, 2014
453
if (base == 0) {
454
if (_pre == '0B') base=2
455
if (_pre == '0O') base=8
456
if (_pre == '0X') base=16
457
}
458
if (_pre=='0B' || _pre=='0O' || _pre=='0X') {
Sep 5, 2014
460
}
461
}
462
var _digits=$valid_digits(base)
463
var _re=new RegExp('^[+-]?['+_digits+']+$', 'i')
Sep 5, 2014
465
throw _b_.ValueError(
466
"invalid literal for int() with base "+base +": '"+_b_.str(value)+"'")
Sep 5, 2014
467
}
468
if(base <= 10 && !isFinite(value)) {
469
throw _b_.ValueError(
470
"invalid literal for int() with base "+base +": '"+_b_.str(value)+"'")
Sep 5, 2014
471
}
472
return Number(parseInt(_value, base))
Sep 5, 2014
473
}
Dec 28, 2014
474
Sep 5, 2014
475
476
if(isinstance(value,[_b_.bytes,_b_.bytearray])){
477
var _digits = $valid_digits(base)
478
for(var i=0;i<value.source.length;i++){
479
if(_digits.indexOf(String.fromCharCode(value.source[i]))==-1){
480
throw _b_.ValueError("invalid literal for int() with base "+
481
base +": "+_b_.repr(value))
482
}
483
}
484
return Number(parseInt(getattr(value,'decode')('latin-1'), base))
485
}
Sep 5, 2014
486
487
if(hasattr(value, '__int__')) return Number(getattr(value,'__int__')())
488
if(hasattr(value, '__index__')) return Number(getattr(value,'__index__')())
Sep 5, 2014
489
if(hasattr(value, '__trunc__')) return Number(getattr(value,'__trunc__')())
490
491
throw _b_.ValueError(
492
"invalid literal for int() with base "+base +": '"+_b_.str(value)+"'")
Sep 5, 2014
493
}
494
int.$dict = $IntDict
495
int.__class__ = $B.$factory
496
$IntDict.$factory = int
497
498
_b_.int = int
499
Sep 5, 2014
501
})(__BRYTHON__)