Debian Codegraph @

lib_pypy/__decimal.py

raw symbols SCIP
1 # Implementation of the "decimal" module, based on libmpdec library.
2
3 __xname__ = __name__ # sys.modules lookup (--without-threads)
4 __name__ = 'decimal' # For pickling
5
6
7 import _collections_abc
8 import math as _math
9 import numbers as _numbers
10 import sys as _sys
11
12 from _decimal_cffi import ffi as _ffi, lib as _mpdec
13
14 # Compatibility with the C version
15 HAVE_THREADS = True
16 HAVE_CONTEXTVAR = True
17 if _sys.maxsize == 2**63-1:
18 MAX_PREC = 999999999999999999
19 MAX_EMAX = 999999999999999999
20 MIN_EMIN = -999999999999999999
21 else:
22 MAX_PREC = 425000000
23 MAX_EMAX = 425000000
24 MIN_EMIN = -425000000
25
26 MIN_ETINY = MIN_EMIN - (MAX_PREC-1)
27
28 # Errors
29
30 class DecimalException(ArithmeticError):
31 def handle(self, context, *args):
32 pass
33
34 class Clamped(DecimalException):
35 pass
36
37 class InvalidOperation(DecimalException):
38 def handle(self, context, *args):
39 if args:
40 ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
41 return ans._fix_nan(context)
42 return _NaN
43
44 class ConversionSyntax(InvalidOperation):
45 def handle(self, context, *args):
46 return _NaN
47
48 class DivisionByZero(DecimalException, ZeroDivisionError):
49 def handle(self, context, sign, *args):
50 return _SignedInfinity[sign]
51
52 class DivisionImpossible(InvalidOperation):
53 def handle(self, context, *args):
54 return _NaN
55
56 class DivisionUndefined(InvalidOperation, ZeroDivisionError):
57 def handle(self, context, *args):
58 return _NaN
59
60 class Inexact(DecimalException):
61 pass
62
63 class InvalidContext(InvalidOperation):
64 def handle(self, context, *args):
65 return _NaN
66
67 class Rounded(DecimalException):
68 pass
69
70 class Subnormal(DecimalException):
71 pass
72
73 class Overflow(Inexact, Rounded):
74 def handle(self, context, sign, *args):
75 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
76 ROUND_HALF_DOWN, ROUND_UP):
77 return _SignedInfinity[sign]
78 if sign == 0:
79 if context.rounding == ROUND_CEILING:
80 return _SignedInfinity[sign]
81 return _dec_from_triple(sign, '9'*context.prec,
82 context.Emax-context.prec+1)
83 if sign == 1:
84 if context.rounding == ROUND_FLOOR:
85 return _SignedInfinity[sign]
86 return _dec_from_triple(sign, '9'*context.prec,
87 context.Emax-context.prec+1)
88
89 class Underflow(Inexact, Rounded, Subnormal):
90 pass
91
92 class FloatOperation(DecimalException, TypeError):
93 pass
94
95
96 __version__ = "1.70"
97 __libmpdec_version__ = _ffi.string(_mpdec.mpd_version())
98
99 # Default context
100
101 import threading
102 __local = threading.local()
103 del threading
104
105 def getcontext():
106 """Returns this thread's context.
107
108 If this thread does not yet have a context, returns
109 a new context and sets this thread's context.
110 New contexts are copies of DefaultContext.
111 """
112 try:
113 return __local.__decimal_context__
114 except AttributeError:
115 context = Context()
116 __local.__decimal_context__ = context
117 return context
118
119 def _getcontext(context=None):
120 if context is None:
121 return getcontext()
122 if not isinstance(context, Context):
123 raise TypeError
124 return context
125
126 def setcontext(context):
127 """Set this thread's context to context."""
128 if context in (DefaultContext, BasicContext, ExtendedContext):
129 context = context.copy()
130 context.clear_flags()
131 if not isinstance(context, Context):
132 raise TypeError
133 __local.__decimal_context__ = context
134
135 def localcontext(ctx=None):
136 """Return a context manager for a copy of the supplied context.
137 """
138 return _ContextManager(_getcontext(ctx))
139
140
141 from collections import namedtuple as _namedtuple
142 DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
143
144
145 # A codecs error handler to handle unicode digits
146 import codecs as _codecs
147 import unicodedata as _unicodedata
148 def _handle_decimaldigits(exc):
149 res = ""
150 for c in exc.object[exc.start:exc.end]:
151 if c.isspace():
152 res += ' '
153 else:
154 res += str(_unicodedata.digit(c))
155 return res, exc.end
156 _codecs.register_error('_decimal_encode', _handle_decimaldigits)
157
158
159 def _unsafe_check(name, lo, hi, value):
160 if not -_sys.maxsize-1 <= value <= _sys.maxsize:
161 raise OverflowError(
162 "Python int too large to convert to C ssize_t")
163 if not lo <= value <= hi:
164 raise ValueError("valid range for unsafe %s is [%d, %d]" %
165 (name, lo, hi))
166
167
168 # Decimal class
169
170 _DEC_MINALLOC = 4
171
172 class Decimal(object):
173 __slots__ = ('_mpd', '_data')
174
175 def __new__(cls, value="0", context=None):
176 return cls._from_object(value, context, exact=True)
177
178 @classmethod
179 def _new_empty(cls):
180 self = object.__new__(cls)
181 self._mpd = mpd = _ffi.new("struct mpd_t*")
182 self._data = _ffi.new("mpd_uint_t[]", _DEC_MINALLOC)
183 mpd.flags = _mpdec.MPD_STATIC | _mpdec.MPD_STATIC_DATA
184 mpd.alloc = _DEC_MINALLOC
185 mpd.exp = 0
186 mpd.digits = 0
187 mpd.len = 0
188 mpd.data = self._data
189 return self
190
191 def __del__(self):
192 _mpdec.mpd_del(self._mpd)
193
194 @classmethod
195 def _from_object(cls, value, context, exact=True):
196 if isinstance(value, Decimal):
197 return cls._from_decimal(value, context, exact=exact)
198 if isinstance(value, str):
199 return cls._from_str(value, context, exact=exact, strip=exact)
200 if isinstance(value, int):
201 return cls._from_int(value, context, exact=exact)
202 if isinstance(value, (list, tuple)):
203 return cls._from_tuple(value, context, exact=exact)
204 if isinstance(value, float):
205 context = _getcontext(context)
206 context._add_status(_mpdec.MPD_Float_operation)
207 return cls._from_float_subclass_handling(value, context, exact=exact)
208 raise TypeError("conversion from %s to Decimal is not supported" %
209 value.__class__.__name__)
210
211 @classmethod
212 def _from_decimal(cls, value, context, exact=True):
213 if exact:
214 if cls is Decimal and type(value) is Decimal:
215 return value
216 self = cls._new_empty()
217 with _CatchConversions(self._mpd, context, exact) as (
218 ctx, status_ptr):
219 _mpdec.mpd_qcopy(self._mpd, value._mpd, status_ptr)
220 return self
221 else:
222 if (_mpdec.mpd_isnan(value._mpd) and
223 value._mpd.digits > (context._ctx.prec - context._ctx.clamp)):
224 # Special case: too many NaN payload digits
225 context._add_status(_mpdec.MPD_Conversion_syntax)
226 self = cls._new_empty()
227 _mpdec.mpd_setspecial(self._mpd, _mpdec.MPD_POS, _mpdec.MPD_NAN)
228 return self
229 else:
230 self = cls._new_empty()
231 with _CatchStatus(context) as (ctx, status_ptr):
232 _mpdec.mpd_qcopy(self._mpd, value._mpd, status_ptr)
233 _mpdec.mpd_qfinalize(self._mpd, ctx, status_ptr)
234 return self
235
236 @classmethod
237 def _from_str(cls, value, context, exact=True, strip=True):
238 value = value.replace("_", "")
239 s = str.encode(value, 'ascii', '_decimal_encode')
240 if b'\0' in s:
241 s = b'' # empty string triggers ConversionSyntax.
242 if strip:
243 s = s.strip()
244 return cls._from_bytes(s, context, exact=exact)
245
246 @classmethod
247 def _from_bytes(cls, value, context, exact=True):
248 self = cls._new_empty()
249 with _CatchConversions(self._mpd, context, exact) as (ctx, status_ptr):
250 _mpdec.mpd_qset_string(self._mpd, value, ctx, status_ptr)
251 return self
252
253 @classmethod
254 def _from_int(cls, value, context, exact=True):
255 value = int(value) # in case it's a subclass of 'int'
256 self = cls._new_empty()
257 with _CatchConversions(self._mpd, context, exact) as (ctx, status_ptr):
258 size = (((value|1).bit_length() + 15) // 16) + 5
259 if value < 0:
260 value = -value
261 sign = _mpdec.MPD_NEG
262 else:
263 sign = _mpdec.MPD_POS
264 array = value.to_bytes(2*size, byteorder='little', signed=False)
265 digits = _ffi.new("uint8_t[]", array)
266 _mpdec.mpd_qimport_u16(
267 self._mpd, _ffi.cast("uint16_t*", digits),
268 size, sign, 0x10000, ctx, status_ptr)
269 return self
270
271 @classmethod
272 def _from_tuple(cls, value, context, exact=True):
273 sign, digits, exponent = value
274
275 # Make a bytes string representation of a DecimalTuple
276 builder = []
277
278 # sign
279 if not isinstance(sign, int) or sign not in (0, 1):
280 raise ValueError("sign must be an integer with the value 0 or 1")
281 builder.append(b'-' if sign else b'+')
282
283 # exponent or encoding for a special number
284 is_infinite = False
285 is_special = False
286 if isinstance(exponent, str):
287 # special
288 is_special = True
289 if exponent == 'F':
290 builder.append(b'Inf')
291 is_infinite = True
292 elif exponent == 'n':
293 builder.append(b'Nan')
294 elif exponent == 'N':
295 builder.append(b'sNan')
296 else:
297 raise ValueError("string argument in the third position "
298 "must be 'F', 'n' or 'N'")
299 exponent = 0
300 else:
301 if not isinstance(exponent, int):
302 raise ValueError("exponent must be an integer")
303 if not -_sys.maxsize-1 <= exponent <= _sys.maxsize:
304 # Compatibility with CPython
305 raise OverflowError(
306 "Python int too large to convert to C ssize_t")
307
308 # coefficients
309 if not digits and not is_special:
310 # empty tuple: zero coefficient, except for special numbers
311 builder.append(b'0')
312 for digit in digits:
313 if not isinstance(digit, int) or not 0 <= digit <= 9:
314 raise ValueError("coefficient must be a tuple of digits")
315 if is_infinite:
316 # accept but ignore any well-formed coefficient for
317 # compatibility with decimal.py
318 continue
319 builder.append(bytes([ord('0') + digit]))
320
321 if not is_special:
322 builder.append(b'E')
323 builder.append(str(exponent).encode())
324
325 return cls._from_bytes(b''.join(builder), context, exact=exact)
326
327 @classmethod
328 def from_float(cls, value):
329 if not isinstance(value, (int, float)):
330 raise TypeError("argument must be int of float")
331 return cls._from_float_subclass_handling(value, getcontext())
332
333 @classmethod
334 def _from_float_subclass_handling(cls, value, context, exact=True):
335 result = cls._from_float(value, context, exact=exact)
336 if cls is Decimal:
337 return result
338 else:
339 return cls(result)
340
341 @staticmethod
342 def _from_float(value, context, exact=True):
343 if isinstance(value, int):
344 return Decimal._from_int(value, context, exact=exact)
345 value = float(value) # in case it's a subclass of 'float'
346 sign = 0 if _math.copysign(1.0, value) == 1.0 else 1
347
348 if _math.isnan(value):
349 self = Decimal._new_empty()
350 # decimal.py calls repr(float(+-nan)), which always gives a
351 # positive result.
352 _mpdec.mpd_setspecial(self._mpd, _mpdec.MPD_POS, _mpdec.MPD_NAN)
353 return self
354 if _math.isinf(value):
355 self = Decimal._new_empty()
356 _mpdec.mpd_setspecial(self._mpd, sign, _mpdec.MPD_INF)
357 return self
358
359 # float as integer ratio: numerator/denominator
360 num, den = abs(value).as_integer_ratio()
361 k = den.bit_length() - 1
362
363 self = Decimal._from_int(num, context, exact=True)
364
365 # Compute num * 5**k
366 d1 = _mpdec.mpd_qnew()
367 if not d1:
368 raise MemoryError()
369 try:
370 d2 = _mpdec.mpd_qnew()
371 if not d2:
372 raise MemoryError()
373 try:
374 with _CatchConversions(self._mpd, context, exact=True) as (
375 ctx, status_ptr):
376 _mpdec.mpd_qset_uint(d1, 5, ctx, status_ptr)
377 _mpdec.mpd_qset_ssize(d2, k, ctx, status_ptr)
378 _mpdec.mpd_qpow(d1, d1, d2, ctx, status_ptr)
379 finally:
380 _mpdec.mpd_del(d2)
381 with _CatchConversions(self._mpd, context, exact=True) as (
382 ctx, status_ptr):
383 _mpdec.mpd_qmul(self._mpd, self._mpd, d1, ctx, status_ptr)
384 finally:
385 _mpdec.mpd_del(d1)
386
387 # result = +- n * 5**k * 10**-k
388 _mpdec.mpd_set_sign(self._mpd, sign)
389 self._mpd.exp = - k
390
391 if not exact:
392 with _CatchStatus(context) as (ctx, status_ptr):
393 _mpdec.mpd_qfinalize(self._mpd, ctx, status_ptr)
394 return self
395
396 def __str__(self):
397 return getcontext().to_sci_string(self)
398
399 def __repr__(self):
400 context = getcontext()
401 output = _mpdec.mpd_to_sci(self._mpd, context._capitals)
402 if not output:
403 raise MemoryError
404 try:
405 result = _ffi.string(output)
406 finally:
407 _mpdec.mpd_free(output)
408 return "Decimal('%s')" % result.decode()
409
410 def as_tuple(self):
411 "Return the DecimalTuple representation of a Decimal"
412 mpd = self._mpd
413 sign = _mpdec.mpd_sign(mpd)
414 if _mpdec.mpd_isinfinite(mpd):
415 expt = "F"
416 # decimal.py has non-compliant infinity payloads.
417 coeff = (0,)
418 else:
419 if _mpdec.mpd_isnan(mpd):
420 if _mpdec.mpd_issnan(mpd):
421 expt = "N"
422 else:
423 expt = "n"
424 else:
425 expt = mpd.exp
426
427 if mpd.len > 0:
428 # coefficient is defined
429
430 # make an integer
431 # XXX this should be done in C...
432 x = _mpdec.mpd_qncopy(mpd)
433 if not x:
434 raise MemoryError
435 try:
436 x.exp = 0
437 # clear NaN and sign
438 _mpdec.mpd_clear_flags(x)
439 intstring = _mpdec.mpd_to_sci(x, 1)
440 finally:
441 _mpdec.mpd_del(x)
442 if not intstring:
443 raise MemoryError
444 try:
445 digits = _ffi.string(intstring)
446 finally:
447 _mpdec.mpd_free(intstring)
448 coeff = tuple(d - ord('0') for d in digits)
449 else:
450 coeff = ()
451
452 return DecimalTuple(sign, coeff, expt)
453
454 def as_integer_ratio(self):
455 "Convert a Decimal to its exact integer ratio representation"
456 if _mpdec.mpd_isspecial(self._mpd):
457 if _mpdec.mpd_isnan(self._mpd):
458 raise ValueError("cannot convert NaN to integer ratio")
459 else:
460 raise OverflowError("cannot convert Infinity to integer ratio")
461
462 context = getcontext()
463 tmp = Decimal._new_empty()
464 with _CatchStatus(context) as (ctx, status_ptr):
465 _mpdec.mpd_qcopy(tmp._mpd, self._mpd, status_ptr)
466 exp = tmp._mpd.exp if tmp else 0
467 tmp._mpd.exp = 0
468
469 # context and rounding are unused here: the conversion is exact
470 numerator = tmp._to_int(_mpdec.MPD_ROUND_FLOOR)
471
472 exponent = 10 ** abs(exp)
473 if exp >= 0:
474 numerator *= exponent
475 denominator = 1
476 else:
477 denominator = exponent
478 gcd = _math.gcd(numerator, denominator)
479 numerator //= gcd
480 denominator //= gcd
481
482 return numerator, denominator
483
484 def _convert_for_comparison(self, other, op):
485 if isinstance(other, Decimal):
486 return self, other
487
488 context = getcontext()
489 if isinstance(other, int):
490 other = Decimal._from_int(other, context)
491 elif isinstance(other, float):
492 if op not in ('eq', 'ne'):
493 # Add status, and maybe raise
494 context._add_status(_mpdec.MPD_Float_operation)
495 else:
496 # Add status, but don't raise
497 context._ctx.status |= _mpdec.MPD_Float_operation
498 other = Decimal._from_float(other, context)
499 elif isinstance(other, complex):
500 if op not in ('eq', 'ne'):
501 return NotImplemented, NotImplemented
502 if other.imag != 0.0:
503 return NotImplemented, NotImplemented
504 # Add status, but don't raise
505 context._ctx.status |= _mpdec.MPD_Float_operation
506 other = Decimal._from_float(other.real, context)
507 elif isinstance(other, _numbers.Rational):
508 numerator = Decimal._from_int(other.numerator, context)
509 if not _mpdec.mpd_isspecial(self._mpd):
510 # multiplied = self * other.denominator
511 #
512 # Prevent Overflow in the following multiplication.
513 # The result of the multiplication is
514 # only used in mpd_qcmp, which can handle values that
515 # are technically out of bounds, like (for 32-bit)
516 # 99999999999999999999...99999999e+425000000.
517 vv = _mpdec.mpd_qncopy(self._mpd)
518 if not vv:
519 raise MemoryError
520 try:
521 exp = vv.exp
522 vv.exp = 0
523 multiplied = Decimal._new_empty()
524 denom = Decimal(other.denominator)
525 maxctx = _ffi.new("struct mpd_context_t*")
526 _mpdec.mpd_maxcontext(maxctx)
527 status_ptr = _ffi.new("uint32_t*")
528 _mpdec.mpd_qmul(multiplied._mpd, vv, denom._mpd,
529 maxctx, status_ptr)
530 multiplied._mpd.exp = exp
531 finally:
532 _mpdec.mpd_del(vv)
533 if status_ptr[0] != 0:
534 raise ValueError("exact conversion for comparison failed")
535
536 return multiplied, numerator
537 else:
538 return self, numerator
539 else:
540 return NotImplemented, NotImplemented
541 return self, other
542
543 # _PyHASH_10INV is the inverse of 10 modulo the prime _PyHASH_MODULUS
544 _PyHASH_MODULUS = _sys.hash_info.modulus
545 _PyHASH_10INV = pow(10, _PyHASH_MODULUS - 2, _PyHASH_MODULUS)
546
547 def __bool__(self):
548 return not _mpdec.mpd_iszero(self._mpd)
549
550 def __hash__(self):
551 # In order to make sure that the hash of a Decimal instance
552 # agrees with the hash of a numerically equal integer, float
553 # or Fraction, we follow the rules for numeric hashes outlined
554 # in the documentation. (See library docs, 'Built-in Types').
555 mpd = self._mpd
556 if _mpdec.mpd_isspecial(mpd):
557 if _mpdec.mpd_issnan(mpd):
558 raise TypeError("cannot hash a signaling NaN value")
559 elif _mpdec.mpd_isnan(mpd):
560 return _sys.hash_info.nan
561 elif _mpdec.mpd_isnegative(mpd):
562 return -_sys.hash_info.inf
563 else:
564 return _sys.hash_info.inf
565
566 maxctx = _ffi.new("struct mpd_context_t*")
567 _mpdec.mpd_maxcontext(maxctx)
568 status_ptr = _ffi.new("uint32_t*")
569
570 # XXX cache these
571 p = self._new_empty()
572 _mpdec.mpd_qset_ssize(p._mpd, self._PyHASH_MODULUS,
573 maxctx, status_ptr)
574 ten = self._new_empty()
575 _mpdec.mpd_qset_ssize(ten._mpd, 10,
576 maxctx, status_ptr)
577 inv10_p = self._new_empty()
578 _mpdec.mpd_qset_ssize(inv10_p._mpd, self._PyHASH_10INV,
579 maxctx, status_ptr)
580
581 tmp = self._new_empty()
582 exp_hash = self._new_empty()
583
584 if mpd.exp >= 0:
585 # 10**exp(v) % p
586 _mpdec.mpd_qsset_ssize(tmp._mpd, mpd.exp, maxctx, status_ptr)
587 _mpdec.mpd_qpowmod(exp_hash._mpd, ten._mpd, tmp._mpd, p._mpd,
588 maxctx, status_ptr)
589 else:
590 # inv10_p**(-exp(v)) % p
591 _mpdec.mpd_qsset_ssize(tmp._mpd, -mpd.exp, maxctx, status_ptr)
592 _mpdec.mpd_qpowmod(exp_hash._mpd, inv10_p._mpd, tmp._mpd, p._mpd,
593 maxctx, status_ptr)
594
595 # hash = (int(v) * exp_hash) % p
596 if not _mpdec.mpd_qcopy(tmp._mpd, mpd, status_ptr):
597 raise MemoryError
598
599 tmp._mpd.exp = 0
600 _mpdec.mpd_set_positive(tmp._mpd)
601
602 maxctx.prec = MAX_PREC + 21
603 maxctx.emax = MAX_EMAX + 21
604 maxctx.emin = MIN_EMIN - 21
605
606 _mpdec.mpd_qmul(tmp._mpd, tmp._mpd, exp_hash._mpd, maxctx, status_ptr)
607 _mpdec.mpd_qrem(tmp._mpd, tmp._mpd, p._mpd, maxctx, status_ptr)
608
609 result = _mpdec.mpd_qget_ssize(tmp._mpd, status_ptr)
610 result = result if _mpdec.mpd_ispositive(mpd) else -result
611 result = result if result != -1 else -2
612
613 if status_ptr[0]:
614 if status_ptr[0] & _mpdec.MPD_Malloc_error:
615 raise MemoryError
616 else:
617 raise SystemError("Decimal.__hash__")
618
619 return result
620
621 def _cmp(self, other, op):
622 a, b = self._convert_for_comparison(other, op)
623 if a is NotImplemented:
624 return NotImplemented
625 status_ptr = _ffi.new("uint32_t*")
626 r = _mpdec.mpd_qcmp(a._mpd, b._mpd, status_ptr)
627 if r > 1: # INT_MAX
628 # sNaNs or op={le,ge,lt,gt} always signal
629 if (_mpdec.mpd_issnan(a._mpd) or
630 _mpdec.mpd_issnan(b._mpd) or
631 op not in ('eq', 'ne')):
632 getcontext()._add_status(status_ptr[0])
633 # qNaN comparison with op={eq,ne} or comparison with
634 # InvalidOperation disabled.
635 # Arrange to return False.
636 if op in ('gt', 'ge'):
637 return -1
638 else:
639 return 1
640 return r
641
642 def __eq__(self, other):
643 r = self._cmp(other, 'eq')
644 if r is NotImplemented:
645 return NotImplemented
646 return r == 0
647
648 def __ne__(self, other):
649 r = self._cmp(other, 'ne')
650 if r is NotImplemented:
651 return NotImplemented
652 return r != 0
653
654 def __lt__(self, other):
655 r = self._cmp(other, 'lt')
656 if r is NotImplemented:
657 return NotImplemented
658 return r < 0
659
660 def __le__(self, other):
661 r = self._cmp(other, 'le')
662 if r is NotImplemented:
663 return NotImplemented
664 return r <= 0
665
666 def __gt__(self, other):
667 r = self._cmp(other, 'gt')
668 if r is NotImplemented:
669 return NotImplemented
670 return r > 0
671
672 def __ge__(self, other):
673 r = self._cmp(other, 'ge')
674 if r is NotImplemented:
675 return NotImplemented
676 return r >= 0
677
678 # operations
679 def _make_unary_operation(name, ctxop_name=None):
680 ctxop_name = ctxop_name or name
681 if name.startswith('__'):
682 def method(self):
683 return getattr(getcontext(), ctxop_name)(self)
684 else:
685 # Allow optional context
686 def method(self, context=None):
687 context = _getcontext(context)
688 return getattr(context, ctxop_name)(self)
689 method.__name__ = name
690 return method
691
692 def _make_unary_operation_noctx(name, ctxop_name=None):
693 ctxop_name = ctxop_name or name
694 def method(self):
695 return getattr(getcontext(), ctxop_name)(self)
696 method.__name__ = name
697 return method
698
699 def _make_binary_operation(name, ctxop_name=None):
700 ctxop_name = ctxop_name or name
701 if name.startswith('__'):
702 def method(self, other):
703 return getattr(getcontext(), ctxop_name)(
704 self, other, strict=False)
705 else:
706 def method(self, other, context=None):
707 context = _getcontext(context)
708 return getattr(context, ctxop_name)(
709 self, other)
710 method.__name__ = name
711 return method
712
713 def _make_binary_roperation(name, ctxop_name):
714 def method(self, other):
715 return getattr(getcontext(), ctxop_name)(other, self, strict=False)
716 method.__name__ = name
717 return method
718
719 __abs__ = _make_unary_operation('__abs__', 'abs')
720 __pos__ = _make_unary_operation('__pos__', 'plus')
721 __neg__ = _make_unary_operation('__neg__', 'minus')
722
723 __add__ = _make_binary_operation('__add__', 'add')
724 __sub__ = _make_binary_operation('__sub__', 'subtract')
725 __mul__ = _make_binary_operation('__mul__', 'multiply')
726 __floordiv__ = _make_binary_operation('__floordiv__', 'divide_int')
727 __truediv__ = _make_binary_operation('__truediv__', 'divide')
728 __mod__ = _make_binary_operation('__mod__', 'remainder')
729 __divmod__ = _make_binary_operation('__divmod__', 'divmod')
730
731 __radd__ = _make_binary_roperation('__radd__', 'add')
732 __rsub__ = _make_binary_roperation('__rsub__', 'subtract')
733 __rmul__ = _make_binary_roperation('__rmul__', 'multiply')
734 __rfloordiv__ = _make_binary_roperation('__rfloordiv__', 'divide_int')
735 __rtruediv__ = _make_binary_roperation('__rtruediv__', 'divide')
736 __rmod__ = _make_binary_roperation('__rmod__', 'remainder')
737 __rdivmod__ = _make_binary_roperation('__rdivmod__', 'divmod')
738
739 def __pow__(self, other, modulo=None):
740 return getcontext().power(self, other, modulo, strict=False)
741 def __rpow__(self, other):
742 return getcontext().power(other, self, strict=False)
743
744 copy_sign = _make_binary_operation('copy_sign')
745 copy_abs = _make_unary_operation_noctx('copy_abs')
746 copy_negate = _make_unary_operation_noctx('copy_negate')
747
748 sqrt = _make_unary_operation('sqrt')
749 exp = _make_unary_operation('exp')
750 ln = _make_unary_operation('ln')
751 log10 = _make_unary_operation('log10')
752 logb = _make_unary_operation('logb')
753 logical_invert = _make_unary_operation('logical_invert')
754 normalize = _make_unary_operation('normalize')
755
756 compare = _make_binary_operation('compare')
757 compare_signal = _make_binary_operation('compare_signal')
758 compare_total = _make_binary_operation('compare_total')
759 compare_total_mag = _make_binary_operation('compare_total_mag')
760 logical_and = _make_binary_operation('logical_and')
761 logical_or = _make_binary_operation('logical_or')
762 logical_xor = _make_binary_operation('logical_xor')
763 max = _make_binary_operation('max')
764 max_mag = _make_binary_operation('max_mag')
765 min = _make_binary_operation('min')
766 min_mag = _make_binary_operation('min_mag')
767 next_minus = _make_unary_operation('next_minus')
768 next_plus = _make_unary_operation('next_plus')
769 next_toward = _make_binary_operation('next_toward')
770 remainder_near = _make_binary_operation('remainder_near')
771 rotate = _make_binary_operation('rotate')
772 same_quantum = _make_binary_operation('same_quantum')
773 scaleb = _make_binary_operation('scaleb')
774 shift = _make_binary_operation('shift')
775
776 is_normal = _make_unary_operation('is_normal')
777 is_subnormal = _make_unary_operation('is_subnormal')
778 is_signed = _make_unary_operation_noctx('is_signed')
779 is_zero = _make_unary_operation_noctx('is_zero')
780 is_nan = _make_unary_operation_noctx('is_nan')
781 is_snan = _make_unary_operation_noctx('is_snan')
782 is_qnan = _make_unary_operation_noctx('is_qnan')
783 is_finite = _make_unary_operation_noctx('is_finite')
784 is_infinite = _make_unary_operation_noctx('is_infinite')
785 number_class = _make_unary_operation('number_class')
786
787 to_eng_string = _make_unary_operation('to_eng_string')
788
789 def fma(self, other, third, context=None):
790 context = _getcontext(context)
791 return context.fma(self, other, third)
792
793 def _to_int(self, rounding):
794 mpd = self._mpd
795 if _mpdec.mpd_isspecial(mpd):
796 if _mpdec.mpd_isnan(mpd):
797 raise ValueError("cannot convert NaN to integer")
798 else:
799 raise OverflowError("cannot convert Infinity to integer")
800
801 x = Decimal._new_empty()
802 context = getcontext()
803 tempctx = context.copy()
804 tempctx._ctx.round = rounding
805 with _CatchStatus(context) as (ctx, status_ptr):
806 # We round with the temporary context, but set status and
807 # raise errors on the global one.
808 _mpdec.mpd_qround_to_int(x._mpd, mpd, tempctx._ctx, status_ptr)
809
810 # XXX mpd_qexport_u64 would be faster...
811 digits_ptr = _ffi.new("uint16_t**")
812 n = _mpdec.mpd_qexport_u16(digits_ptr, 0, 0x10000,
813 x._mpd, status_ptr)
814 if n == _mpdec.MPD_SIZE_MAX:
815 raise MemoryError
816 try:
817 s = _ffi.buffer(digits_ptr[0], n * 2)[:]
818 finally:
819 _mpdec.mpd_free(digits_ptr[0])
820 result = int.from_bytes(s, 'little', signed=False)
821 if _mpdec.mpd_isnegative(x._mpd) and not _mpdec.mpd_iszero(x._mpd):
822 result = -result
823 return result
824
825 def __int__(self):
826 return self._to_int(_mpdec.MPD_ROUND_DOWN)
827
828 __trunc__ = __int__
829
830 def __floor__(self):
831 return self._to_int(_mpdec.MPD_ROUND_FLOOR)
832
833 def __ceil__(self):
834 return self._to_int(_mpdec.MPD_ROUND_CEILING)
835
836 def to_integral(self, rounding=None, context=None):
837 context = _getcontext(context)
838 workctx = context.copy()
839 if rounding is not None:
840 workctx.rounding = rounding
841 result = Decimal._new_empty()
842 with _CatchStatus(context) as (ctx, status_ptr):
843 # We round with the temporary context, but set status and
844 # raise errors on the global one.
845 _mpdec.mpd_qround_to_int(result._mpd, self._mpd,
846 workctx._ctx, status_ptr)
847 return result
848
849 to_integral_value = to_integral
850
851 def to_integral_exact(self, rounding=None, context=None):
852 context = _getcontext(context)
853 workctx = context.copy()
854 if rounding is not None:
855 workctx.rounding = rounding
856 result = Decimal._new_empty()
857 with _CatchStatus(context) as (ctx, status_ptr):
858 # We round with the temporary context, but set status and
859 # raise errors on the global one.
860 _mpdec.mpd_qround_to_intx(result._mpd, self._mpd,
861 workctx._ctx, status_ptr)
862 return result
863
864 def quantize(self, exp, rounding=None, context=None):
865 context = _getcontext(context)
866 exp = context._convert_unaryop(exp)
867 workctx = context.copy()
868 if rounding is not None:
869 workctx.rounding = rounding
870 result = Decimal._new_empty()
871 with _CatchStatus(context) as (ctx, status_ptr):
872 # We round with the temporary context, but set status and
873 # raise errors on the global one.
874 _mpdec.mpd_qquantize(result._mpd, self._mpd, exp._mpd,
875 workctx._ctx, status_ptr)
876 return result
877
878 def __round__(self, x=None):
879 if x is None:
880 return self._to_int(_mpdec.MPD_ROUND_HALF_EVEN)
881 result = Decimal._new_empty()
882 context = getcontext()
883 q = Decimal._from_int(1, context)
884 if x == _mpdec.MPD_SSIZE_MIN:
885 q._mpd.exp = _mpdec.MPD_SSIZE_MAX
886 elif x == -_mpdec.MPD_SSIZE_MIN:
887 raise OverflowError # For compatibility with CPython.
888 else:
889 q._mpd.exp = -x
890 with _CatchStatus(context) as (ctx, status_ptr):
891 _mpdec.mpd_qquantize(result._mpd, self._mpd, q._mpd,
892 ctx, status_ptr)
893 return result
894
895 def __float__(self):
896 if _mpdec.mpd_isnan(self._mpd):
897 if _mpdec.mpd_issnan(self._mpd):
898 raise ValueError("cannot convert signaling NaN to float")
899 if _mpdec.mpd_isnegative(self._mpd):
900 return float("-nan")
901 else:
902 return float("nan")
903 else:
904 return float(str(self))
905
906 def radix(self):
907 return Decimal(10)
908
909 def canonical(self):
910 return self
911
912 def is_canonical(self):
913 return True
914
915 def adjusted(self):
916 if _mpdec.mpd_isspecial(self._mpd):
917 return 0
918 return _mpdec.mpd_adjexp(self._mpd)
919
920 @property
921 def real(self):
922 return self
923
924 @property
925 def imag(self):
926 return Decimal(0)
927
928 def conjugate(self):
929 return self
930
931 def __complex__(self):
932 return complex(float(self))
933
934 def __copy__(self):
935 return self
936
937 def __deepcopy__(self, memo=None):
938 return self
939
940 def __reduce__(self):
941 return (type(self), (str(self),))
942
943 def __format__(self, specifier, override=None):
944 if not isinstance(specifier, str):
945 raise TypeError
946 fmt = specifier.encode('utf-8')
947 context = getcontext()
948
949 replace_fillchar = False
950 if fmt and fmt[0] == 0:
951 # NUL fill character: must be replaced with a valid UTF-8 char
952 # before calling mpd_parse_fmt_str().
953 replace_fillchar = True
954 fmt = b'_' + fmt[1:]
955
956 spec = _ffi.new("mpd_spec_t*")
957 if not _mpdec.mpd_parse_fmt_str(spec, fmt, context._capitals):
958 raise ValueError("invalid format string")
959 if replace_fillchar:
960 # In order to avoid clobbering parts of UTF-8 thousands
961 # separators or decimal points when the substitution is
962 # reversed later, the actual placeholder must be an invalid
963 # UTF-8 byte.
964 spec.fill = b'\xff\x00'
965
966 if override:
967 # Values for decimal_point, thousands_sep and grouping can
968 # be explicitly specified in the override dict. These values
969 # take precedence over the values obtained from localeconv()
970 # in mpd_parse_fmt_str(). The feature is not documented and
971 # is only used in test_decimal.
972 try:
973 dot = _ffi.new("char[]", override['decimal_point'].encode())
974 except KeyError:
975 pass
976 else:
977 spec.dot = dot
978 try:
979 sep = _ffi.new("char[]", override['thousands_sep'].encode())
980 except KeyError:
981 pass
982 else:
983 spec.sep = sep
984 try:
985 grouping = _ffi.new("char[]", override['grouping'].encode())
986 except KeyError:
987 pass
988 else:
989 spec.grouping = grouping
990 if _mpdec.mpd_validate_lconv(spec) < 0:
991 raise ValueError("invalid override dict")
992
993 with _CatchStatus(context) as (ctx, status_ptr):
994 decstring = _mpdec.mpd_qformat_spec(
995 self._mpd, spec, ctx, status_ptr)
996 status = status_ptr[0]
997 if not decstring:
998 if status & _mpdec.MPD_Malloc_error:
999 raise MemoryError
1000 else:
1001 raise ValueError("format specification exceeds "
1002 "internal limits of _decimal")
1003 result = _ffi.string(decstring)
1004 if replace_fillchar:
1005 result = result.replace(b'\xff', b'\0')
1006 return result.decode('utf-8')
1007
1008
1009 # Register Decimal as a kind of Number (an abstract base class).
1010 # However, do not register it as Real (because Decimals are not
1011 # interoperable with floats).
1012 _numbers.Number.register(Decimal)
1013
1014 # Context class
1015
1016 _DEC_DFLT_EMAX = 999999
1017 _DEC_DFLT_EMIN = -999999
1018
1019 # Rounding
1020 _ROUNDINGS = {
1021 'ROUND_DOWN': _mpdec.MPD_ROUND_DOWN,
1022 'ROUND_HALF_UP': _mpdec.MPD_ROUND_HALF_UP,
1023 'ROUND_HALF_EVEN': _mpdec.MPD_ROUND_HALF_EVEN,
1024 'ROUND_CEILING': _mpdec.MPD_ROUND_CEILING,
1025 'ROUND_FLOOR': _mpdec.MPD_ROUND_FLOOR,
1026 'ROUND_UP': _mpdec.MPD_ROUND_UP,
1027 'ROUND_HALF_DOWN': _mpdec.MPD_ROUND_HALF_DOWN,
1028 'ROUND_05UP': _mpdec.MPD_ROUND_05UP,
1029 }
1030 for _rounding in _ROUNDINGS:
1031 globals()[_rounding] = _rounding
1032
1033 _SIGNALS = {
1034 InvalidOperation: _mpdec.MPD_IEEE_Invalid_operation,
1035 FloatOperation: _mpdec.MPD_Float_operation,
1036 DivisionByZero: _mpdec.MPD_Division_by_zero ,
1037 Overflow: _mpdec.MPD_Overflow ,
1038 Underflow: _mpdec.MPD_Underflow ,
1039 Subnormal: _mpdec.MPD_Subnormal ,
1040 Inexact: _mpdec.MPD_Inexact ,
1041 Rounded: _mpdec.MPD_Rounded,
1042 Clamped: _mpdec.MPD_Clamped,
1043 }
1044
1045 class _ContextManager(object):
1046 """Context manager class to support localcontext().
1047
1048 Sets a copy of the supplied context in __enter__() and restores
1049 the previous decimal context in __exit__()
1050 """
1051 def __init__(self, new_context):
1052 self.new_context = new_context.copy()
1053 def __enter__(self):
1054 self.saved_context = getcontext()
1055 setcontext(self.new_context)
1056 return self.new_context
1057 def __exit__(self, t, v, tb):
1058 setcontext(self.saved_context)
1059
1060
1061 class Context(object):
1062 """Contains the context for a Decimal instance.
1063
1064 Contains:
1065 prec - precision (for use in rounding, division, square roots..)
1066 rounding - rounding type (how you round)
1067 traps - If traps[exception] = 1, then the exception is
1068 raised when it is caused. Otherwise, a value is
1069 substituted in.
1070 flags - When an exception is caused, flags[exception] is set.
1071 (Whether or not the trap_enabler is set)
1072 Should be reset by user of Decimal instance.
1073 Emin - Minimum exponent
1074 Emax - Maximum exponent
1075 capitals - If 1, 1*10^1 is printed as 1E+1.
1076 If 0, printed as 1e1
1077 clamp - If 1, change exponents if too high (Default 0)
1078 """
1079
1080 __slots__ = ('_ctx', '_capitals')
1081
1082 def __new__(cls, prec=None, rounding=None, Emin=None, Emax=None,
1083 capitals=None, clamp=None, flags=None, traps=None):
1084 # NOTE: the arguments are ignored here, they are used in __init__()
1085 self = object.__new__(cls)
1086 self._ctx = ctx = _ffi.new("struct mpd_context_t*")
1087 # Default context
1088 ctx.prec = 28
1089 ctx.emax = _DEC_DFLT_EMAX
1090 ctx.emin = _DEC_DFLT_EMIN
1091 ctx.traps = (_mpdec.MPD_IEEE_Invalid_operation|
1092 _mpdec.MPD_Division_by_zero|
1093 _mpdec.MPD_Overflow)
1094 ctx.status = 0
1095 ctx.newtrap = 0
1096 ctx.round = _mpdec.MPD_ROUND_HALF_EVEN
1097 ctx.clamp = 0
1098 ctx.allcr = 1
1099
1100 self._capitals = 1
1101 return self
1102
1103 def __init__(self, prec=None, rounding=None, Emin=None, Emax=None,
1104 capitals=None, clamp=None, flags=None, traps=None):
1105 ctx = self._ctx
1106
1107 try:
1108 dc = DefaultContext._ctx
1109 except NameError:
1110 pass
1111 else:
1112 ctx[0] = dc[0]
1113 if prec is not None:
1114 self.prec = prec
1115 if rounding is not None:
1116 self.rounding = rounding
1117 if Emin is not None:
1118 self.Emin = Emin
1119 if Emax is not None:
1120 self.Emax = Emax
1121 if clamp is not None:
1122 self.clamp = clamp
1123 if capitals is not None:
1124 self.capitals = capitals
1125
1126 if traps is None:
1127 ctx.traps = dc.traps
1128 elif isinstance(traps, list):
1129 ctx.traps = 0
1130 for signal in traps:
1131 ctx.traps |= _SIGNALS[signal]
1132 elif isinstance(traps, dict):
1133 ctx.traps = 0
1134 for signal, value in traps.items():
1135 if value:
1136 ctx.traps |= _SIGNALS[signal]
1137 else:
1138 self.traps = traps
1139
1140 if flags is None:
1141 ctx.status = 0
1142 elif isinstance(flags, list):
1143 ctx.status = 0
1144 for signal in flags:
1145 ctx.status |= _SIGNALS[signal]
1146 elif isinstance(flags, dict):
1147 for signal, value in flags.items():
1148 if value:
1149 ctx.status |= _SIGNALS[signal]
1150 else:
1151 self.flags = flags
1152
1153 def clear_flags(self):
1154 self._ctx.status = 0
1155
1156 def clear_traps(self):
1157 self._ctx.traps = 0
1158
1159 @property
1160 def prec(self):
1161 return self._ctx.prec
1162 @prec.setter
1163 def prec(self, value):
1164 if not _mpdec.mpd_qsetprec(self._ctx, value):
1165 raise ValueError("valid range for prec is [1, MAX_PREC]")
1166
1167 @property
1168 def clamp(self):
1169 return self._ctx.clamp
1170 @clamp.setter
1171 def clamp(self, value):
1172 if not _mpdec.mpd_qsetclamp(self._ctx, value):
1173 raise ValueError("valid values for clamp are 0 or 1")
1174
1175 @property
1176 def rounding(self):
1177 return next(name
1178 for (name, value) in _ROUNDINGS.items()
1179 if value==self._ctx.round)
1180 @rounding.setter
1181 def rounding(self, value):
1182 if value not in _ROUNDINGS:
1183 raise TypeError(
1184 "valid values for rounding are:\n"
1185 "[ROUND_CEILING, ROUND_FLOOR, ROUND_UP, ROUND_DOWN,\n"
1186 "ROUND_HALF_UP, ROUND_HALF_DOWN, ROUND_HALF_EVEN,\n"
1187 "ROUND_05UP]")
1188 if not _mpdec.mpd_qsetround(self._ctx, _ROUNDINGS[value]):
1189 raise RuntimeError("internal error while setting rounding")
1190
1191 @property
1192 def Emin(self):
1193 return self._ctx.emin
1194 @Emin.setter
1195 def Emin(self, value):
1196 if not _mpdec.mpd_qsetemin(self._ctx, value):
1197 raise ValueError("valid range for Emin is [MIN_EMIN, 0]")
1198
1199 @property
1200 def Emax(self):
1201 return self._ctx.emax
1202 @Emax.setter
1203 def Emax(self, value):
1204 if not _mpdec.mpd_qsetemax(self._ctx, value):
1205 raise ValueError("valid range for Emax is [0, MAX_EMAX]")
1206
1207 @property
1208 def flags(self):
1209 return _SignalDict(self._ctx, 'status')
1210 @flags.setter
1211 def flags(self, value):
1212 if not isinstance(value, _collections_abc.Mapping):
1213 raise TypeError
1214 if len(value) != len(_SIGNALS):
1215 raise KeyError("Invalid signal dict")
1216 for signal, value in value.items():
1217 if value:
1218 self._ctx.status |= _SIGNALS[signal]
1219
1220 @property
1221 def traps(self):
1222 return _SignalDict(self._ctx, 'traps')
1223 @traps.setter
1224 def traps(self, value):
1225 if not isinstance(value, _collections_abc.Mapping):
1226 raise TypeError
1227 if len(value) != len(_SIGNALS):
1228 raise KeyError("Invalid signal dict")
1229 for signal, value in value.items():
1230 if value:
1231 self._ctx.traps |= _SIGNALS[signal]
1232
1233 @property
1234 def capitals(self):
1235 return self._capitals
1236 @capitals.setter
1237 def capitals(self, value):
1238 if not isinstance(value, int):
1239 raise TypeError
1240 if value not in (0, 1):
1241 raise ValueError("valid values for capitals are 0 or 1")
1242 self._capitals = value
1243
1244 def __repr__(self):
1245 ctx = self._ctx
1246 return ("Context(prec=%s, rounding=%s, Emin=%s, Emax=%s, "
1247 "capitals=%s, clamp=%s, flags=%s, traps=%s)" % (
1248 ctx.prec, self.rounding,
1249 ctx.emin, ctx.emax,
1250 self._capitals, ctx.clamp,
1251 self.flags, self.traps))
1252
1253 def radix(self):
1254 return Decimal(10)
1255
1256 def Etiny(self):
1257 return _mpdec.mpd_etiny(self._ctx)
1258
1259 def Etop(self):
1260 return _mpdec.mpd_etop(self._ctx)
1261
1262 def is_canonical(self, a):
1263 if not isinstance(a, Decimal):
1264 raise TypeError("is_canonical requires a Decimal as an argument.")
1265 return a.is_canonical()
1266
1267 def canonical(self, a):
1268 if not isinstance(a, Decimal):
1269 raise TypeError("argument must be a Decimal")
1270 return a
1271
1272 def copy(self):
1273 other = Context()
1274 other._ctx[0] = self._ctx[0]
1275 other._capitals = self._capitals
1276 return other
1277
1278 def __copy__(self):
1279 return self.copy()
1280
1281 def __reduce__(self):
1282 return (type(self), (
1283 self.prec, self.rounding, self.Emin, self.Emax,
1284 self._capitals, self.clamp,
1285 self.flags._as_list(),
1286 self.traps._as_list()))
1287
1288 def _add_status(self, status):
1289 self._ctx.status |= status
1290 if self._ctx.status & _mpdec.MPD_Malloc_error:
1291 raise MemoryError()
1292 trapped = self._ctx.traps & status
1293 if trapped:
1294 for exception, flag in _SIGNALS.items():
1295 if trapped & flag:
1296 raise exception
1297 raise RuntimeError("Invalid error flag", trapped)
1298
1299 def create_decimal(self, num="0"):
1300 """Creates a new Decimal instance but using self as context.
1301
1302 This method implements the to-number operation of the
1303 IBM Decimal specification."""
1304
1305 if isinstance(num, str) and (num != num.strip() or '_' in num):
1306 num = '' # empty string triggers ConversionSyntax
1307 return Decimal._from_object(num, self, exact=False)
1308
1309 def create_decimal_from_float(self, f):
1310 return Decimal._from_float(f, self, exact=False)
1311
1312 # operations
1313 def _convert_unaryop(self, a, *, strict=True):
1314 if isinstance(a, Decimal):
1315 return a
1316 elif isinstance(a, int):
1317 return Decimal._from_int(a, self)
1318 if strict:
1319 raise TypeError("Unable to convert %s to Decimal" % (a,))
1320 else:
1321 return NotImplemented
1322
1323 def _convert_binop(self, a, b, *, strict=True):
1324 a = self._convert_unaryop(a, strict=strict)
1325 b = self._convert_unaryop(b, strict=strict)
1326 if b is NotImplemented:
1327 return b, b
1328 return a, b
1329
1330 def _make_unary_method(name, mpd_func_name):
1331 mpd_func = getattr(_mpdec, mpd_func_name)
1332
1333 def method(self, a, *, strict=True):
1334 a = self._convert_unaryop(a, strict=strict)
1335 if a is NotImplemented:
1336 return NotImplemented
1337 res = Decimal._new_empty()
1338 with _CatchStatus(self) as (ctx, status_ptr):
1339 mpd_func(res._mpd, a._mpd, ctx, status_ptr)
1340 return res
1341 method.__name__ = name
1342 return method
1343
1344 def _make_unary_method_noctx(name, mpd_func_name):
1345 mpd_func = getattr(_mpdec, mpd_func_name)
1346
1347 def method(self, a, *, strict=True):
1348 a = self._convert_unaryop(a, strict=strict)
1349 if a is NotImplemented:
1350 return NotImplemented
1351 res = Decimal._new_empty()
1352 with _CatchStatus(self) as (ctx, status_ptr):
1353 mpd_func(res._mpd, a._mpd, status_ptr)
1354 return res
1355 method.__name__ = name
1356 return method
1357
1358 def _make_bool_method(name, mpd_func_name):
1359 mpd_func = getattr(_mpdec, mpd_func_name)
1360
1361 def method(self, a):
1362 a = self._convert_unaryop(a)
1363 return bool(mpd_func(a._mpd, self._ctx))
1364 method.__name__ = name
1365 return method
1366
1367 def _make_bool_method_noctx(name, mpd_func_name):
1368 mpd_func = getattr(_mpdec, mpd_func_name)
1369
1370 def method(self, a):
1371 a = self._convert_unaryop(a)
1372 return bool(mpd_func(a._mpd))
1373 method.__name__ = name
1374 return method
1375
1376 def _make_binary_method(name, mpd_func_name):
1377 mpd_func = getattr(_mpdec, mpd_func_name)
1378
1379 def method(self, a, b, *, strict=True):
1380 a, b = self._convert_binop(a, b, strict=strict)
1381 if a is NotImplemented:
1382 return NotImplemented
1383 res = Decimal._new_empty()
1384 with _CatchStatus(self) as (ctx, status_ptr):
1385 mpd_func(res._mpd, a._mpd, b._mpd, ctx, status_ptr)
1386 return res
1387 method.__name__ = name
1388 return method
1389
1390 def _make_binary_bool_method(name, mpd_func_name):
1391 mpd_func = getattr(_mpdec, mpd_func_name)
1392
1393 def method(self, a, b):
1394 a, b = self._convert_binop(a, b)
1395 return bool(mpd_func(a._mpd, b._mpd))
1396 method.__name__ = name
1397 return method
1398
1399 def _make_binary_method_noctx(name, mpd_func_name):
1400 mpd_func = getattr(_mpdec, mpd_func_name)
1401
1402 def method(self, a, b, *, strict=True):
1403 a, b = self._convert_binop(a, b, strict=strict)
1404 if a is NotImplemented:
1405 return NotImplemented
1406 res = Decimal._new_empty()
1407 with _CatchStatus(self) as (ctx, status_ptr):
1408 mpd_func(res._mpd, a._mpd, b._mpd, status_ptr)
1409 return res
1410 method.__name__ = name
1411 return method
1412
1413 def _make_binary_method_nostatus(name, mpd_func_name):
1414 mpd_func = getattr(_mpdec, mpd_func_name)
1415
1416 def method(self, a, b, *, strict=True):
1417 a, b = self._convert_binop(a, b, strict=strict)
1418 if a is NotImplemented:
1419 return NotImplemented
1420 res = Decimal._new_empty()
1421 mpd_func(res._mpd, a._mpd, b._mpd)
1422 return res
1423 method.__name__ = name
1424 return method
1425
1426 abs = _make_unary_method('abs', 'mpd_qabs')
1427 plus = _make_unary_method('plus', 'mpd_qplus')
1428 minus = _make_unary_method('minus', 'mpd_qminus')
1429 sqrt = _make_unary_method('sqrt', 'mpd_qsqrt')
1430 exp = _make_unary_method('exp', 'mpd_qexp')
1431 ln = _make_unary_method('ln', 'mpd_qln')
1432 log10 = _make_unary_method('log10', 'mpd_qlog10')
1433 logb = _make_unary_method('logb', 'mpd_qlogb')
1434 logical_invert = _make_unary_method('logical_invert', 'mpd_qinvert')
1435 normalize = _make_unary_method('normalize', 'mpd_qreduce')
1436
1437 add = _make_binary_method('add', 'mpd_qadd')
1438 subtract = _make_binary_method('add', 'mpd_qsub')
1439 multiply = _make_binary_method('multiply', 'mpd_qmul')
1440 divide = _make_binary_method('divide', 'mpd_qdiv')
1441 divide_int = _make_binary_method('divide_int', 'mpd_qdivint')
1442 remainder = _make_binary_method('remainder', 'mpd_qrem')
1443 remainder_near = _make_binary_method('remainder_near', 'mpd_qrem_near')
1444 copy_sign = _make_binary_method_noctx('copy_sign', 'mpd_qcopy_sign')
1445 copy_abs = _make_unary_method_noctx('copy_abs', 'mpd_qcopy_abs')
1446 copy_negate = _make_unary_method_noctx('copy_negate', 'mpd_qcopy_negate')
1447
1448 compare = _make_binary_method('compare', 'mpd_qcompare')
1449 compare_signal = _make_binary_method('compare_signal',
1450 'mpd_qcompare_signal')
1451 compare_total = _make_binary_method_nostatus('compare_total',
1452 'mpd_compare_total')
1453 compare_total_mag = _make_binary_method_nostatus('compare_total_mag',
1454 'mpd_compare_total_mag')
1455 logical_and = _make_binary_method('logical_and', 'mpd_qand')
1456 logical_or = _make_binary_method('logical_or', 'mpd_qor')
1457 logical_xor = _make_binary_method('logical_xor', 'mpd_qxor')
1458 max = _make_binary_method('max', 'mpd_qmax')
1459 max_mag = _make_binary_method('max_mag', 'mpd_qmax_mag')
1460 min = _make_binary_method('min', 'mpd_qmin')
1461 min_mag = _make_binary_method('min_mag', 'mpd_qmin_mag')
1462 next_minus = _make_unary_method('next_minus', 'mpd_qnext_minus')
1463 next_plus = _make_unary_method('next_plus', 'mpd_qnext_plus')
1464 next_toward = _make_binary_method('next_toward', 'mpd_qnext_toward')
1465 rotate = _make_binary_method('rotate', 'mpd_qrotate')
1466 same_quantum = _make_binary_bool_method('same_quantum', 'mpd_same_quantum')
1467 scaleb = _make_binary_method('scaleb', 'mpd_qscaleb')
1468 shift = _make_binary_method('shift', 'mpd_qshift')
1469 quantize = _make_binary_method('quantize', 'mpd_qquantize')
1470
1471 is_normal = _make_bool_method('is_normal', 'mpd_isnormal')
1472 is_signed = _make_bool_method_noctx('is_signed', 'mpd_issigned')
1473 is_zero = _make_bool_method_noctx('is_signed', 'mpd_iszero')
1474 is_subnormal = _make_bool_method('is_subnormal', 'mpd_issubnormal')
1475 is_nan = _make_bool_method_noctx('is_qnan', 'mpd_isnan')
1476 is_snan = _make_bool_method_noctx('is_qnan', 'mpd_issnan')
1477 is_qnan = _make_bool_method_noctx('is_qnan', 'mpd_isqnan')
1478 is_finite = _make_bool_method_noctx('is_finite', 'mpd_isfinite')
1479 is_infinite = _make_bool_method_noctx('is_infinite', 'mpd_isinfinite')
1480
1481 def _apply(self, a):
1482 # Apply the context to the input operand.
1483 a = self._convert_unaryop(a)
1484 result = Decimal._new_empty()
1485 with _CatchStatus(self) as (ctx, status_ptr):
1486 _mpdec.mpd_qcopy(result._mpd, a._mpd, status_ptr)
1487 _mpdec.mpd_qfinalize(result._mpd, ctx, status_ptr)
1488 return result
1489
1490 def divmod(self, a, b, *, strict=True):
1491 a, b = self._convert_binop(a, b, strict=strict)
1492 if a is NotImplemented:
1493 return NotImplemented
1494 q = Decimal._new_empty()
1495 r = Decimal._new_empty()
1496 with _CatchStatus(self) as (ctx, status_ptr):
1497 _mpdec.mpd_qdivmod(q._mpd, r._mpd, a._mpd, b._mpd,
1498 ctx, status_ptr)
1499 return q, r
1500
1501 def power(self, a, b, modulo=None, *, strict=True):
1502 a, b = self._convert_binop(a, b, strict=strict)
1503 if a is NotImplemented:
1504 return NotImplemented
1505 if modulo is not None:
1506 modulo = self._convert_unaryop(modulo, strict=strict)
1507 if modulo is NotImplemented:
1508 return NotImplemented
1509 res = Decimal._new_empty()
1510 with _CatchStatus(self) as (ctx, status_ptr):
1511 if modulo is not None:
1512 _mpdec.mpd_qpowmod(res._mpd, a._mpd, b._mpd, modulo._mpd,
1513 ctx, status_ptr)
1514 else:
1515 _mpdec.mpd_qpow(res._mpd, a._mpd, b._mpd,
1516 ctx, status_ptr)
1517 return res
1518
1519 to_integral = _make_unary_method('to_integral', 'mpd_qround_to_int')
1520 to_integral_value = to_integral
1521 to_integral_exact = _make_unary_method('to_integral_exact',
1522 'mpd_qround_to_intx')
1523
1524 def fma(self, a, b, c):
1525 a = self._convert_unaryop(a)
1526 b = self._convert_unaryop(b)
1527 c = self._convert_unaryop(c)
1528 res = Decimal._new_empty()
1529 with _CatchStatus(self) as (ctx, status_ptr):
1530 _mpdec.mpd_qfma(res._mpd, a._mpd, b._mpd, c._mpd,
1531 ctx, status_ptr)
1532 return res
1533
1534 def copy_decimal(self, a):
1535 return self._convert_unaryop(a)
1536
1537 def number_class(self, a):
1538 a = self._convert_unaryop(a)
1539 cp = _mpdec.mpd_class(a._mpd, self._ctx)
1540 return _ffi.string(cp).decode()
1541
1542 def to_eng_string(self, a):
1543 a = self._convert_unaryop(a)
1544 output = _mpdec.mpd_to_eng(a._mpd, self._capitals)
1545 if not output:
1546 raise MemoryError
1547 try:
1548 result = _ffi.string(output)
1549 finally:
1550 _mpdec.mpd_free(output)
1551 return result.decode()
1552
1553 def to_sci_string(self, a):
1554 a = self._convert_unaryop(a)
1555 output = _mpdec.mpd_to_sci(a._mpd, self._capitals)
1556 if not output:
1557 raise MemoryError
1558 try:
1559 result = _ffi.string(output)
1560 finally:
1561 _mpdec.mpd_free(output)
1562 return result.decode()
1563
1564 if _sys.maxsize < 2**63-1:
1565 def _unsafe_setprec(self, value):
1566 _unsafe_check('prec', 1, 1070000000, value)
1567 self._ctx.prec = value
1568
1569 def _unsafe_setemin(self, value):
1570 _unsafe_check('emin', -1070000000, 0, value)
1571 self._ctx.emin = value
1572
1573 def _unsafe_setemax(self, value):
1574 _unsafe_check('emax', 0, 1070000000, value)
1575 self._ctx.emax = value
1576
1577
1578 class _SignalDict(_collections_abc.MutableMapping):
1579
1580 def __init__(self, ctx, attrname):
1581 self.ctx = ctx
1582 self.attrname = attrname
1583
1584 def __repr__(self):
1585 value = getattr(self.ctx, self.attrname)
1586 buf = _ffi.new("char[]", _mpdec.MPD_MAX_SIGNAL_LIST)
1587 n = _mpdec.mpd_lsnprint_signals(buf, len(buf), value,
1588 _mpdec.dec_signal_string)
1589 if not 0 <= n < len(buf):
1590 raise SystemError("flags repr")
1591 return _ffi.buffer(buf, n)[:].decode()
1592
1593 def _as_list(self):
1594 value = getattr(self.ctx, self.attrname)
1595 names = []
1596 for name, flag in _SIGNALS.items():
1597 if value & flag:
1598 names.append(name)
1599 return names
1600
1601 def _as_dict(self):
1602 value = getattr(self.ctx, self.attrname)
1603 return {name: bool(value & flag)
1604 for (name, flag) in _SIGNALS.items()}
1605
1606 def copy(self):
1607 return self._as_dict()
1608
1609 def __len__(self):
1610 return len(_SIGNALS)
1611
1612 def __iter__(self):
1613 return iter(_SIGNALS)
1614
1615 def __getitem__(self, key):
1616 return bool(getattr(self.ctx, self.attrname) & _SIGNALS[key])
1617
1618 def __setitem__(self, key, value):
1619 if value:
1620 setattr(self.ctx, self.attrname,
1621 getattr(self.ctx, self.attrname) | _SIGNALS[key])
1622 else:
1623 setattr(self.ctx, self.attrname,
1624 getattr(self.ctx, self.attrname) & ~_SIGNALS[key])
1625
1626 def __delitem__(self, key):
1627 raise ValueError("signal keys cannot be deleted")
1628
1629
1630 class _CatchConversions:
1631 def __init__(self, mpd, context, exact):
1632 self.mpd = mpd
1633 self.context = _getcontext(context)
1634 self.exact = exact
1635
1636 def __enter__(self):
1637 if self.exact:
1638 self.ctx = _ffi.new("struct mpd_context_t*")
1639 _mpdec.mpd_maxcontext(self.ctx)
1640 else:
1641 self.ctx = self.context._ctx
1642 self.status_ptr = _ffi.new("uint32_t*")
1643 return self.ctx, self.status_ptr
1644
1645 def __exit__(self, *args):
1646 if self.exact:
1647 # we want exact results
1648 status = self.status_ptr[0]
1649 if status & (_mpdec.MPD_Inexact |
1650 _mpdec.MPD_Rounded |
1651 _mpdec.MPD_Clamped):
1652 _mpdec.mpd_seterror(
1653 self.mpd, _mpdec.MPD_Invalid_operation, self.status_ptr)
1654 status = self.status_ptr[0]
1655 if self.exact:
1656 status &= _mpdec.MPD_Errors
1657 # May raise a DecimalException
1658 self.context._add_status(status)
1659
1660 class _CatchStatus:
1661 def __init__(self, context):
1662 self.context = context
1663
1664 def __enter__(self):
1665 self.status_ptr = _ffi.new("uint32_t*")
1666 return self.context._ctx, self.status_ptr
1667
1668 def __exit__(self, *args):
1669 status = self.status_ptr[0]
1670 # May raise a DecimalException
1671 self.context._add_status(status)
1672
1673 ##### Setup Specific Contexts ############################################
1674
1675 # The default context prototype used by Context()
1676 # Is mutable, so that new contexts can have different default values
1677
1678 DefaultContext = Context(
1679 prec=28, rounding=ROUND_HALF_EVEN,
1680 traps=[DivisionByZero, Overflow, InvalidOperation],
1681 flags=[],
1682 Emax=999999,
1683 Emin=-999999,
1684 capitals=1,
1685 clamp=0
1686 )
1687
1688 # Pre-made alternate contexts offered by the specification
1689 # Don't change these; the user should be able to select these
1690 # contexts and be able to reproduce results from other implementations
1691 # of the spec.
1692
1693 BasicContext = Context(
1694 prec=9, rounding=ROUND_HALF_UP,
1695 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
1696 flags=[],
1697 )
1698
1699 ExtendedContext = Context(
1700 prec=9, rounding=ROUND_HALF_EVEN,
1701 traps=[],
1702 flags=[],
1703 )