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