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