Debian Codegraph @

pypy/objspace/std/smalllongobject.py

raw symbols SCIP
1 """Implementation of the int type based on r_longlong.
2
3 Useful for 32-bit applications manipulating values a bit larger than
4 fits in an 'int'.
5 """
6 import operator
7
8 from rpython.rlib.rarithmetic import LONGLONG_BIT, intmask, r_longlong, r_uint
9 from rpython.rlib.rbigint import rbigint
10 from rpython.tool.sourcetools import func_renamer, func_with_new_name
11
12 from pypy.interpreter.error import oefmt
13 from pypy.interpreter.gateway import WrappedDefault, unwrap_spec
14 from pypy.objspace.std.intobject import W_IntObject
15 from pypy.objspace.std.longobject import W_AbstractLongObject, W_LongObject
16 from pypy.objspace.std.util import COMMUTATIVE_OPS
17
18 # XXX: breaks translation
19 #LONGLONG_MIN = r_longlong(-1 << (LONGLONG_BIT - 1))
20
21
22 class W_SmallLongObject(W_AbstractLongObject):
23
24 _immutable_fields_ = ['longlong']
25
26 def __init__(self, value):
27 assert isinstance(value, r_longlong)
28 self.longlong = value
29
30 @staticmethod
31 def fromint(value):
32 return W_SmallLongObject(r_longlong(value))
33
34 @staticmethod
35 def frombigint(bigint):
36 return W_SmallLongObject(bigint.tolonglong())
37
38 def asbigint(self):
39 return rbigint.fromrarith_int(self.longlong)
40
41 def longval(self):
42 return self.longlong
43
44 def __repr__(self):
45 return '<W_SmallLongObject(%d)>' % self.longlong
46
47 def _int_w(self, space):
48 a = self.longlong
49 b = intmask(a)
50 if b == a:
51 return b
52 raise oefmt(space.w_OverflowError,
53 "long int too large to convert to int")
54
55 def uint_w(self, space):
56 a = self.longlong
57 if a < 0:
58 raise oefmt(space.w_ValueError,
59 "cannot convert negative integer to unsigned int")
60 b = r_uint(a)
61 if r_longlong(b) == a:
62 return b
63 raise oefmt(space.w_OverflowError,
64 "long int too large to convert to unsigned int")
65
66 def bigint_w(self, space, allow_conversion=True):
67 return self.asbigint()
68
69 def _bigint_w(self, space):
70 return self.asbigint()
71
72 def _float_w(self, space):
73 return float(self.longlong)
74
75 def int(self, space):
76 if type(self) is W_SmallLongObject:
77 return self
78 if not space.is_overloaded(self, space.w_int, '__int__'):
79 return W_LongObject(self.num)
80 return W_Root.int(self, space)
81
82 def descr_float(self, space):
83 return space.newfloat(float(self.longlong))
84
85 def descr_neg(self, space):
86 a = self.longlong
87 try:
88 if a == r_longlong(-1 << (LONGLONG_BIT-1)):
89 raise OverflowError
90 x = -a
91 except OverflowError:
92 self = _small2long(space, self)
93 return self.descr_neg(space)
94 return W_SmallLongObject(x)
95
96 def descr_abs(self, space):
97 return self if self.longlong >= 0 else self.descr_neg(space)
98
99 def descr_bool(self, space):
100 return space.newbool(bool(self.longlong))
101
102 def descr_invert(self, space):
103 x = ~self.longlong
104 return W_SmallLongObject(x)
105
106 @unwrap_spec(w_modulus=WrappedDefault(None))
107 def descr_pow(self, space, w_exponent, w_modulus=None):
108 if isinstance(w_exponent, W_AbstractLongObject):
109 self = _small2long(space, self)
110 return self.descr_pow(space, w_exponent, w_modulus)
111 elif not isinstance(w_exponent, W_IntObject):
112 return space.w_NotImplemented
113
114 x = self.longlong
115 y = space.int_w(w_exponent)
116
117 if space.is_none(w_modulus):
118 try:
119 return _pow(space, x, y, r_longlong(0))
120 except ValueError:
121 self = self.descr_float(space)
122 return space.pow(self, w_exponent, space.w_None)
123 except OverflowError:
124 self = _small2long(space, self)
125 return self.descr_pow(space, w_exponent, w_modulus)
126 elif isinstance(w_modulus, W_IntObject):
127 w_modulus = w_modulus.as_w_long(space)
128 elif not isinstance(w_modulus, W_AbstractLongObject):
129 return space.w_NotImplemented
130 elif not isinstance(w_modulus, W_SmallLongObject):
131 self = _small2long(space, self)
132 return self.descr_pow(space, w_exponent, w_modulus)
133
134 z = w_modulus.longlong
135 if z == 0:
136 raise oefmt(space.w_ValueError, "pow() 3rd argument cannot be 0")
137 if y < 0:
138 # don't implement with smalllong
139 self = _small2long(space, self)
140 return self.descr_pow(space, w_exponent, w_modulus)
141 try:
142 return _pow(space, x, y, z)
143 except ValueError:
144 self = self.descr_float(space)
145 return space.pow(self, w_exponent, w_modulus)
146 except OverflowError:
147 self = _small2long(space, self)
148 return self.descr_pow(space, w_exponent, w_modulus)
149
150 @unwrap_spec(w_modulus=WrappedDefault(None))
151 def descr_rpow(self, space, w_base, w_modulus=None):
152 if isinstance(w_base, W_IntObject):
153 # Defer to w_base<W_SmallLongObject>.descr_pow
154 w_base = w_base.descr_long(space)
155 elif not isinstance(w_base, W_AbstractLongObject):
156 return space.w_NotImplemented
157 return w_base.descr_pow(space, self, w_modulus)
158
159 def _make_descr_cmp(opname):
160 op = getattr(operator, opname)
161 bigint_op = getattr(rbigint, opname)
162 @func_renamer('descr_' + opname)
163 def descr_cmp(self, space, w_other):
164 if isinstance(w_other, W_IntObject):
165 result = op(self.longlong, w_other.int_w(space))
166 elif not isinstance(w_other, W_AbstractLongObject):
167 return space.w_NotImplemented
168 elif isinstance(w_other, W_SmallLongObject):
169 result = op(self.longlong, w_other.longlong)
170 else:
171 result = bigint_op(self.asbigint(), w_other.asbigint())
172 return space.newbool(result)
173 return descr_cmp
174
175 descr_lt = _make_descr_cmp('lt')
176 descr_le = _make_descr_cmp('le')
177 descr_eq = _make_descr_cmp('eq')
178 descr_ne = _make_descr_cmp('ne')
179 descr_gt = _make_descr_cmp('gt')
180 descr_ge = _make_descr_cmp('ge')
181
182 def _make_descr_binop(func, ovf=True):
183 opname = func.__name__[1:]
184 descr_name, descr_rname = 'descr_' + opname, 'descr_r' + opname
185 long_op = getattr(W_LongObject, descr_name)
186
187 @func_renamer(descr_name)
188 def descr_binop(self, space, w_other):
189 if isinstance(w_other, W_IntObject):
190 w_other = w_other.as_w_long(space)
191 elif not isinstance(w_other, W_AbstractLongObject):
192 return space.w_NotImplemented
193 elif not isinstance(w_other, W_SmallLongObject):
194 self = _small2long(space, self)
195 return long_op(self, space, w_other)
196
197 if ovf:
198 try:
199 return func(self, space, w_other)
200 except OverflowError:
201 self = _small2long(space, self)
202 w_other = _small2long(space, w_other)
203 return long_op(self, space, w_other)
204 else:
205 return func(self, space, w_other)
206
207 if opname in COMMUTATIVE_OPS:
208 @func_renamer(descr_rname)
209 def descr_rbinop(self, space, w_other):
210 return descr_binop(self, space, w_other)
211 return descr_binop, descr_rbinop
212
213 long_rop = getattr(W_LongObject, descr_rname)
214 @func_renamer(descr_rname)
215 def descr_rbinop(self, space, w_other):
216 if isinstance(w_other, W_IntObject):
217 w_other = w_other.as_w_long(space)
218 elif not isinstance(w_other, W_AbstractLongObject):
219 return space.w_NotImplemented
220 elif not isinstance(w_other, W_SmallLongObject):
221 self = _small2long(space, self)
222 return long_rop(self, space, w_other)
223
224 if ovf:
225 try:
226 return func(w_other, space, self)
227 except OverflowError:
228 self = _small2long(space, self)
229 w_other = _small2long(space, w_other)
230 return long_rop(self, space, w_other)
231 else:
232 return func(w_other, space, self)
233
234 return descr_binop, descr_rbinop
235
236 def _add(self, space, w_other):
237 x = self.longlong
238 y = w_other.longlong
239 z = x + y
240 if ((z ^ x) & (z ^ y)) < 0:
241 raise OverflowError
242 return W_SmallLongObject(z)
243 descr_add, descr_radd = _make_descr_binop(_add)
244
245 def _sub(self, space, w_other):
246 x = self.longlong
247 y = w_other.longlong
248 z = x - y
249 if ((z ^ x) & (z ^ ~y)) < 0:
250 raise OverflowError
251 return W_SmallLongObject(z)
252 descr_sub, descr_rsub = _make_descr_binop(_sub)
253
254 def _mul(self, space, w_other):
255 x = self.longlong
256 y = w_other.longlong
257 z = _llong_mul_ovf(x, y)
258 return W_SmallLongObject(z)
259 descr_mul, descr_rmul = _make_descr_binop(_mul)
260
261 def _floordiv(self, space, w_other):
262 x = self.longlong
263 y = w_other.longlong
264 try:
265 if y == -1 and x == r_longlong(-1 << (LONGLONG_BIT-1)):
266 raise OverflowError
267 z = x // y
268 except ZeroDivisionError:
269 raise oefmt(space.w_ZeroDivisionError, "integer division by zero")
270 return W_SmallLongObject(z)
271 descr_floordiv, descr_rfloordiv = _make_descr_binop(_floordiv)
272
273 def _mod(self, space, w_other):
274 x = self.longlong
275 y = w_other.longlong
276 try:
277 if y == -1 and x == r_longlong(-1 << (LONGLONG_BIT-1)):
278 raise OverflowError
279 z = x % y
280 except ZeroDivisionError:
281 raise oefmt(space.w_ZeroDivisionError, "integer modulo by zero")
282 return W_SmallLongObject(z)
283 descr_mod, descr_rmod = _make_descr_binop(_mod)
284
285 def _divmod(self, space, w_other):
286 x = self.longlong
287 y = w_other.longlong
288 try:
289 if y == -1 and x == r_longlong(-1 << (LONGLONG_BIT-1)):
290 raise OverflowError
291 z = x // y
292 except ZeroDivisionError:
293 raise oefmt(space.w_ZeroDivisionError, "integer divmod by zero")
294 # no overflow possible
295 m = x % y
296 return space.newtuple2(W_SmallLongObject(z), W_SmallLongObject(m))
297 descr_divmod, descr_rdivmod = _make_descr_binop(_divmod)
298
299 def _lshift(self, space, w_other):
300 a = self.longlong
301 # May overflow
302 b = space.int_w(w_other)
303 if r_uint(b) < LONGLONG_BIT: # 0 <= b < LONGLONG_BIT
304 c = a << b
305 if a != (c >> b):
306 raise OverflowError
307 return W_SmallLongObject(c)
308 if b < 0:
309 raise oefmt(space.w_ValueError, "negative shift count")
310 # b >= LONGLONG_BIT
311 if a == 0:
312 return self
313 raise OverflowError
314 descr_lshift, descr_rlshift = _make_descr_binop(_lshift)
315
316 def _rshift(self, space, w_other):
317 a = self.longlong
318 # May overflow
319 b = space.int_w(w_other)
320 if r_uint(b) >= LONGLONG_BIT: # not (0 <= b < LONGLONG_BIT)
321 if b < 0:
322 raise oefmt(space.w_ValueError, "negative shift count")
323 # b >= LONGLONG_BIT
324 if a == 0:
325 return self
326 a = -1 if a < 0 else 0
327 else:
328 a = a >> b
329 return W_SmallLongObject(a)
330 descr_rshift, descr_rrshift = _make_descr_binop(_rshift, ovf=False)
331
332 def _and(self, space, w_other):
333 a = self.longlong
334 b = w_other.longlong
335 res = a & b
336 return W_SmallLongObject(res)
337 descr_and, descr_rand = _make_descr_binop(_and, ovf=False)
338
339 def _or(self, space, w_other):
340 a = self.longlong
341 b = w_other.longlong
342 res = a | b
343 return W_SmallLongObject(res)
344 descr_or, descr_ror = _make_descr_binop(_or, ovf=False)
345
346 def _xor(self, space, w_other):
347 a = self.longlong
348 b = w_other.longlong
349 res = a ^ b
350 return W_SmallLongObject(res)
351 descr_xor, descr_rxor = _make_descr_binop(_xor, ovf=False)
352
353
354 def _llong_mul_ovf(a, b):
355 # xxx duplication of the logic from translator/c/src/int.h
356 longprod = a * b
357 doubleprod = float(a) * float(b)
358 doubled_longprod = float(longprod)
359
360 # Fast path for normal case: small multiplicands, and no info
361 # is lost in either method.
362 if doubled_longprod == doubleprod:
363 return longprod
364
365 # Somebody somewhere lost info. Close enough, or way off? Note
366 # that a != 0 and b != 0 (else doubled_longprod == doubleprod == 0).
367 # The difference either is or isn't significant compared to the
368 # true value (of which doubleprod is a good approximation).
369 diff = doubled_longprod - doubleprod
370 absdiff = abs(diff)
371 absprod = abs(doubleprod)
372 # absdiff/absprod <= 1/32 iff
373 # 32 * absdiff <= absprod -- 5 good bits is "close enough"
374 if 32.0 * absdiff <= absprod:
375 return longprod
376 raise OverflowError("integer multiplication")
377
378
379 def _small2long(space, w_small):
380 return W_LongObject(w_small.asbigint())
381
382
383 def _pow(space, iv, iw, iz):
384 if iw < 0:
385 if iz != 0:
386 raise oefmt(space.w_ValueError,
387 "pow() 2nd argument cannot be negative when 3rd "
388 "argument specified")
389 raise ValueError
390 temp = iv
391 ix = r_longlong(1)
392 while iw > 0:
393 if iw & 1:
394 ix = _llong_mul_ovf(ix, temp)
395 iw >>= 1 # Shift exponent down by 1 bit
396 if iw == 0:
397 break
398 temp = _llong_mul_ovf(temp, temp) # Square the value of temp
399 if iz:
400 # If we did a multiplication, perform a modulo
401 ix %= iz
402 temp %= iz
403 if iz:
404 ix %= iz
405 return W_SmallLongObject(ix)