Permalink
Newer
100644
463 lines (386 sloc)
14.2 KB
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
22
var $ns=$B.$MakeArgs("from_bytes", arguments, ['x', 'byteorder'],
23
'signed', 'args', 'kw')
26
var byteorder = $ns['byteorder']
27
var signed = $ns['signed'] || _b_.dict.$dict.get($ns['kw'],'signed', False)
29
var _bytes, _len
30
if (isinstance(x, [_b_.list, _b_.tuple])) {
31
_bytes=x
32
_len=len(x)
36
} else {
37
_b_.TypeError("Error! " + _b_.type(x) + " is not supported in int.from_bytes. fix me!")
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
}
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
}
59
if (!signed) return num
60
if (_bytes[_len - 1] < 128) return num
61
return num - _mult
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
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
}
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
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
}
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()
167
168
// this will be quick check, so lets do it early.
169
if(typeof other==="string") {
170
return other.repeat(val)
171
}
172
180
}
181
if(isinstance(other,_b_.complex)){
182
return _b_.complex(self.valueOf()*other.real, self.valueOf()*other.imag)
183
}
184
if(isinstance(other,[_b_.list,_b_.tuple])){
185
var res = []
186
// make temporary copy of list
187
var $temp = other.slice(0,other.length)
188
for(var i=0;i<val;i++) res=res.concat($temp)
189
if(isinstance(other,_b_.tuple)) res=_b_.tuple(res)
190
return res
191
}
192
if(hasattr(other,'__rmul__')) return getattr(other,'__rmul__')(self)
193
$err("*",other)
194
}
195
196
$IntDict.__name__ = 'int'
197
198
$IntDict.__ne__ = function(self,other){return !$IntDict.__eq__(self,other)}
199
200
$IntDict.__neg__ = function(self){return -self}
201
202
$IntDict.__new__ = function(cls){
203
if(cls===undefined){throw _b_.TypeError('int.__new__(): not enough arguments')}
204
return {__class__:cls.$dict}
205
}
206
207
//$IntDict.__or__ = function(self,other){return self | other} // bitwise OR
208
209
$IntDict.__pow__ = function(self,other){
210
if(isinstance(other, int)) {
211
switch(other.valueOf()) {
212
case 0:
213
return int(1)
214
case 1:
215
return int(self.valueOf())
216
}
217
return Math.pow(self.valueOf(),other.valueOf())
218
}
219
if(isinstance(other, _b_.float)) {
220
return _b_.float(Math.pow(self.valueOf(), other.valueOf()))
221
}
222
if(hasattr(other,'__rpow__')) return getattr(other,'__rpow__')(self)
223
$err("**",other)
224
}
225
226
$IntDict.__repr__ = function(self){
227
if(self===int) return "<class 'int'>"
228
return self.toString()
229
}
230
231
//$IntDict.__rshift__ = function(self,other){return self >> other} // bitwise right shift
232
233
$IntDict.__setattr__ = function(self,attr,value){
234
if(self.__class__===$IntDict){
235
throw _b_.AttributeError("'int' object has no attribute "+attr+"'")
236
}
237
// subclasses of int can have attributes set
238
self[attr] = value
239
}
240
241
$IntDict.__str__ = $IntDict.__repr__
242
243
$IntDict.__truediv__ = function(self,other){
244
if(isinstance(other,int)){
245
if(other==0) throw ZeroDivisionError('division by zero')
246
return _b_.float(self/other)
247
}
248
if(isinstance(other,_b_.float)){
249
if(!other.value) throw ZeroDivisionError('division by zero')
250
return _b_.float(self/other.value)
251
}
252
if(isinstance(other,_b_.complex)){
253
var cmod = other.real*other.real+other.imag*other.imag
254
if(cmod==0) throw ZeroDivisionError('division by zero')
255
return _b_.complex(self*other.real/cmod,-self*other.imag/cmod)
256
}
257
if(hasattr(other,'__rtruediv__')) return getattr(other,'__rtruediv__')(self)
258
$err("/",other)
259
}
260
261
//$IntDict.__xor__ = function(self,other){return self ^ other} // bitwise XOR
262
263
$IntDict.bit_length = function(self){
264
s = bin(self)
265
s = getattr(s,'lstrip')('-0b') // remove leading zeros and minus sign
266
return s.length // len('100101') --> 6
267
}
268
269
$IntDict.numerator = function(self){return self}
270
$IntDict.denominator = function(self){return int(1)}
271
272
// code for operands & | ^ << >>
273
var $op_func = function(self,other){
274
if(isinstance(other,int)) return self-other
275
if(isinstance(other,_b_.bool)) return self-other
276
if(hasattr(other,'__rsub__')) return getattr(other,'__rsub__')(self)
277
$err("-",other)
278
}
279
280
$op_func += '' // source code
281
var $ops = {'&':'and','|':'or','<<':'lshift','>>':'rshift','^':'xor'}
282
for(var $op in $ops){
283
var opf = $op_func.replace(/-/gm,$op)
284
opf = opf.replace(new RegExp('sub','gm'),$ops[$op])
285
eval('$IntDict.__'+$ops[$op]+'__ = '+opf)
286
}
287
288
// code for + and -
289
var $op_func = function(self,other){
290
if(isinstance(other,int)){
291
var res = self.valueOf()-other.valueOf()
292
if(isinstance(res,int)) return res
293
return _b_.float(res)
294
}
295
if(isinstance(other,_b_.float)){
296
return _b_.float(self.valueOf()-other.value)
297
}
298
if(isinstance(other,_b_.complex)){
299
return _b_.complex(self-other.real,-other.imag)
300
}
301
if(isinstance(other,_b_.bool)){
302
var bool_value=0;
303
if(other.valueOf()) bool_value=1;
304
return self.valueOf()-bool_value
305
}
306
if(isinstance(other,_b_.complex)){
307
return _b_.complex(self.valueOf() - other.real, other.imag)
308
}
309
if(hasattr(other,'__rsub__')) return getattr(other,'__rsub__')(self)
310
throw $err('-',other)
311
}
312
$op_func += '' // source code
313
var $ops = {'+':'add','-':'sub'}
314
for(var $op in $ops){
315
var opf = $op_func.replace(/-/gm,$op)
316
opf = opf.replace(new RegExp('sub','gm'),$ops[$op])
317
eval('$IntDict.__'+$ops[$op]+'__ = '+opf)
318
}
319
320
// comparison methods
321
var $comp_func = function(self,other){
322
if(isinstance(other,int)) return self.valueOf() > other.valueOf()
323
if(isinstance(other,_b_.float)) return self.valueOf() > other.value
324
if(isinstance(other,_b_.bool)) {
325
return self.valueOf() > _b_.bool.$dict.__hash__(other)
326
}
327
if (hasattr(other, '__int__') || hasattr(other, '__index__')) {
328
return $IntDict.__gt__(self, $B.$GetInt(other))
329
}
332
}
333
$comp_func += '' // source codevar $comps = {'>':'gt','>=':'ge','<':'lt','<=':'le'}
334
for(var $op in $B.$comps){
335
eval("$IntDict.__"+$B.$comps[$op]+'__ = '+
336
$comp_func.replace(/>/gm,$op).replace(/__gt__/gm,'__'+$B.$comps[$op]+'__'))
337
}
338
339
// add "reflected" methods
340
$B.make_rmethods($IntDict)
341
342
var $valid_digits=function(base) {
343
var digits=''
344
if (base === 0) return '0'
345
if (base < 10) {
346
for (var i=0; i < base; i++) digits+=String.fromCharCode(i+48)
347
return digits
348
}
349
350
var digits='0123456789'
351
// A = 65 (10 + 55)
352
for (var i=10; i < base; i++) digits+=String.fromCharCode(i+55)
353
return digits
354
}
355
358
// int() with no argument returns 0
359
if(value===undefined){return 0}
360
361
// int() of an integer returns the integer if base is undefined
362
if(typeof value=='number' &&
363
(base===undefined || base==10)){return parseInt(value)}
364
365
if(base!==undefined){
366
if(!isinstance(value,[_b_.str,_b_.bytes,_b_.bytearray])){
367
throw TypeError("int() can't convert non-string with explicit base")
368
}
369
}
370
371
if(isinstance(value,_b_.complex)){
372
throw TypeError("can't convert complex to int")
373
}
374
375
var $ns=$B.$MakeArgs1('int',2,{x:null,base:null},['x','base'],arguments,
376
{'base':10},'null','null')
377
var value = $ns['x']
378
var base = $ns['base']
379
380
if(value.__class__==_b_.float.$dict && base===10){return parseInt(value.value)}
382
if (!(base >=2 && base <= 36)) {
383
// throw error (base must be 0, or 2-36)
384
if (base != 0) throw _b_.ValueError("invalid base")
385
}
386
387
if (typeof value == 'number'){
389
else if(value.toString().search('e')>-1){
390
// can't convert to another base if value is too big
391
throw _b_.OverflowError("can't convert to base "+base)
392
}else{
393
return parseInt(value, base)
394
}
395
}
400
base=$B.$GetInt(base)
401
//if(!isinstance(base, _b_.int)) {
402
// if (hasattr(base, '__int__')) {base = Number(getattr(base,'__int__')())
403
// }else if (hasattr(base, '__index__')) {base = Number(getattr(base,'__index__')())}
404
//}
405
406
if(isinstance(value, _b_.str)) value=value.valueOf()
407
408
if(typeof value=="string") {
409
var _value=value.trim() // remove leading/trailing whitespace
410
if (_value.length == 2 && base==0 && (_value=='0b' || _value=='0o' || _value=='0x')) {
415
if (base == 0) {
416
if (_pre == '0B') base=2
417
if (_pre == '0O') base=8
418
if (_pre == '0X') base=16
419
}
420
if (_pre=='0B' || _pre=='0O' || _pre=='0X') {
422
}
423
}
424
var _digits=$valid_digits(base)
425
var _re=new RegExp('^[+-]?['+_digits+']+$', 'i')
438
if(isinstance(value,[_b_.bytes,_b_.bytearray])){
439
var _digits = $valid_digits(base)
440
for(var i=0;i<value.source.length;i++){
441
if(_digits.indexOf(String.fromCharCode(value.source[i]))==-1){
442
throw _b_.ValueError("invalid literal for int() with base "+
443
base +": "+_b_.repr(value))
444
}
445
}
446
return Number(parseInt(getattr(value,'decode')('latin-1'), base))
447
}
451
if(hasattr(value, '__trunc__')) return Number(getattr(value,'__trunc__')())
452
453
throw _b_.ValueError(
455
}
456
int.$dict = $IntDict
457
int.__class__ = $B.$factory
458
$IntDict.$factory = int
459
460
_b_.int = int
461