Debian Codegraph @

Modules/_decimal/_decimal.c

raw
1 /*
2 * Copyright (c) 2008-2012 Stefan Krah. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25 * SUCH DAMAGE.
26 */
27
28 #ifndef Py_BUILD_CORE_BUILTIN
29 # define Py_BUILD_CORE_MODULE 1
30 #endif
31
32 #include <Python.h>
33 #include "pycore_long.h" // _PyLong_IsZero()
34 #include "pycore_pystate.h" // _PyThreadState_GET()
35 #include "pycore_typeobject.h"
36 #include "complexobject.h"
37
38 #include <mpdecimal.h>
39
40 // Reuse config from mpdecimal.h if present.
41 #if defined(MPD_CONFIG_64)
42 #ifndef CONFIG_64
43 #define CONFIG_64 MPD_CONFIG_64
44 #endif
45 #elif defined(MPD_CONFIG_32)
46 #ifndef CONFIG_32
47 #define CONFIG_32 MPD_CONFIG_32
48 #endif
49 #endif
50
51 #include <ctype.h> // isascii()
52 #include <stdlib.h>
53
54 #include "docstrings.h"
55
56 #ifdef EXTRA_FUNCTIONALITY
57 #define _PY_DEC_ROUND_GUARD MPD_ROUND_GUARD
58 #else
59 #define _PY_DEC_ROUND_GUARD (MPD_ROUND_GUARD-1)
60 #endif
61
62 struct PyDecContextObject;
63 struct DecCondMap;
64
65 typedef struct {
66 PyTypeObject *PyDecContextManager_Type;
67 PyTypeObject *PyDecContext_Type;
68 PyTypeObject *PyDecSignalDictMixin_Type;
69 PyTypeObject *PyDec_Type;
70 PyTypeObject *PyDecSignalDict_Type;
71 PyTypeObject *DecimalTuple;
72
73 /* Top level Exception; inherits from ArithmeticError */
74 PyObject *DecimalException;
75
76 #ifndef WITH_DECIMAL_CONTEXTVAR
77 /* Key for thread state dictionary */
78 PyObject *tls_context_key;
79 /* Invariant: NULL or a strong reference to the most recently accessed
80 thread local context. */
81 struct PyDecContextObject *cached_context; /* Not borrowed */
82 #else
83 PyObject *current_context_var;
84 #endif
85
86 /* Template for creating new thread contexts, calling Context() without
87 * arguments and initializing the module_context on first access. */
88 PyObject *default_context_template;
89
90 /* Basic and extended context templates */
91 PyObject *basic_context_template;
92 PyObject *extended_context_template;
93
94 PyObject *round_map[_PY_DEC_ROUND_GUARD];
95
96 /* Convert rationals for comparison */
97 PyObject *Rational;
98
99 /* Invariant: NULL or pointer to _pydecimal.Decimal */
100 PyObject *PyDecimal;
101
102 PyObject *SignalTuple;
103
104 struct DecCondMap *signal_map;
105 struct DecCondMap *cond_map;
106
107 /* External C-API functions */
108 binaryfunc _py_long_multiply;
109 binaryfunc _py_long_floor_divide;
110 ternaryfunc _py_long_power;
111 unaryfunc _py_float_abs;
112 PyCFunction _py_long_bit_length;
113 PyCFunction _py_float_as_integer_ratio;
114 } decimal_state;
115
116 static inline decimal_state *
117 get_module_state(PyObject *mod)
118 {
119 decimal_state *state = _PyModule_GetState(mod);
120 assert(state != NULL);
121 return state;
122 }
123
124 static struct PyModuleDef _decimal_module;
125
126 static inline decimal_state *
127 get_module_state_by_def(PyTypeObject *tp)
128 {
129 PyObject *mod = PyType_GetModuleByDef(tp, &_decimal_module);
130 assert(mod != NULL);
131 return get_module_state(mod);
132 }
133
134 static inline decimal_state *
135 find_state_left_or_right(PyObject *left, PyObject *right)
136 {
137 PyObject *mod = _PyType_GetModuleByDef2(Py_TYPE(left), Py_TYPE(right),
138 &_decimal_module);
139 assert(mod != NULL);
140 return get_module_state(mod);
141 }
142
143 static inline decimal_state *
144 find_state_ternary(PyObject *left, PyObject *right, PyObject *modulus)
145 {
146 PyObject *mod = _PyType_GetModuleByDef3(Py_TYPE(left), Py_TYPE(right), Py_TYPE(modulus),
147 &_decimal_module);
148 assert(mod != NULL);
149 return get_module_state(mod);
150 }
151
152
153 #if !defined(MPD_VERSION_HEX) || MPD_VERSION_HEX < 0x02050000
154 #error "libmpdec version >= 2.5.0 required"
155 #endif
156
157
158 /*
159 * Type sizes with assertions in mpdecimal.h and pyport.h:
160 * sizeof(size_t) == sizeof(Py_ssize_t)
161 * sizeof(size_t) == sizeof(mpd_uint_t) == sizeof(mpd_ssize_t)
162 */
163
164 #ifdef TEST_COVERAGE
165 #undef Py_LOCAL_INLINE
166 #define Py_LOCAL_INLINE Py_LOCAL
167 #endif
168
169 #define MPD_Float_operation MPD_Not_implemented
170
171 #define BOUNDS_CHECK(x, MIN, MAX) x = (x < MIN || MAX < x) ? MAX : x
172
173 #if defined(__GNUC__) && !defined(__INTEL_COMPILER)
174 #define UNUSED __attribute__((unused))
175 #else
176 #define UNUSED
177 #endif
178
179 /* _Py_DEC_MINALLOC >= MPD_MINALLOC */
180 #define _Py_DEC_MINALLOC 4
181
182 typedef struct {
183 PyObject_HEAD
184 Py_hash_t hash;
185 mpd_t dec;
186 mpd_uint_t data[_Py_DEC_MINALLOC];
187 } PyDecObject;
188
189 typedef struct {
190 PyObject_HEAD
191 uint32_t *flags;
192 } PyDecSignalDictObject;
193
194 typedef struct PyDecContextObject {
195 PyObject_HEAD
196 mpd_context_t ctx;
197 PyObject *traps;
198 PyObject *flags;
199 int capitals;
200 PyThreadState *tstate;
201 } PyDecContextObject;
202
203 typedef struct {
204 PyObject_HEAD
205 PyObject *local;
206 PyObject *global;
207 } PyDecContextManagerObject;
208
209 #undef MPD
210 #undef CTX
211 #define PyDec_CheckExact(st, v) Py_IS_TYPE(v, (st)->PyDec_Type)
212 #define PyDec_Check(st, v) PyObject_TypeCheck(v, (st)->PyDec_Type)
213 #define PyDecSignalDict_Check(st, v) Py_IS_TYPE(v, (st)->PyDecSignalDict_Type)
214 #define PyDecContext_Check(st, v) PyObject_TypeCheck(v, (st)->PyDecContext_Type)
215 #define MPD(v) (&((PyDecObject *)v)->dec)
216 #define SdFlagAddr(v) (((PyDecSignalDictObject *)v)->flags)
217 #define SdFlags(v) (*((PyDecSignalDictObject *)v)->flags)
218 #define CTX(v) (&((PyDecContextObject *)v)->ctx)
219 #define CtxCaps(v) (((PyDecContextObject *)v)->capitals)
220
221
222 Py_LOCAL_INLINE(PyObject *)
223 incr_true(void)
224 {
225 return Py_NewRef(Py_True);
226 }
227
228 Py_LOCAL_INLINE(PyObject *)
229 incr_false(void)
230 {
231 return Py_NewRef(Py_False);
232 }
233
234 /* Error codes for functions that return signals or conditions */
235 #define DEC_INVALID_SIGNALS (MPD_Max_status+1U)
236 #define DEC_ERR_OCCURRED (DEC_INVALID_SIGNALS<<1)
237 #define DEC_ERRORS (DEC_INVALID_SIGNALS|DEC_ERR_OCCURRED)
238
239 typedef struct DecCondMap {
240 const char *name; /* condition or signal name */
241 const char *fqname; /* fully qualified name */
242 uint32_t flag; /* libmpdec flag */
243 PyObject *ex; /* corresponding exception */
244 } DecCondMap;
245
246 /* Exceptions that correspond to IEEE signals */
247 #define SUBNORMAL 5
248 #define INEXACT 6
249 #define ROUNDED 7
250 #define SIGNAL_MAP_LEN 9
251 static DecCondMap signal_map_template[] = {
252 {"InvalidOperation", "decimal.InvalidOperation", MPD_IEEE_Invalid_operation, NULL},
253 {"FloatOperation", "decimal.FloatOperation", MPD_Float_operation, NULL},
254 {"DivisionByZero", "decimal.DivisionByZero", MPD_Division_by_zero, NULL},
255 {"Overflow", "decimal.Overflow", MPD_Overflow, NULL},
256 {"Underflow", "decimal.Underflow", MPD_Underflow, NULL},
257 {"Subnormal", "decimal.Subnormal", MPD_Subnormal, NULL},
258 {"Inexact", "decimal.Inexact", MPD_Inexact, NULL},
259 {"Rounded", "decimal.Rounded", MPD_Rounded, NULL},
260 {"Clamped", "decimal.Clamped", MPD_Clamped, NULL},
261 {NULL}
262 };
263
264 /* Exceptions that inherit from InvalidOperation */
265 static DecCondMap cond_map_template[] = {
266 {"InvalidOperation", "decimal.InvalidOperation", MPD_Invalid_operation, NULL},
267 {"ConversionSyntax", "decimal.ConversionSyntax", MPD_Conversion_syntax, NULL},
268 {"DivisionImpossible", "decimal.DivisionImpossible", MPD_Division_impossible, NULL},
269 {"DivisionUndefined", "decimal.DivisionUndefined", MPD_Division_undefined, NULL},
270 {"InvalidContext", "decimal.InvalidContext", MPD_Invalid_context, NULL},
271 #ifdef EXTRA_FUNCTIONALITY
272 {"MallocError", "decimal.MallocError", MPD_Malloc_error, NULL},
273 #endif
274 {NULL}
275 };
276
277 /* Return a duplicate of DecCondMap template */
278 static inline DecCondMap *
279 dec_cond_map_init(DecCondMap *template, Py_ssize_t size)
280 {
281 DecCondMap *cm;
282 cm = PyMem_Malloc(size);
283 if (cm == NULL) {
284 PyErr_NoMemory();
285 return NULL;
286 }
287
288 memcpy(cm, template, size);
289 return cm;
290 }
291
292 static const char *dec_signal_string[MPD_NUM_FLAGS] = {
293 "Clamped",
294 "InvalidOperation",
295 "DivisionByZero",
296 "InvalidOperation",
297 "InvalidOperation",
298 "InvalidOperation",
299 "Inexact",
300 "InvalidOperation",
301 "InvalidOperation",
302 "InvalidOperation",
303 "FloatOperation",
304 "Overflow",
305 "Rounded",
306 "Subnormal",
307 "Underflow",
308 };
309
310 static const char *invalid_rounding_err =
311 "valid values for rounding are:\n\
312 [ROUND_CEILING, ROUND_FLOOR, ROUND_UP, ROUND_DOWN,\n\
313 ROUND_HALF_UP, ROUND_HALF_DOWN, ROUND_HALF_EVEN,\n\
314 ROUND_05UP]";
315
316 static const char *invalid_signals_err =
317 "valid values for signals are:\n\
318 [InvalidOperation, FloatOperation, DivisionByZero,\n\
319 Overflow, Underflow, Subnormal, Inexact, Rounded,\n\
320 Clamped]";
321
322 #ifdef EXTRA_FUNCTIONALITY
323 static const char *invalid_flags_err =
324 "valid values for _flags or _traps are:\n\
325 signals:\n\
326 [DecIEEEInvalidOperation, DecFloatOperation, DecDivisionByZero,\n\
327 DecOverflow, DecUnderflow, DecSubnormal, DecInexact, DecRounded,\n\
328 DecClamped]\n\
329 conditions which trigger DecIEEEInvalidOperation:\n\
330 [DecInvalidOperation, DecConversionSyntax, DecDivisionImpossible,\n\
331 DecDivisionUndefined, DecFpuError, DecInvalidContext, DecMallocError]";
332 #endif
333
334 static int
335 value_error_int(const char *mesg)
336 {
337 PyErr_SetString(PyExc_ValueError, mesg);
338 return -1;
339 }
340
341 static PyObject *
342 value_error_ptr(const char *mesg)
343 {
344 PyErr_SetString(PyExc_ValueError, mesg);
345 return NULL;
346 }
347
348 static int
349 type_error_int(const char *mesg)
350 {
351 PyErr_SetString(PyExc_TypeError, mesg);
352 return -1;
353 }
354
355 static int
356 runtime_error_int(const char *mesg)
357 {
358 PyErr_SetString(PyExc_RuntimeError, mesg);
359 return -1;
360 }
361 #define INTERNAL_ERROR_INT(funcname) \
362 return runtime_error_int("internal error in " funcname)
363
364 static PyObject *
365 runtime_error_ptr(const char *mesg)
366 {
367 PyErr_SetString(PyExc_RuntimeError, mesg);
368 return NULL;
369 }
370 #define INTERNAL_ERROR_PTR(funcname) \
371 return runtime_error_ptr("internal error in " funcname)
372
373 static void
374 dec_traphandler(mpd_context_t *ctx UNUSED) /* GCOV_NOT_REACHED */
375 { /* GCOV_NOT_REACHED */
376 return; /* GCOV_NOT_REACHED */
377 }
378
379 static PyObject *
380 flags_as_exception(decimal_state *state, uint32_t flags)
381 {
382 DecCondMap *cm;
383
384 for (cm = state->signal_map; cm->name != NULL; cm++) {
385 if (flags&cm->flag) {
386 return cm->ex;
387 }
388 }
389
390 INTERNAL_ERROR_PTR("flags_as_exception"); /* GCOV_NOT_REACHED */
391 }
392
393 Py_LOCAL_INLINE(uint32_t)
394 exception_as_flag(decimal_state *state, PyObject *ex)
395 {
396 DecCondMap *cm;
397
398 for (cm = state->signal_map; cm->name != NULL; cm++) {
399 if (cm->ex == ex) {
400 return cm->flag;
401 }
402 }
403
404 PyErr_SetString(PyExc_KeyError, invalid_signals_err);
405 return DEC_INVALID_SIGNALS;
406 }
407
408 static PyObject *
409 flags_as_list(decimal_state *state, uint32_t flags)
410 {
411 PyObject *list;
412 DecCondMap *cm;
413
414 list = PyList_New(0);
415 if (list == NULL) {
416 return NULL;
417 }
418
419 for (cm = state->cond_map; cm->name != NULL; cm++) {
420 if (flags&cm->flag) {
421 if (PyList_Append(list, cm->ex) < 0) {
422 goto error;
423 }
424 }
425 }
426 for (cm = state->signal_map+1; cm->name != NULL; cm++) {
427 if (flags&cm->flag) {
428 if (PyList_Append(list, cm->ex) < 0) {
429 goto error;
430 }
431 }
432 }
433
434 return list;
435
436 error:
437 Py_DECREF(list);
438 return NULL;
439 }
440
441 static PyObject *
442 signals_as_list(decimal_state *state, uint32_t flags)
443 {
444 PyObject *list;
445 DecCondMap *cm;
446
447 list = PyList_New(0);
448 if (list == NULL) {
449 return NULL;
450 }
451
452 for (cm = state->signal_map; cm->name != NULL; cm++) {
453 if (flags&cm->flag) {
454 if (PyList_Append(list, cm->ex) < 0) {
455 Py_DECREF(list);
456 return NULL;
457 }
458 }
459 }
460
461 return list;
462 }
463
464 static uint32_t
465 list_as_flags(decimal_state *state, PyObject *list)
466 {
467 PyObject *item;
468 uint32_t flags, x;
469 Py_ssize_t n, j;
470
471 assert(PyList_Check(list));
472
473 n = PyList_Size(list);
474 flags = 0;
475 for (j = 0; j < n; j++) {
476 item = PyList_GetItem(list, j);
477 x = exception_as_flag(state, item);
478 if (x & DEC_ERRORS) {
479 return x;
480 }
481 flags |= x;
482 }
483
484 return flags;
485 }
486
487 static PyObject *
488 flags_as_dict(decimal_state *state, uint32_t flags)
489 {
490 DecCondMap *cm;
491 PyObject *dict;
492
493 dict = PyDict_New();
494 if (dict == NULL) {
495 return NULL;
496 }
497
498 for (cm = state->signal_map; cm->name != NULL; cm++) {
499 PyObject *b = flags&cm->flag ? Py_True : Py_False;
500 if (PyDict_SetItem(dict, cm->ex, b) < 0) {
501 Py_DECREF(dict);
502 return NULL;
503 }
504 }
505
506 return dict;
507 }
508
509 static uint32_t
510 dict_as_flags(decimal_state *state, PyObject *val)
511 {
512 PyObject *b;
513 DecCondMap *cm;
514 uint32_t flags = 0;
515 int x;
516
517 if (!PyDict_Check(val)) {
518 PyErr_SetString(PyExc_TypeError,
519 "argument must be a signal dict");
520 return DEC_INVALID_SIGNALS;
521 }
522
523 if (PyDict_Size(val) != SIGNAL_MAP_LEN) {
524 PyErr_SetString(PyExc_KeyError,
525 "invalid signal dict");
526 return DEC_INVALID_SIGNALS;
527 }
528
529 for (cm = state->signal_map; cm->name != NULL; cm++) {
530 b = PyDict_GetItemWithError(val, cm->ex);
531 if (b == NULL) {
532 if (PyErr_Occurred()) {
533 return DEC_ERR_OCCURRED;
534 }
535 PyErr_SetString(PyExc_KeyError,
536 "invalid signal dict");
537 return DEC_INVALID_SIGNALS;
538 }
539
540 x = PyObject_IsTrue(b);
541 if (x < 0) {
542 return DEC_ERR_OCCURRED;
543 }
544 if (x == 1) {
545 flags |= cm->flag;
546 }
547 }
548
549 return flags;
550 }
551
552 #ifdef EXTRA_FUNCTIONALITY
553 static uint32_t
554 long_as_flags(PyObject *v)
555 {
556 long x;
557
558 x = PyLong_AsLong(v);
559 if (x == -1 && PyErr_Occurred()) {
560 return DEC_ERR_OCCURRED;
561 }
562 if (x < 0 || x > (long)MPD_Max_status) {
563 PyErr_SetString(PyExc_TypeError, invalid_flags_err);
564 return DEC_INVALID_SIGNALS;
565 }
566
567 return x;
568 }
569 #endif
570
571 static int
572 dec_addstatus(PyObject *context, uint32_t status)
573 {
574 mpd_context_t *ctx = CTX(context);
575 decimal_state *state = get_module_state_by_def(Py_TYPE(context));
576
577 ctx->status |= status;
578 if (status & (ctx->traps|MPD_Malloc_error)) {
579 PyObject *ex, *siglist;
580
581 if (status & MPD_Malloc_error) {
582 PyErr_NoMemory();
583 return 1;
584 }
585
586 ex = flags_as_exception(state, ctx->traps&status);
587 if (ex == NULL) {
588 return 1; /* GCOV_NOT_REACHED */
589 }
590 siglist = flags_as_list(state, ctx->traps&status);
591 if (siglist == NULL) {
592 return 1;
593 }
594
595 PyErr_SetObject(ex, siglist);
596 Py_DECREF(siglist);
597 return 1;
598 }
599 return 0;
600 }
601
602 static int
603 getround(decimal_state *state, PyObject *v)
604 {
605 int i;
606 if (PyUnicode_Check(v)) {
607 for (i = 0; i < _PY_DEC_ROUND_GUARD; i++) {
608 if (v == state->round_map[i]) {
609 return i;
610 }
611 }
612 for (i = 0; i < _PY_DEC_ROUND_GUARD; i++) {
613 if (PyUnicode_Compare(v, state->round_map[i]) == 0) {
614 return i;
615 }
616 }
617 }
618
619 return type_error_int(invalid_rounding_err);
620 }
621
622
623 /******************************************************************************/
624 /* SignalDict Object */
625 /******************************************************************************/
626
627 /* The SignalDict is a MutableMapping that provides access to the
628 mpd_context_t flags, which reside in the context object. When a
629 new context is created, context.traps and context.flags are
630 initialized to new SignalDicts. Once a SignalDict is tied to
631 a context, it cannot be deleted. */
632
633 static const char *INVALID_SIGNALDICT_ERROR_MSG = "invalid signal dict";
634
635 static int
636 signaldict_init(PyObject *self, PyObject *args UNUSED, PyObject *kwds UNUSED)
637 {
638 SdFlagAddr(self) = NULL;
639 return 0;
640 }
641
642 static Py_ssize_t
643 signaldict_len(PyObject *self)
644 {
645 if (SdFlagAddr(self) == NULL) {
646 return value_error_int(INVALID_SIGNALDICT_ERROR_MSG);
647 }
648 return SIGNAL_MAP_LEN;
649 }
650
651 static PyObject *
652 signaldict_iter(PyObject *self)
653 {
654 if (SdFlagAddr(self) == NULL) {
655 return value_error_ptr(INVALID_SIGNALDICT_ERROR_MSG);
656 }
657 decimal_state *state = get_module_state_by_def(Py_TYPE(self));
658 return PyTuple_Type.tp_iter(state->SignalTuple);
659 }
660
661 static PyObject *
662 signaldict_getitem(PyObject *self, PyObject *key)
663 {
664 uint32_t flag;
665 if (SdFlagAddr(self) == NULL) {
666 return value_error_ptr(INVALID_SIGNALDICT_ERROR_MSG);
667 }
668 decimal_state *state = get_module_state_by_def(Py_TYPE(self));
669
670 flag = exception_as_flag(state, key);
671 if (flag & DEC_ERRORS) {
672 return NULL;
673 }
674
675 return SdFlags(self)&flag ? incr_true() : incr_false();
676 }
677
678 static int
679 signaldict_setitem(PyObject *self, PyObject *key, PyObject *value)
680 {
681 uint32_t flag;
682 int x;
683
684 if (SdFlagAddr(self) == NULL) {
685 return value_error_int(INVALID_SIGNALDICT_ERROR_MSG);
686 }
687
688 if (value == NULL) {
689 return value_error_int("signal keys cannot be deleted");
690 }
691
692 decimal_state *state = get_module_state_by_def(Py_TYPE(self));
693 flag = exception_as_flag(state, key);
694 if (flag & DEC_ERRORS) {
695 return -1;
696 }
697
698 x = PyObject_IsTrue(value);
699 if (x < 0) {
700 return -1;
701 }
702
703 if (x == 1) {
704 SdFlags(self) |= flag;
705 }
706 else {
707 SdFlags(self) &= ~flag;
708 }
709
710 return 0;
711 }
712
713 static int
714 signaldict_traverse(PyObject *self, visitproc visit, void *arg)
715 {
716 Py_VISIT(Py_TYPE(self));
717 return 0;
718 }
719
720 static void
721 signaldict_dealloc(PyObject *self)
722 {
723 PyTypeObject *tp = Py_TYPE(self);
724 PyObject_GC_UnTrack(self);
725 tp->tp_free(self);
726 Py_DECREF(tp);
727 }
728
729 static PyObject *
730 signaldict_repr(PyObject *self)
731 {
732 DecCondMap *cm;
733 const char *n[SIGNAL_MAP_LEN]; /* name */
734 const char *b[SIGNAL_MAP_LEN]; /* bool */
735 int i;
736
737 if (SdFlagAddr(self) == NULL) {
738 return value_error_ptr(INVALID_SIGNALDICT_ERROR_MSG);
739 }
740
741 assert(SIGNAL_MAP_LEN == 9);
742
743 decimal_state *state = get_module_state_by_def(Py_TYPE(self));
744 for (cm=state->signal_map, i=0; cm->name != NULL; cm++, i++) {
745 n[i] = cm->fqname;
746 b[i] = SdFlags(self)&cm->flag ? "True" : "False";
747 }
748 return PyUnicode_FromFormat(
749 "{<class '%s'>:%s, <class '%s'>:%s, <class '%s'>:%s, "
750 "<class '%s'>:%s, <class '%s'>:%s, <class '%s'>:%s, "
751 "<class '%s'>:%s, <class '%s'>:%s, <class '%s'>:%s}",
752 n[0], b[0], n[1], b[1], n[2], b[2],
753 n[3], b[3], n[4], b[4], n[5], b[5],
754 n[6], b[6], n[7], b[7], n[8], b[8]);
755 }
756
757 static PyObject *
758 signaldict_richcompare(PyObject *v, PyObject *w, int op)
759 {
760 PyObject *res = Py_NotImplemented;
761
762 decimal_state *state = find_state_left_or_right(v, w);
763 assert(PyDecSignalDict_Check(state, v));
764
765 if ((SdFlagAddr(v) == NULL) || (SdFlagAddr(w) == NULL)) {
766 return value_error_ptr(INVALID_SIGNALDICT_ERROR_MSG);
767 }
768
769 if (op == Py_EQ || op == Py_NE) {
770 if (PyDecSignalDict_Check(state, w)) {
771 res = (SdFlags(v)==SdFlags(w)) ^ (op==Py_NE) ? Py_True : Py_False;
772 }
773 else if (PyDict_Check(w)) {
774 uint32_t flags = dict_as_flags(state, w);
775 if (flags & DEC_ERRORS) {
776 if (flags & DEC_INVALID_SIGNALS) {
777 /* non-comparable: Py_NotImplemented */
778 PyErr_Clear();
779 }
780 else {
781 return NULL;
782 }
783 }
784 else {
785 res = (SdFlags(v)==flags) ^ (op==Py_NE) ? Py_True : Py_False;
786 }
787 }
788 }
789
790 return Py_NewRef(res);
791 }
792
793 static PyObject *
794 signaldict_copy(PyObject *self, PyObject *args UNUSED)
795 {
796 if (SdFlagAddr(self) == NULL) {
797 return value_error_ptr(INVALID_SIGNALDICT_ERROR_MSG);
798 }
799 decimal_state *state = get_module_state_by_def(Py_TYPE(self));
800 return flags_as_dict(state, SdFlags(self));
801 }
802
803
804 static PyMethodDef signaldict_methods[] = {
805 { "copy", (PyCFunction)signaldict_copy, METH_NOARGS, NULL},
806 {NULL, NULL}
807 };
808
809
810 static PyType_Slot signaldict_slots[] = {
811 {Py_tp_dealloc, signaldict_dealloc},
812 {Py_tp_traverse, signaldict_traverse},
813 {Py_tp_repr, signaldict_repr},
814 {Py_tp_hash, PyObject_HashNotImplemented},
815 {Py_tp_getattro, PyObject_GenericGetAttr},
816 {Py_tp_richcompare, signaldict_richcompare},
817 {Py_tp_iter, signaldict_iter},
818 {Py_tp_methods, signaldict_methods},
819 {Py_tp_init, signaldict_init},
820
821 // Mapping protocol
822 {Py_mp_length, signaldict_len},
823 {Py_mp_subscript, signaldict_getitem},
824 {Py_mp_ass_subscript, signaldict_setitem},
825 {0, NULL},
826 };
827
828 static PyType_Spec signaldict_spec = {
829 .name = "decimal.SignalDictMixin",
830 .basicsize = sizeof(PyDecSignalDictObject),
831 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
832 Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE),
833 .slots = signaldict_slots,
834 };
835
836
837 /******************************************************************************/
838 /* Context Object, Part 1 */
839 /******************************************************************************/
840
841 #define Dec_CONTEXT_GET_SSIZE(mem) \
842 static PyObject * \
843 context_get##mem(PyObject *self, void *closure UNUSED) \
844 { \
845 return PyLong_FromSsize_t(mpd_get##mem(CTX(self))); \
846 }
847
848 #define Dec_CONTEXT_GET_ULONG(mem) \
849 static PyObject * \
850 context_get##mem(PyObject *self, void *closure UNUSED) \
851 { \
852 return PyLong_FromUnsignedLong(mpd_get##mem(CTX(self))); \
853 }
854
855 Dec_CONTEXT_GET_SSIZE(prec)
856 Dec_CONTEXT_GET_SSIZE(emax)
857 Dec_CONTEXT_GET_SSIZE(emin)
858 Dec_CONTEXT_GET_SSIZE(clamp)
859
860 #ifdef EXTRA_FUNCTIONALITY
861 Dec_CONTEXT_GET_ULONG(traps)
862 Dec_CONTEXT_GET_ULONG(status)
863 #endif
864
865 static PyObject *
866 context_getround(PyObject *self, void *closure UNUSED)
867 {
868 int i = mpd_getround(CTX(self));
869 decimal_state *state = get_module_state_by_def(Py_TYPE(self));
870
871 return Py_NewRef(state->round_map[i]);
872 }
873
874 static PyObject *
875 context_getcapitals(PyObject *self, void *closure UNUSED)
876 {
877 return PyLong_FromLong(CtxCaps(self));
878 }
879
880 #ifdef EXTRA_FUNCTIONALITY
881 static PyObject *
882 context_getallcr(PyObject *self, void *closure UNUSED)
883 {
884 return PyLong_FromLong(mpd_getcr(CTX(self)));
885 }
886 #endif
887
888 static PyObject *
889 context_getetiny(PyObject *self, PyObject *dummy UNUSED)
890 {
891 return PyLong_FromSsize_t(mpd_etiny(CTX(self)));
892 }
893
894 static PyObject *
895 context_getetop(PyObject *self, PyObject *dummy UNUSED)
896 {
897 return PyLong_FromSsize_t(mpd_etop(CTX(self)));
898 }
899
900 static int
901 context_setprec(PyObject *self, PyObject *value, void *closure UNUSED)
902 {
903 mpd_context_t *ctx;
904 mpd_ssize_t x;
905
906 x = PyLong_AsSsize_t(value);
907 if (x == -1 && PyErr_Occurred()) {
908 return -1;
909 }
910
911 ctx = CTX(self);
912 if (!mpd_qsetprec(ctx, x)) {
913 return value_error_int(
914 "valid range for prec is [1, MAX_PREC]");
915 }
916
917 return 0;
918 }
919
920 static int
921 context_setemin(PyObject *self, PyObject *value, void *closure UNUSED)
922 {
923 mpd_context_t *ctx;
924 mpd_ssize_t x;
925
926 x = PyLong_AsSsize_t(value);
927 if (x == -1 && PyErr_Occurred()) {
928 return -1;
929 }
930
931 ctx = CTX(self);
932 if (!mpd_qsetemin(ctx, x)) {
933 return value_error_int(
934 "valid range for Emin is [MIN_EMIN, 0]");
935 }
936
937 return 0;
938 }
939
940 static int
941 context_setemax(PyObject *self, PyObject *value, void *closure UNUSED)
942 {
943 mpd_context_t *ctx;
944 mpd_ssize_t x;
945
946 x = PyLong_AsSsize_t(value);
947 if (x == -1 && PyErr_Occurred()) {
948 return -1;
949 }
950
951 ctx = CTX(self);
952 if (!mpd_qsetemax(ctx, x)) {
953 return value_error_int(
954 "valid range for Emax is [0, MAX_EMAX]");
955 }
956
957 return 0;
958 }
959
960 #ifdef CONFIG_32
961 static PyObject *
962 context_unsafe_setprec(PyObject *self, PyObject *value)
963 {
964 mpd_context_t *ctx = CTX(self);
965 mpd_ssize_t x;
966
967 x = PyLong_AsSsize_t(value);
968 if (x == -1 && PyErr_Occurred()) {
969 return NULL;
970 }
971
972 if (x < 1 || x > 1070000000L) {
973 return value_error_ptr(
974 "valid range for unsafe prec is [1, 1070000000]");
975 }
976
977 ctx->prec = x;
978 Py_RETURN_NONE;
979 }
980
981 static PyObject *
982 context_unsafe_setemin(PyObject *self, PyObject *value)
983 {
984 mpd_context_t *ctx = CTX(self);
985 mpd_ssize_t x;
986
987 x = PyLong_AsSsize_t(value);
988 if (x == -1 && PyErr_Occurred()) {
989 return NULL;
990 }
991
992 if (x < -1070000000L || x > 0) {
993 return value_error_ptr(
994 "valid range for unsafe emin is [-1070000000, 0]");
995 }
996
997 ctx->emin = x;
998 Py_RETURN_NONE;
999 }
1000
1001 static PyObject *
1002 context_unsafe_setemax(PyObject *self, PyObject *value)
1003 {
1004 mpd_context_t *ctx = CTX(self);
1005 mpd_ssize_t x;
1006
1007 x = PyLong_AsSsize_t(value);
1008 if (x == -1 && PyErr_Occurred()) {
1009 return NULL;
1010 }
1011
1012 if (x < 0 || x > 1070000000L) {
1013 return value_error_ptr(
1014 "valid range for unsafe emax is [0, 1070000000]");
1015 }
1016
1017 ctx->emax = x;
1018 Py_RETURN_NONE;
1019 }
1020 #endif
1021
1022 static int
1023 context_setround(PyObject *self, PyObject *value, void *closure UNUSED)
1024 {
1025 mpd_context_t *ctx;
1026 int x;
1027
1028 decimal_state *state = get_module_state_by_def(Py_TYPE(self));
1029 x = getround(state, value);
1030 if (x == -1) {
1031 return -1;
1032 }
1033
1034 ctx = CTX(self);
1035 if (!mpd_qsetround(ctx, x)) {
1036 INTERNAL_ERROR_INT("context_setround"); /* GCOV_NOT_REACHED */
1037 }
1038
1039 return 0;
1040 }
1041
1042 static int
1043 context_setcapitals(PyObject *self, PyObject *value, void *closure UNUSED)
1044 {
1045 mpd_ssize_t x;
1046
1047 x = PyLong_AsSsize_t(value);
1048 if (x == -1 && PyErr_Occurred()) {
1049 return -1;
1050 }
1051
1052 if (x != 0 && x != 1) {
1053 return value_error_int(
1054 "valid values for capitals are 0 or 1");
1055 }
1056 CtxCaps(self) = (int)x;
1057
1058 return 0;
1059 }
1060
1061 #ifdef EXTRA_FUNCTIONALITY
1062 static int
1063 context_settraps(PyObject *self, PyObject *value, void *closure UNUSED)
1064 {
1065 mpd_context_t *ctx;
1066 uint32_t flags;
1067
1068 flags = long_as_flags(value);
1069 if (flags & DEC_ERRORS) {
1070 return -1;
1071 }
1072
1073 ctx = CTX(self);
1074 if (!mpd_qsettraps(ctx, flags)) {
1075 INTERNAL_ERROR_INT("context_settraps");
1076 }
1077
1078 return 0;
1079 }
1080 #endif
1081
1082 static int
1083 context_settraps_list(PyObject *self, PyObject *value)
1084 {
1085 mpd_context_t *ctx;
1086 uint32_t flags;
1087 decimal_state *state = get_module_state_by_def(Py_TYPE(self));
1088 flags = list_as_flags(state, value);
1089 if (flags & DEC_ERRORS) {
1090 return -1;
1091 }
1092
1093 ctx = CTX(self);
1094 if (!mpd_qsettraps(ctx, flags)) {
1095 INTERNAL_ERROR_INT("context_settraps_list");
1096 }
1097
1098 return 0;
1099 }
1100
1101 static int
1102 context_settraps_dict(PyObject *self, PyObject *value)
1103 {
1104 mpd_context_t *ctx;
1105 uint32_t flags;
1106
1107 decimal_state *state = get_module_state_by_def(Py_TYPE(self));
1108 if (PyDecSignalDict_Check(state, value)) {
1109 flags = SdFlags(value);
1110 }
1111 else {
1112 flags = dict_as_flags(state, value);
1113 if (flags & DEC_ERRORS) {
1114 return -1;
1115 }
1116 }
1117
1118 ctx = CTX(self);
1119 if (!mpd_qsettraps(ctx, flags)) {
1120 INTERNAL_ERROR_INT("context_settraps_dict");
1121 }
1122
1123 return 0;
1124 }
1125
1126 #ifdef EXTRA_FUNCTIONALITY
1127 static int
1128 context_setstatus(PyObject *self, PyObject *value, void *closure UNUSED)
1129 {
1130 mpd_context_t *ctx;
1131 uint32_t flags;
1132
1133 flags = long_as_flags(value);
1134 if (flags & DEC_ERRORS) {
1135 return -1;
1136 }
1137
1138 ctx = CTX(self);
1139 if (!mpd_qsetstatus(ctx, flags)) {
1140 INTERNAL_ERROR_INT("context_setstatus");
1141 }
1142
1143 return 0;
1144 }
1145 #endif
1146
1147 static int
1148 context_setstatus_list(PyObject *self, PyObject *value)
1149 {
1150 mpd_context_t *ctx;
1151 uint32_t flags;
1152 decimal_state *state = get_module_state_by_def(Py_TYPE(self));
1153
1154 flags = list_as_flags(state, value);
1155 if (flags & DEC_ERRORS) {
1156 return -1;
1157 }
1158
1159 ctx = CTX(self);
1160 if (!mpd_qsetstatus(ctx, flags)) {
1161 INTERNAL_ERROR_INT("context_setstatus_list");
1162 }
1163
1164 return 0;
1165 }
1166
1167 static int
1168 context_setstatus_dict(PyObject *self, PyObject *value)
1169 {
1170 mpd_context_t *ctx;
1171 uint32_t flags;
1172
1173 decimal_state *state = get_module_state_by_def(Py_TYPE(self));
1174 if (PyDecSignalDict_Check(state, value)) {
1175 flags = SdFlags(value);
1176 }
1177 else {
1178 flags = dict_as_flags(state, value);
1179 if (flags & DEC_ERRORS) {
1180 return -1;
1181 }
1182 }
1183
1184 ctx = CTX(self);
1185 if (!mpd_qsetstatus(ctx, flags)) {
1186 INTERNAL_ERROR_INT("context_setstatus_dict");
1187 }
1188
1189 return 0;
1190 }
1191
1192 static int
1193 context_setclamp(PyObject *self, PyObject *value, void *closure UNUSED)
1194 {
1195 mpd_context_t *ctx;
1196 mpd_ssize_t x;
1197
1198 x = PyLong_AsSsize_t(value);
1199 if (x == -1 && PyErr_Occurred()) {
1200 return -1;
1201 }
1202 BOUNDS_CHECK(x, INT_MIN, INT_MAX);
1203
1204 ctx = CTX(self);
1205 if (!mpd_qsetclamp(ctx, (int)x)) {
1206 return value_error_int("valid values for clamp are 0 or 1");
1207 }
1208
1209 return 0;
1210 }
1211
1212 #ifdef EXTRA_FUNCTIONALITY
1213 static int
1214 context_setallcr(PyObject *self, PyObject *value, void *closure UNUSED)
1215 {
1216 mpd_context_t *ctx;
1217 mpd_ssize_t x;
1218
1219 x = PyLong_AsSsize_t(value);
1220 if (x == -1 && PyErr_Occurred()) {
1221 return -1;
1222 }
1223 BOUNDS_CHECK(x, INT_MIN, INT_MAX);
1224
1225 ctx = CTX(self);
1226 if (!mpd_qsetcr(ctx, (int)x)) {
1227 return value_error_int("valid values for _allcr are 0 or 1");
1228 }
1229
1230 return 0;
1231 }
1232 #endif
1233
1234 static PyObject *
1235 context_getattr(PyObject *self, PyObject *name)
1236 {
1237 PyObject *retval;
1238
1239 if (PyUnicode_Check(name)) {
1240 if (PyUnicode_CompareWithASCIIString(name, "traps") == 0) {
1241 retval = ((PyDecContextObject *)self)->traps;
1242 return Py_NewRef(retval);
1243 }
1244 if (PyUnicode_CompareWithASCIIString(name, "flags") == 0) {
1245 retval = ((PyDecContextObject *)self)->flags;
1246 return Py_NewRef(retval);
1247 }
1248 }
1249
1250 return PyObject_GenericGetAttr(self, name);
1251 }
1252
1253 static int
1254 context_setattr(PyObject *self, PyObject *name, PyObject *value)
1255 {
1256 if (value == NULL) {
1257 PyErr_SetString(PyExc_AttributeError,
1258 "context attributes cannot be deleted");
1259 return -1;
1260 }
1261
1262 if (PyUnicode_Check(name)) {
1263 if (PyUnicode_CompareWithASCIIString(name, "traps") == 0) {
1264 return context_settraps_dict(self, value);
1265 }
1266 if (PyUnicode_CompareWithASCIIString(name, "flags") == 0) {
1267 return context_setstatus_dict(self, value);
1268 }
1269 }
1270
1271 return PyObject_GenericSetAttr(self, name, value);
1272 }
1273
1274 static int
1275 context_setattrs(PyObject *self, PyObject *prec, PyObject *rounding,
1276 PyObject *emin, PyObject *emax, PyObject *capitals,
1277 PyObject *clamp, PyObject *status, PyObject *traps) {
1278
1279 int ret;
1280 if (prec != Py_None && context_setprec(self, prec, NULL) < 0) {
1281 return -1;
1282 }
1283 if (rounding != Py_None && context_setround(self, rounding, NULL) < 0) {
1284 return -1;
1285 }
1286 if (emin != Py_None && context_setemin(self, emin, NULL) < 0) {
1287 return -1;
1288 }
1289 if (emax != Py_None && context_setemax(self, emax, NULL) < 0) {
1290 return -1;
1291 }
1292 if (capitals != Py_None && context_setcapitals(self, capitals, NULL) < 0) {
1293 return -1;
1294 }
1295 if (clamp != Py_None && context_setclamp(self, clamp, NULL) < 0) {
1296 return -1;
1297 }
1298
1299 if (traps != Py_None) {
1300 if (PyList_Check(traps)) {
1301 ret = context_settraps_list(self, traps);
1302 }
1303 #ifdef EXTRA_FUNCTIONALITY
1304 else if (PyLong_Check(traps)) {
1305 ret = context_settraps(self, traps, NULL);
1306 }
1307 #endif
1308 else {
1309 ret = context_settraps_dict(self, traps);
1310 }
1311 if (ret < 0) {
1312 return ret;
1313 }
1314 }
1315 if (status != Py_None) {
1316 if (PyList_Check(status)) {
1317 ret = context_setstatus_list(self, status);
1318 }
1319 #ifdef EXTRA_FUNCTIONALITY
1320 else if (PyLong_Check(status)) {
1321 ret = context_setstatus(self, status, NULL);
1322 }
1323 #endif
1324 else {
1325 ret = context_setstatus_dict(self, status);
1326 }
1327 if (ret < 0) {
1328 return ret;
1329 }
1330 }
1331
1332 return 0;
1333 }
1334
1335 static PyObject *
1336 context_clear_traps(PyObject *self, PyObject *dummy UNUSED)
1337 {
1338 CTX(self)->traps = 0;
1339 Py_RETURN_NONE;
1340 }
1341
1342 static PyObject *
1343 context_clear_flags(PyObject *self, PyObject *dummy UNUSED)
1344 {
1345 CTX(self)->status = 0;
1346 Py_RETURN_NONE;
1347 }
1348
1349 #define DEC_DFLT_EMAX 999999
1350 #define DEC_DFLT_EMIN -999999
1351
1352 static mpd_context_t dflt_ctx = {
1353 28, DEC_DFLT_EMAX, DEC_DFLT_EMIN,
1354 MPD_IEEE_Invalid_operation|MPD_Division_by_zero|MPD_Overflow,
1355 0, 0, MPD_ROUND_HALF_EVEN, 0, 1
1356 };
1357
1358 static PyObject *
1359 context_new(PyTypeObject *type, PyObject *args UNUSED, PyObject *kwds UNUSED)
1360 {
1361 PyDecContextObject *self = NULL;
1362 mpd_context_t *ctx;
1363
1364 decimal_state *state = get_module_state_by_def(type);
1365 if (type == state->PyDecContext_Type) {
1366 self = PyObject_GC_New(PyDecContextObject, state->PyDecContext_Type);
1367 }
1368 else {
1369 self = (PyDecContextObject *)type->tp_alloc(type, 0);
1370 }
1371
1372 if (self == NULL) {
1373 return NULL;
1374 }
1375
1376 self->traps = PyObject_CallObject((PyObject *)state->PyDecSignalDict_Type, NULL);
1377 if (self->traps == NULL) {
1378 self->flags = NULL;
1379 Py_DECREF(self);
1380 return NULL;
1381 }
1382 self->flags = PyObject_CallObject((PyObject *)state->PyDecSignalDict_Type, NULL);
1383 if (self->flags == NULL) {
1384 Py_DECREF(self);
1385 return NULL;
1386 }
1387
1388 ctx = CTX(self);
1389
1390 if (state->default_context_template) {
1391 *ctx = *CTX(state->default_context_template);
1392 }
1393 else {
1394 *ctx = dflt_ctx;
1395 }
1396
1397 SdFlagAddr(self->traps) = &ctx->traps;
1398 SdFlagAddr(self->flags) = &ctx->status;
1399
1400 CtxCaps(self) = 1;
1401 self->tstate = NULL;
1402
1403 if (type == state->PyDecContext_Type) {
1404 PyObject_GC_Track(self);
1405 }
1406 assert(PyObject_GC_IsTracked((PyObject *)self));
1407 return (PyObject *)self;
1408 }
1409
1410 static int
1411 context_traverse(PyDecContextObject *self, visitproc visit, void *arg)
1412 {
1413 Py_VISIT(Py_TYPE(self));
1414 Py_VISIT(self->traps);
1415 Py_VISIT(self->flags);
1416 return 0;
1417 }
1418
1419 static int
1420 context_clear(PyDecContextObject *self)
1421 {
1422 Py_CLEAR(self->traps);
1423 Py_CLEAR(self->flags);
1424 return 0;
1425 }
1426
1427 static void
1428 context_dealloc(PyDecContextObject *self)
1429 {
1430 PyTypeObject *tp = Py_TYPE(self);
1431 PyObject_GC_UnTrack(self);
1432 (void)context_clear(self);
1433 tp->tp_free(self);
1434 Py_DECREF(tp);
1435 }
1436
1437 static int
1438 context_init(PyObject *self, PyObject *args, PyObject *kwds)
1439 {
1440 static char *kwlist[] = {
1441 "prec", "rounding", "Emin", "Emax", "capitals", "clamp",
1442 "flags", "traps", NULL
1443 };
1444 PyObject *prec = Py_None;
1445 PyObject *rounding = Py_None;
1446 PyObject *emin = Py_None;
1447 PyObject *emax = Py_None;
1448 PyObject *capitals = Py_None;
1449 PyObject *clamp = Py_None;
1450 PyObject *status = Py_None;
1451 PyObject *traps = Py_None;
1452
1453 assert(PyTuple_Check(args));
1454
1455 if (!PyArg_ParseTupleAndKeywords(
1456 args, kwds,
1457 "|OOOOOOOO", kwlist,
1458 &prec, &rounding, &emin, &emax, &capitals, &clamp, &status, &traps
1459 )) {
1460 return -1;
1461 }
1462
1463 return context_setattrs(
1464 self, prec, rounding,
1465 emin, emax, capitals,
1466 clamp, status, traps
1467 );
1468 }
1469
1470 static PyObject *
1471 context_repr(PyDecContextObject *self)
1472 {
1473 mpd_context_t *ctx;
1474 char flags[MPD_MAX_SIGNAL_LIST];
1475 char traps[MPD_MAX_SIGNAL_LIST];
1476 int n, mem;
1477
1478 #ifdef Py_DEBUG
1479 decimal_state *state = get_module_state_by_def(Py_TYPE(self));
1480 assert(PyDecContext_Check(state, self));
1481 #endif
1482 ctx = CTX(self);
1483
1484 mem = MPD_MAX_SIGNAL_LIST;
1485 n = mpd_lsnprint_signals(flags, mem, ctx->status, dec_signal_string);
1486 if (n < 0 || n >= mem) {
1487 INTERNAL_ERROR_PTR("context_repr");
1488 }
1489
1490 n = mpd_lsnprint_signals(traps, mem, ctx->traps, dec_signal_string);
1491 if (n < 0 || n >= mem) {
1492 INTERNAL_ERROR_PTR("context_repr");
1493 }
1494
1495 return PyUnicode_FromFormat(
1496 "Context(prec=%zd, rounding=%s, Emin=%zd, Emax=%zd, "
1497 "capitals=%d, clamp=%d, flags=%s, traps=%s)",
1498 ctx->prec, mpd_round_string[ctx->round], ctx->emin, ctx->emax,
1499 self->capitals, ctx->clamp, flags, traps);
1500 }
1501
1502 static void
1503 init_basic_context(PyObject *v)
1504 {
1505 mpd_context_t ctx = dflt_ctx;
1506
1507 ctx.prec = 9;
1508 ctx.traps |= (MPD_Underflow|MPD_Clamped);
1509 ctx.round = MPD_ROUND_HALF_UP;
1510
1511 *CTX(v) = ctx;
1512 CtxCaps(v) = 1;
1513 }
1514
1515 static void
1516 init_extended_context(PyObject *v)
1517 {
1518 mpd_context_t ctx = dflt_ctx;
1519
1520 ctx.prec = 9;
1521 ctx.traps = 0;
1522
1523 *CTX(v) = ctx;
1524 CtxCaps(v) = 1;
1525 }
1526
1527 #ifdef EXTRA_FUNCTIONALITY
1528 /* Factory function for creating IEEE interchange format contexts */
1529 static PyObject *
1530 ieee_context(PyObject *module, PyObject *v)
1531 {
1532 PyObject *context;
1533 mpd_ssize_t bits;
1534 mpd_context_t ctx;
1535
1536 bits = PyLong_AsSsize_t(v);
1537 if (bits == -1 && PyErr_Occurred()) {
1538 return NULL;
1539 }
1540 if (bits <= 0 || bits > INT_MAX) {
1541 goto error;
1542 }
1543 if (mpd_ieee_context(&ctx, (int)bits) < 0) {
1544 goto error;
1545 }
1546
1547 decimal_state *state = get_module_state(module);
1548 context = PyObject_CallObject((PyObject *)state->PyDecContext_Type, NULL);
1549 if (context == NULL) {
1550 return NULL;
1551 }
1552 *CTX(context) = ctx;
1553
1554 return context;
1555
1556 error:
1557 PyErr_Format(PyExc_ValueError,
1558 "argument must be a multiple of 32, with a maximum of %d",
1559 MPD_IEEE_CONTEXT_MAX_BITS);
1560
1561 return NULL;
1562 }
1563 #endif
1564
1565 static PyObject *
1566 context_copy(PyObject *self, PyObject *args UNUSED)
1567 {
1568 PyObject *copy;
1569
1570 decimal_state *state = get_module_state_by_def(Py_TYPE(self));
1571 copy = PyObject_CallObject((PyObject *)state->PyDecContext_Type, NULL);
1572 if (copy == NULL) {
1573 return NULL;
1574 }
1575
1576 *CTX(copy) = *CTX(self);
1577 CTX(copy)->newtrap = 0;
1578 CtxCaps(copy) = CtxCaps(self);
1579
1580 return copy;
1581 }
1582
1583 static PyObject *
1584 context_reduce(PyObject *self, PyObject *args UNUSED)
1585 {
1586 PyObject *flags;
1587 PyObject *traps;
1588 PyObject *ret;
1589 mpd_context_t *ctx;
1590 decimal_state *state = get_module_state_by_def(Py_TYPE(self));
1591
1592 ctx = CTX(self);
1593
1594 flags = signals_as_list(state, ctx->status);
1595 if (flags == NULL) {
1596 return NULL;
1597 }
1598 traps = signals_as_list(state, ctx->traps);
1599 if (traps == NULL) {
1600 Py_DECREF(flags);
1601 return NULL;
1602 }
1603
1604 ret = Py_BuildValue(
1605 "O(nsnniiOO)",
1606 Py_TYPE(self),
1607 ctx->prec, mpd_round_string[ctx->round], ctx->emin, ctx->emax,
1608 CtxCaps(self), ctx->clamp, flags, traps
1609 );
1610
1611 Py_DECREF(flags);
1612 Py_DECREF(traps);
1613 return ret;
1614 }
1615
1616
1617 static PyGetSetDef context_getsets [] =
1618 {
1619 { "prec", (getter)context_getprec, (setter)context_setprec, NULL, NULL},
1620 { "Emax", (getter)context_getemax, (setter)context_setemax, NULL, NULL},
1621 { "Emin", (getter)context_getemin, (setter)context_setemin, NULL, NULL},
1622 { "rounding", (getter)context_getround, (setter)context_setround, NULL, NULL},
1623 { "capitals", (getter)context_getcapitals, (setter)context_setcapitals, NULL, NULL},
1624 { "clamp", (getter)context_getclamp, (setter)context_setclamp, NULL, NULL},
1625 #ifdef EXTRA_FUNCTIONALITY
1626 { "_allcr", (getter)context_getallcr, (setter)context_setallcr, NULL, NULL},
1627 { "_traps", (getter)context_gettraps, (setter)context_settraps, NULL, NULL},
1628 { "_flags", (getter)context_getstatus, (setter)context_setstatus, NULL, NULL},
1629 #endif
1630 {NULL}
1631 };
1632
1633
1634 #define CONTEXT_CHECK(state, obj) \
1635 if (!PyDecContext_Check(state, obj)) { \
1636 PyErr_SetString(PyExc_TypeError, \
1637 "argument must be a context"); \
1638 return NULL; \
1639 }
1640
1641 #define CONTEXT_CHECK_VA(state, obj) \
1642 if (obj == Py_None) { \
1643 CURRENT_CONTEXT(state, obj); \
1644 } \
1645 else if (!PyDecContext_Check(state, obj)) { \
1646 PyErr_SetString(PyExc_TypeError, \
1647 "optional argument must be a context"); \
1648 return NULL; \
1649 }
1650
1651
1652 /******************************************************************************/
1653 /* Global, thread local and temporary contexts */
1654 /******************************************************************************/
1655
1656 /*
1657 * Thread local storage currently has a speed penalty of about 4%.
1658 * All functions that map Python's arithmetic operators to mpdecimal
1659 * functions have to look up the current context for each and every
1660 * operation.
1661 */
1662
1663 #ifndef WITH_DECIMAL_CONTEXTVAR
1664 /* Get the context from the thread state dictionary. */
1665 static PyObject *
1666 current_context_from_dict(decimal_state *modstate)
1667 {
1668 PyThreadState *tstate = _PyThreadState_GET();
1669 #ifdef Py_DEBUG
1670 // The caller must hold the GIL
1671 _Py_EnsureTstateNotNULL(tstate);
1672 #endif
1673
1674 PyObject *dict = _PyThreadState_GetDict(tstate);
1675 if (dict == NULL) {
1676 PyErr_SetString(PyExc_RuntimeError,
1677 "cannot get thread state");
1678 return NULL;
1679 }
1680
1681 PyObject *tl_context;
1682 tl_context = PyDict_GetItemWithError(dict, modstate->tls_context_key);
1683 if (tl_context != NULL) {
1684 /* We already have a thread local context. */
1685 CONTEXT_CHECK(modstate, tl_context);
1686 }
1687 else {
1688 if (PyErr_Occurred()) {
1689 return NULL;
1690 }
1691
1692 /* Set up a new thread local context. */
1693 tl_context = context_copy(modstate->default_context_template, NULL);
1694 if (tl_context == NULL) {
1695 return NULL;
1696 }
1697 CTX(tl_context)->status = 0;
1698
1699 if (PyDict_SetItem(dict, modstate->tls_context_key, tl_context) < 0) {
1700 Py_DECREF(tl_context);
1701 return NULL;
1702 }
1703 Py_DECREF(tl_context);
1704 }
1705
1706 /* Cache the context of the current thread, assuming that it
1707 * will be accessed several times before a thread switch. */
1708 Py_XSETREF(modstate->cached_context,
1709 (PyDecContextObject *)Py_NewRef(tl_context));
1710 modstate->cached_context->tstate = tstate;
1711
1712 /* Borrowed reference with refcount==1 */
1713 return tl_context;
1714 }
1715
1716 /* Return borrowed reference to thread local context. */
1717 static PyObject *
1718 current_context(decimal_state *modstate)
1719 {
1720 PyThreadState *tstate = _PyThreadState_GET();
1721 if (modstate->cached_context && modstate->cached_context->tstate == tstate) {
1722 return (PyObject *)(modstate->cached_context);
1723 }
1724
1725 return current_context_from_dict(modstate);
1726 }
1727
1728 /* ctxobj := borrowed reference to the current context */
1729 #define CURRENT_CONTEXT(state, ctxobj) \
1730 ctxobj = current_context(state); \
1731 if (ctxobj == NULL) { \
1732 return NULL; \
1733 }
1734
1735 /* Return a new reference to the current context */
1736 static PyObject *
1737 PyDec_GetCurrentContext(PyObject *self, PyObject *args UNUSED)
1738 {
1739 PyObject *context;
1740 decimal_state *state = get_module_state(self);
1741
1742 CURRENT_CONTEXT(state, context);
1743 return Py_NewRef(context);
1744 }
1745
1746 /* Set the thread local context to a new context, decrement old reference */
1747 static PyObject *
1748 PyDec_SetCurrentContext(PyObject *self, PyObject *v)
1749 {
1750 PyObject *dict;
1751
1752 decimal_state *state = get_module_state(self);
1753 CONTEXT_CHECK(state, v);
1754
1755 dict = PyThreadState_GetDict();
1756 if (dict == NULL) {
1757 PyErr_SetString(PyExc_RuntimeError,
1758 "cannot get thread state");
1759 return NULL;
1760 }
1761
1762 /* If the new context is one of the templates, make a copy.
1763 * This is the current behavior of decimal.py. */
1764 if (v == state->default_context_template ||
1765 v == state->basic_context_template ||
1766 v == state->extended_context_template) {
1767 v = context_copy(v, NULL);
1768 if (v == NULL) {
1769 return NULL;
1770 }
1771 CTX(v)->status = 0;
1772 }
1773 else {
1774 Py_INCREF(v);
1775 }
1776
1777 Py_CLEAR(state->cached_context);
1778 if (PyDict_SetItem(dict, state->tls_context_key, v) < 0) {
1779 Py_DECREF(v);
1780 return NULL;
1781 }
1782
1783 Py_DECREF(v);
1784 Py_RETURN_NONE;
1785 }
1786 #else
1787 static PyObject *
1788 init_current_context(decimal_state *state)
1789 {
1790 PyObject *tl_context = context_copy(state->default_context_template, NULL);
1791 if (tl_context == NULL) {
1792 return NULL;
1793 }
1794 CTX(tl_context)->status = 0;
1795
1796 PyObject *tok = PyContextVar_Set(state->current_context_var, tl_context);
1797 if (tok == NULL) {
1798 Py_DECREF(tl_context);
1799 return NULL;
1800 }
1801 Py_DECREF(tok);
1802
1803 return tl_context;
1804 }
1805
1806 static inline PyObject *
1807 current_context(decimal_state *state)
1808 {
1809 PyObject *tl_context;
1810 if (PyContextVar_Get(state->current_context_var, NULL, &tl_context) < 0) {
1811 return NULL;
1812 }
1813
1814 if (tl_context != NULL) {
1815 return tl_context;
1816 }
1817
1818 return init_current_context(state);
1819 }
1820
1821 /* ctxobj := borrowed reference to the current context */
1822 #define CURRENT_CONTEXT(state, ctxobj) \
1823 ctxobj = current_context(state); \
1824 if (ctxobj == NULL) { \
1825 return NULL; \
1826 } \
1827 Py_DECREF(ctxobj);
1828
1829 /* Return a new reference to the current context */
1830 static PyObject *
1831 PyDec_GetCurrentContext(PyObject *self, PyObject *args UNUSED)
1832 {
1833 decimal_state *state = get_module_state(self);
1834 return current_context(state);
1835 }
1836
1837 /* Set the thread local context to a new context, decrement old reference */
1838 static PyObject *
1839 PyDec_SetCurrentContext(PyObject *self, PyObject *v)
1840 {
1841 decimal_state *state = get_module_state(self);
1842 CONTEXT_CHECK(state, v);
1843
1844 /* If the new context is one of the templates, make a copy.
1845 * This is the current behavior of decimal.py. */
1846 if (v == state->default_context_template ||
1847 v == state->basic_context_template ||
1848 v == state->extended_context_template) {
1849 v = context_copy(v, NULL);
1850 if (v == NULL) {
1851 return NULL;
1852 }
1853 CTX(v)->status = 0;
1854 }
1855 else {
1856 Py_INCREF(v);
1857 }
1858
1859 PyObject *tok = PyContextVar_Set(state->current_context_var, v);
1860 Py_DECREF(v);
1861 if (tok == NULL) {
1862 return NULL;
1863 }
1864 Py_DECREF(tok);
1865
1866 Py_RETURN_NONE;
1867 }
1868 #endif
1869
1870 /* Context manager object for the 'with' statement. The manager
1871 * owns one reference to the global (outer) context and one
1872 * to the local (inner) context. */
1873 static PyObject *
1874 ctxmanager_new(PyObject *m, PyObject *args, PyObject *kwds)
1875 {
1876 static char *kwlist[] = {
1877 "ctx", "prec", "rounding",
1878 "Emin", "Emax", "capitals",
1879 "clamp", "flags", "traps",
1880 NULL
1881 };
1882 PyObject *local = Py_None;
1883 PyObject *global;
1884
1885 PyObject *prec = Py_None;
1886 PyObject *rounding = Py_None;
1887 PyObject *Emin = Py_None;
1888 PyObject *Emax = Py_None;
1889 PyObject *capitals = Py_None;
1890 PyObject *clamp = Py_None;
1891 PyObject *flags = Py_None;
1892 PyObject *traps = Py_None;
1893
1894 decimal_state *state = get_module_state(m);
1895 CURRENT_CONTEXT(state, global);
1896 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOOOOOOOO", kwlist, &local,
1897 &prec, &rounding, &Emin, &Emax, &capitals, &clamp, &flags, &traps)) {
1898 return NULL;
1899 }
1900 if (local == Py_None) {
1901 local = global;
1902 }
1903 else if (!PyDecContext_Check(state, local)) {
1904 PyErr_SetString(PyExc_TypeError,
1905 "optional argument must be a context");
1906 return NULL;
1907 }
1908
1909 PyObject *local_copy = context_copy(local, NULL);
1910 if (local_copy == NULL) {
1911 return NULL;
1912 }
1913
1914 int ret = context_setattrs(
1915 local_copy, prec, rounding,
1916 Emin, Emax, capitals,
1917 clamp, flags, traps
1918 );
1919 if (ret < 0) {
1920 Py_DECREF(local_copy);
1921 return NULL;
1922 }
1923
1924 PyDecContextManagerObject *self;
1925 self = PyObject_GC_New(PyDecContextManagerObject,
1926 state->PyDecContextManager_Type);
1927 if (self == NULL) {
1928 Py_DECREF(local_copy);
1929 return NULL;
1930 }
1931
1932 self->local = local_copy;
1933 self->global = Py_NewRef(global);
1934 PyObject_GC_Track(self);
1935
1936 return (PyObject *)self;
1937 }
1938
1939 static int
1940 ctxmanager_traverse(PyDecContextManagerObject *self, visitproc visit,
1941 void *arg)
1942 {
1943 Py_VISIT(Py_TYPE(self));
1944 Py_VISIT(self->local);
1945 Py_VISIT(self->global);
1946 return 0;
1947 }
1948
1949 static int
1950 ctxmanager_clear(PyDecContextManagerObject *self)
1951 {
1952 Py_CLEAR(self->local);
1953 Py_CLEAR(self->global);
1954 return 0;
1955 }
1956
1957 static void
1958 ctxmanager_dealloc(PyDecContextManagerObject *self)
1959 {
1960 PyTypeObject *tp = Py_TYPE(self);
1961 PyObject_GC_UnTrack(self);
1962 (void)ctxmanager_clear(self);
1963 tp->tp_free((PyObject *)self);
1964 Py_DECREF(tp);
1965 }
1966
1967 static PyObject *
1968 ctxmanager_set_local(PyDecContextManagerObject *self, PyObject *args UNUSED)
1969 {
1970 PyObject *ret;
1971
1972 ret = PyDec_SetCurrentContext(PyType_GetModule(Py_TYPE(self)), self->local);
1973 if (ret == NULL) {
1974 return NULL;
1975 }
1976 Py_DECREF(ret);
1977
1978 return Py_NewRef(self->local);
1979 }
1980
1981 static PyObject *
1982 ctxmanager_restore_global(PyDecContextManagerObject *self,
1983 PyObject *args UNUSED)
1984 {
1985 PyObject *ret;
1986
1987 ret = PyDec_SetCurrentContext(PyType_GetModule(Py_TYPE(self)), self->global);
1988 if (ret == NULL) {
1989 return NULL;
1990 }
1991 Py_DECREF(ret);
1992
1993 Py_RETURN_NONE;
1994 }
1995
1996
1997 static PyMethodDef ctxmanager_methods[] = {
1998 {"__enter__", (PyCFunction)ctxmanager_set_local, METH_NOARGS, NULL},
1999 {"__exit__", (PyCFunction)ctxmanager_restore_global, METH_VARARGS, NULL},
2000 {NULL, NULL}
2001 };
2002
2003 static PyType_Slot ctxmanager_slots[] = {
2004 {Py_tp_dealloc, ctxmanager_dealloc},
2005 {Py_tp_getattro, PyObject_GenericGetAttr},
2006 {Py_tp_traverse, ctxmanager_traverse},
2007 {Py_tp_clear, ctxmanager_clear},
2008 {Py_tp_methods, ctxmanager_methods},
2009 {0, NULL},
2010 };
2011
2012 static PyType_Spec ctxmanager_spec = {
2013 .name = "decimal.ContextManager",
2014 .basicsize = sizeof(PyDecContextManagerObject),
2015 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2016 Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION),
2017 .slots = ctxmanager_slots,
2018 };
2019
2020
2021 /******************************************************************************/
2022 /* New Decimal Object */
2023 /******************************************************************************/
2024
2025 static PyObject *
2026 PyDecType_New(PyTypeObject *type)
2027 {
2028 PyDecObject *dec;
2029
2030 decimal_state *state = get_module_state_by_def(type);
2031 if (type == state->PyDec_Type) {
2032 dec = PyObject_GC_New(PyDecObject, state->PyDec_Type);
2033 }
2034 else {
2035 dec = (PyDecObject *)type->tp_alloc(type, 0);
2036 }
2037 if (dec == NULL) {
2038 return NULL;
2039 }
2040
2041 dec->hash = -1;
2042
2043 MPD(dec)->flags = MPD_STATIC|MPD_STATIC_DATA;
2044 MPD(dec)->exp = 0;
2045 MPD(dec)->digits = 0;
2046 MPD(dec)->len = 0;
2047 MPD(dec)->alloc = _Py_DEC_MINALLOC;
2048 MPD(dec)->data = dec->data;
2049
2050 if (type == state->PyDec_Type) {
2051 PyObject_GC_Track(dec);
2052 }
2053 assert(PyObject_GC_IsTracked((PyObject *)dec));
2054 return (PyObject *)dec;
2055 }
2056 #define dec_alloc(st) PyDecType_New((st)->PyDec_Type)
2057
2058 static int
2059 dec_traverse(PyObject *dec, visitproc visit, void *arg)
2060 {
2061 Py_VISIT(Py_TYPE(dec));
2062 return 0;
2063 }
2064
2065 static void
2066 dec_dealloc(PyObject *dec)
2067 {
2068 PyTypeObject *tp = Py_TYPE(dec);
2069 PyObject_GC_UnTrack(dec);
2070 mpd_del(MPD(dec));
2071 tp->tp_free(dec);
2072 Py_DECREF(tp);
2073 }
2074
2075
2076 /******************************************************************************/
2077 /* Conversions to Decimal */
2078 /******************************************************************************/
2079
2080 Py_LOCAL_INLINE(int)
2081 is_space(int kind, const void *data, Py_ssize_t pos)
2082 {
2083 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
2084 return Py_UNICODE_ISSPACE(ch);
2085 }
2086
2087 /* Return the ASCII representation of a numeric Unicode string. The numeric
2088 string may contain ascii characters in the range [1, 127], any Unicode
2089 space and any unicode digit. If strip_ws is true, leading and trailing
2090 whitespace is stripped. If ignore_underscores is true, underscores are
2091 ignored.
2092
2093 Return NULL if malloc fails and an empty string if invalid characters
2094 are found. */
2095 static char *
2096 numeric_as_ascii(PyObject *u, int strip_ws, int ignore_underscores)
2097 {
2098 int kind;
2099 const void *data;
2100 Py_UCS4 ch;
2101 char *res, *cp;
2102 Py_ssize_t j, len;
2103 int d;
2104
2105 kind = PyUnicode_KIND(u);
2106 data = PyUnicode_DATA(u);
2107 len = PyUnicode_GET_LENGTH(u);
2108
2109 cp = res = PyMem_Malloc(len+1);
2110 if (res == NULL) {
2111 PyErr_NoMemory();
2112 return NULL;
2113 }
2114
2115 j = 0;
2116 if (strip_ws) {
2117 while (len > 0 && is_space(kind, data, len-1)) {
2118 len--;
2119 }
2120 while (j < len && is_space(kind, data, j)) {
2121 j++;
2122 }
2123 }
2124
2125 for (; j < len; j++) {
2126 ch = PyUnicode_READ(kind, data, j);
2127 if (ignore_underscores && ch == '_') {
2128 continue;
2129 }
2130 if (0 < ch && ch <= 127) {
2131 *cp++ = ch;
2132 continue;
2133 }
2134 if (Py_UNICODE_ISSPACE(ch)) {
2135 *cp++ = ' ';
2136 continue;
2137 }
2138 d = Py_UNICODE_TODECIMAL(ch);
2139 if (d < 0) {
2140 /* empty string triggers ConversionSyntax */
2141 *res = '\0';
2142 return res;
2143 }
2144 *cp++ = '0' + d;
2145 }
2146 *cp = '\0';
2147 return res;
2148 }
2149
2150 /* Return a new PyDecObject or a subtype from a C string. Use the context
2151 during conversion. */
2152 static PyObject *
2153 PyDecType_FromCString(PyTypeObject *type, const char *s,
2154 PyObject *context)
2155 {
2156 PyObject *dec;
2157 uint32_t status = 0;
2158
2159 dec = PyDecType_New(type);
2160 if (dec == NULL) {
2161 return NULL;
2162 }
2163
2164 mpd_qset_string(MPD(dec), s, CTX(context), &status);
2165 if (dec_addstatus(context, status)) {
2166 Py_DECREF(dec);
2167 return NULL;
2168 }
2169 return dec;
2170 }
2171
2172 /* Return a new PyDecObject or a subtype from a C string. Attempt exact
2173 conversion. If the operand cannot be converted exactly, set
2174 InvalidOperation. */
2175 static PyObject *
2176 PyDecType_FromCStringExact(PyTypeObject *type, const char *s,
2177 PyObject *context)
2178 {
2179 PyObject *dec;
2180 uint32_t status = 0;
2181 mpd_context_t maxctx;
2182
2183 dec = PyDecType_New(type);
2184 if (dec == NULL) {
2185 return NULL;
2186 }
2187
2188 mpd_maxcontext(&maxctx);
2189
2190 mpd_qset_string(MPD(dec), s, &maxctx, &status);
2191 if (status & (MPD_Inexact|MPD_Rounded|MPD_Clamped)) {
2192 /* we want exact results */
2193 mpd_seterror(MPD(dec), MPD_Invalid_operation, &status);
2194 }
2195 status &= MPD_Errors;
2196 if (dec_addstatus(context, status)) {
2197 Py_DECREF(dec);
2198 return NULL;
2199 }
2200
2201 return dec;
2202 }
2203
2204 /* Return a new PyDecObject or a subtype from a PyUnicodeObject. */
2205 static PyObject *
2206 PyDecType_FromUnicode(PyTypeObject *type, PyObject *u,
2207 PyObject *context)
2208 {
2209 PyObject *dec;
2210 char *s;
2211
2212 s = numeric_as_ascii(u, 0, 0);
2213 if (s == NULL) {
2214 return NULL;
2215 }
2216
2217 dec = PyDecType_FromCString(type, s, context);
2218 PyMem_Free(s);
2219 return dec;
2220 }
2221
2222 /* Return a new PyDecObject or a subtype from a PyUnicodeObject. Attempt exact
2223 * conversion. If the conversion is not exact, fail with InvalidOperation.
2224 * Allow leading and trailing whitespace in the input operand. */
2225 static PyObject *
2226 PyDecType_FromUnicodeExactWS(PyTypeObject *type, PyObject *u,
2227 PyObject *context)
2228 {
2229 PyObject *dec;
2230 char *s;
2231
2232 s = numeric_as_ascii(u, 1, 1);
2233 if (s == NULL) {
2234 return NULL;
2235 }
2236
2237 dec = PyDecType_FromCStringExact(type, s, context);
2238 PyMem_Free(s);
2239 return dec;
2240 }
2241
2242 /* Set PyDecObject from triple without any error checking. */
2243 Py_LOCAL_INLINE(void)
2244 _dec_settriple(PyObject *dec, uint8_t sign, uint32_t v, mpd_ssize_t exp)
2245 {
2246
2247 #ifdef CONFIG_64
2248 MPD(dec)->data[0] = v;
2249 MPD(dec)->len = 1;
2250 #else
2251 uint32_t q, r;
2252 q = v / MPD_RADIX;
2253 r = v - q * MPD_RADIX;
2254 MPD(dec)->data[1] = q;
2255 MPD(dec)->data[0] = r;
2256 MPD(dec)->len = q ? 2 : 1;
2257 #endif
2258 mpd_set_flags(MPD(dec), sign);
2259 MPD(dec)->exp = exp;
2260 mpd_setdigits(MPD(dec));
2261 }
2262
2263 /* Return a new PyDecObject from an mpd_ssize_t. */
2264 static PyObject *
2265 PyDecType_FromSsize(PyTypeObject *type, mpd_ssize_t v, PyObject *context)
2266 {
2267 PyObject *dec;
2268 uint32_t status = 0;
2269
2270 dec = PyDecType_New(type);
2271 if (dec == NULL) {
2272 return NULL;
2273 }
2274
2275 mpd_qset_ssize(MPD(dec), v, CTX(context), &status);
2276 if (dec_addstatus(context, status)) {
2277 Py_DECREF(dec);
2278 return NULL;
2279 }
2280 return dec;
2281 }
2282
2283 /* Return a new PyDecObject from an mpd_ssize_t. Conversion is exact. */
2284 static PyObject *
2285 PyDecType_FromSsizeExact(PyTypeObject *type, mpd_ssize_t v, PyObject *context)
2286 {
2287 PyObject *dec;
2288 uint32_t status = 0;
2289 mpd_context_t maxctx;
2290
2291 dec = PyDecType_New(type);
2292 if (dec == NULL) {
2293 return NULL;
2294 }
2295
2296 mpd_maxcontext(&maxctx);
2297
2298 mpd_qset_ssize(MPD(dec), v, &maxctx, &status);
2299 if (dec_addstatus(context, status)) {
2300 Py_DECREF(dec);
2301 return NULL;
2302 }
2303 return dec;
2304 }
2305
2306 /* Convert from a PyLongObject. The context is not modified; flags set
2307 during conversion are accumulated in the status parameter. */
2308 static PyObject *
2309 dec_from_long(PyTypeObject *type, PyObject *v,
2310 const mpd_context_t *ctx, uint32_t *status)
2311 {
2312 PyObject *dec;
2313 PyLongObject *l = (PyLongObject *)v;
2314
2315 dec = PyDecType_New(type);
2316 if (dec == NULL) {
2317 return NULL;
2318 }
2319
2320 if (_PyLong_IsZero(l)) {
2321 _dec_settriple(dec, MPD_POS, 0, 0);
2322 return dec;
2323 }
2324
2325 uint8_t sign = _PyLong_IsNegative(l) ? MPD_NEG : MPD_POS;
2326
2327 if (_PyLong_IsCompact(l)) {
2328 _dec_settriple(dec, sign, l->long_value.ob_digit[0], 0);
2329 mpd_qfinalize(MPD(dec), ctx, status);
2330 return dec;
2331 }
2332 size_t len = _PyLong_DigitCount(l);
2333
2334 #if PYLONG_BITS_IN_DIGIT == 30
2335 mpd_qimport_u32(MPD(dec), l->long_value.ob_digit, len, sign, PyLong_BASE,
2336 ctx, status);
2337 #elif PYLONG_BITS_IN_DIGIT == 15
2338 mpd_qimport_u16(MPD(dec), l->long_value.ob_digit, len, sign, PyLong_BASE,
2339 ctx, status);
2340 #else
2341 #error "PYLONG_BITS_IN_DIGIT should be 15 or 30"
2342 #endif
2343
2344 return dec;
2345 }
2346
2347 /* Return a new PyDecObject from a PyLongObject. Use the context for
2348 conversion. */
2349 static PyObject *
2350 PyDecType_FromLong(PyTypeObject *type, PyObject *v, PyObject *context)
2351 {
2352 PyObject *dec;
2353 uint32_t status = 0;
2354
2355 if (!PyLong_Check(v)) {
2356 PyErr_SetString(PyExc_TypeError, "argument must be an integer");
2357 return NULL;
2358 }
2359
2360 dec = dec_from_long(type, v, CTX(context), &status);
2361 if (dec == NULL) {
2362 return NULL;
2363 }
2364
2365 if (dec_addstatus(context, status)) {
2366 Py_DECREF(dec);
2367 return NULL;
2368 }
2369
2370 return dec;
2371 }
2372
2373 /* Return a new PyDecObject from a PyLongObject. Use a maximum context
2374 for conversion. If the conversion is not exact, set InvalidOperation. */
2375 static PyObject *
2376 PyDecType_FromLongExact(PyTypeObject *type, PyObject *v,
2377 PyObject *context)
2378 {
2379 PyObject *dec;
2380 uint32_t status = 0;
2381 mpd_context_t maxctx;
2382
2383 if (!PyLong_Check(v)) {
2384 PyErr_SetString(PyExc_TypeError, "argument must be an integer");
2385 return NULL;
2386 }
2387
2388 mpd_maxcontext(&maxctx);
2389 dec = dec_from_long(type, v, &maxctx, &status);
2390 if (dec == NULL) {
2391 return NULL;
2392 }
2393
2394 if (status & (MPD_Inexact|MPD_Rounded|MPD_Clamped)) {
2395 /* we want exact results */
2396 mpd_seterror(MPD(dec), MPD_Invalid_operation, &status);
2397 }
2398 status &= MPD_Errors;
2399 if (dec_addstatus(context, status)) {
2400 Py_DECREF(dec);
2401 return NULL;
2402 }
2403
2404 return dec;
2405 }
2406
2407 /* Return a PyDecObject or a subtype from a PyFloatObject.
2408 Conversion is exact. */
2409 static PyObject *
2410 PyDecType_FromFloatExact(PyTypeObject *type, PyObject *v,
2411 PyObject *context)
2412 {
2413 PyObject *dec, *tmp;
2414 PyObject *n, *d, *n_d;
2415 mpd_ssize_t k;
2416 double x;
2417 int sign;
2418 mpd_t *d1, *d2;
2419 uint32_t status = 0;
2420 mpd_context_t maxctx;
2421 decimal_state *state = get_module_state_by_def(type);
2422
2423 #ifdef Py_DEBUG
2424 assert(PyType_IsSubtype(type, state->PyDec_Type));
2425 #endif
2426 if (PyLong_Check(v)) {
2427 return PyDecType_FromLongExact(type, v, context);
2428 }
2429 if (!PyFloat_Check(v)) {
2430 PyErr_SetString(PyExc_TypeError,
2431 "argument must be int or float");
2432 return NULL;
2433 }
2434
2435 x = PyFloat_AsDouble(v);
2436 if (x == -1.0 && PyErr_Occurred()) {
2437 return NULL;
2438 }
2439 sign = (copysign(1.0, x) == 1.0) ? 0 : 1;
2440
2441 if (Py_IS_NAN(x) || Py_IS_INFINITY(x)) {
2442 dec = PyDecType_New(type);
2443 if (dec == NULL) {
2444 return NULL;
2445 }
2446 if (Py_IS_NAN(x)) {
2447 /* decimal.py calls repr(float(+-nan)),
2448 * which always gives a positive result. */
2449 mpd_setspecial(MPD(dec), MPD_POS, MPD_NAN);
2450 }
2451 else {
2452 mpd_setspecial(MPD(dec), sign, MPD_INF);
2453 }
2454 return dec;
2455 }
2456
2457 /* absolute value of the float */
2458 tmp = state->_py_float_abs(v);
2459 if (tmp == NULL) {
2460 return NULL;
2461 }
2462
2463 /* float as integer ratio: numerator/denominator */
2464 n_d = state->_py_float_as_integer_ratio(tmp, NULL);
2465 Py_DECREF(tmp);
2466 if (n_d == NULL) {
2467 return NULL;
2468 }
2469 n = PyTuple_GET_ITEM(n_d, 0);
2470 d = PyTuple_GET_ITEM(n_d, 1);
2471
2472 tmp = state->_py_long_bit_length(d, NULL);
2473 if (tmp == NULL) {
2474 Py_DECREF(n_d);
2475 return NULL;
2476 }
2477 k = PyLong_AsSsize_t(tmp);
2478 Py_DECREF(tmp);
2479 if (k == -1 && PyErr_Occurred()) {
2480 Py_DECREF(n_d);
2481 return NULL;
2482 }
2483 k--;
2484
2485 dec = PyDecType_FromLongExact(type, n, context);
2486 Py_DECREF(n_d);
2487 if (dec == NULL) {
2488 return NULL;
2489 }
2490
2491 d1 = mpd_qnew();
2492 if (d1 == NULL) {
2493 Py_DECREF(dec);
2494 PyErr_NoMemory();
2495 return NULL;
2496 }
2497 d2 = mpd_qnew();
2498 if (d2 == NULL) {
2499 mpd_del(d1);
2500 Py_DECREF(dec);
2501 PyErr_NoMemory();
2502 return NULL;
2503 }
2504
2505 mpd_maxcontext(&maxctx);
2506 mpd_qset_uint(d1, 5, &maxctx, &status);
2507 mpd_qset_ssize(d2, k, &maxctx, &status);
2508 mpd_qpow(d1, d1, d2, &maxctx, &status);
2509 if (dec_addstatus(context, status)) {
2510 mpd_del(d1);
2511 mpd_del(d2);
2512 Py_DECREF(dec);
2513 return NULL;
2514 }
2515
2516 /* result = n * 5**k */
2517 mpd_qmul(MPD(dec), MPD(dec), d1, &maxctx, &status);
2518 mpd_del(d1);
2519 mpd_del(d2);
2520 if (dec_addstatus(context, status)) {
2521 Py_DECREF(dec);
2522 return NULL;
2523 }
2524 /* result = +- n * 5**k * 10**-k */
2525 mpd_set_sign(MPD(dec), sign);
2526 MPD(dec)->exp = -k;
2527
2528 return dec;
2529 }
2530
2531 static PyObject *
2532 PyDecType_FromFloat(PyTypeObject *type, PyObject *v,
2533 PyObject *context)
2534 {
2535 PyObject *dec;
2536 uint32_t status = 0;
2537
2538 dec = PyDecType_FromFloatExact(type, v, context);
2539 if (dec == NULL) {
2540 return NULL;
2541 }
2542
2543 mpd_qfinalize(MPD(dec), CTX(context), &status);
2544 if (dec_addstatus(context, status)) {
2545 Py_DECREF(dec);
2546 return NULL;
2547 }
2548
2549 return dec;
2550 }
2551
2552 /* Return a new PyDecObject or a subtype from a Decimal. */
2553 static PyObject *
2554 PyDecType_FromDecimalExact(PyTypeObject *type, PyObject *v, PyObject *context)
2555 {
2556 PyObject *dec;
2557 uint32_t status = 0;
2558
2559 decimal_state *state = get_module_state_by_def(type);
2560 if (type == state->PyDec_Type && PyDec_CheckExact(state, v)) {
2561 return Py_NewRef(v);
2562 }
2563
2564 dec = PyDecType_New(type);
2565 if (dec == NULL) {
2566 return NULL;
2567 }
2568
2569 mpd_qcopy(MPD(dec), MPD(v), &status);
2570 if (dec_addstatus(context, status)) {
2571 Py_DECREF(dec);
2572 return NULL;
2573 }
2574
2575 return dec;
2576 }
2577
2578 static PyObject *
2579 sequence_as_tuple(PyObject *v, PyObject *ex, const char *mesg)
2580 {
2581 if (PyTuple_Check(v)) {
2582 return Py_NewRef(v);
2583 }
2584 if (PyList_Check(v)) {
2585 return PyList_AsTuple(v);
2586 }
2587
2588 PyErr_SetString(ex, mesg);
2589 return NULL;
2590 }
2591
2592 /* Return a new C string representation of a DecimalTuple. */
2593 static char *
2594 dectuple_as_str(PyObject *dectuple)
2595 {
2596 PyObject *digits = NULL, *tmp;
2597 char *decstring = NULL;
2598 char sign_special[6];
2599 char *cp;
2600 long sign, l;
2601 mpd_ssize_t exp = 0;
2602 Py_ssize_t i, mem, tsize;
2603 int is_infinite = 0;
2604 int n;
2605
2606 assert(PyTuple_Check(dectuple));
2607
2608 if (PyTuple_Size(dectuple) != 3) {
2609 PyErr_SetString(PyExc_ValueError,
2610 "argument must be a sequence of length 3");
2611 goto error;
2612 }
2613
2614 /* sign */
2615 tmp = PyTuple_GET_ITEM(dectuple, 0);
2616 if (!PyLong_Check(tmp)) {
2617 PyErr_SetString(PyExc_ValueError,
2618 "sign must be an integer with the value 0 or 1");
2619 goto error;
2620 }
2621 sign = PyLong_AsLong(tmp);
2622 if (sign == -1 && PyErr_Occurred()) {
2623 goto error;
2624 }
2625 if (sign != 0 && sign != 1) {
2626 PyErr_SetString(PyExc_ValueError,
2627 "sign must be an integer with the value 0 or 1");
2628 goto error;
2629 }
2630 sign_special[0] = sign ? '-' : '+';
2631 sign_special[1] = '\0';
2632
2633 /* exponent or encoding for a special number */
2634 tmp = PyTuple_GET_ITEM(dectuple, 2);
2635 if (PyUnicode_Check(tmp)) {
2636 /* special */
2637 if (PyUnicode_CompareWithASCIIString(tmp, "F") == 0) {
2638 strcat(sign_special, "Inf");
2639 is_infinite = 1;
2640 }
2641 else if (PyUnicode_CompareWithASCIIString(tmp, "n") == 0) {
2642 strcat(sign_special, "NaN");
2643 }
2644 else if (PyUnicode_CompareWithASCIIString(tmp, "N") == 0) {
2645 strcat(sign_special, "sNaN");
2646 }
2647 else {
2648 PyErr_SetString(PyExc_ValueError,
2649 "string argument in the third position "
2650 "must be 'F', 'n' or 'N'");
2651 goto error;
2652 }
2653 }
2654 else {
2655 /* exponent */
2656 if (!PyLong_Check(tmp)) {
2657 PyErr_SetString(PyExc_ValueError,
2658 "exponent must be an integer");
2659 goto error;
2660 }
2661 exp = PyLong_AsSsize_t(tmp);
2662 if (exp == -1 && PyErr_Occurred()) {
2663 goto error;
2664 }
2665 }
2666
2667 /* coefficient */
2668 digits = sequence_as_tuple(PyTuple_GET_ITEM(dectuple, 1), PyExc_ValueError,
2669 "coefficient must be a tuple of digits");
2670 if (digits == NULL) {
2671 goto error;
2672 }
2673
2674 tsize = PyTuple_Size(digits);
2675 /* [sign][coeffdigits+1][E][-][expdigits+1]['\0'] */
2676 mem = 1 + tsize + 3 + MPD_EXPDIGITS + 2;
2677 cp = decstring = PyMem_Malloc(mem);
2678 if (decstring == NULL) {
2679 PyErr_NoMemory();
2680 goto error;
2681 }
2682
2683 n = snprintf(cp, mem, "%s", sign_special);
2684 if (n < 0 || n >= mem) {
2685 PyErr_SetString(PyExc_RuntimeError,
2686 "internal error in dec_sequence_as_str");
2687 goto error;
2688 }
2689 cp += n;
2690
2691 if (tsize == 0 && sign_special[1] == '\0') {
2692 /* empty tuple: zero coefficient, except for special numbers */
2693 *cp++ = '0';
2694 }
2695 for (i = 0; i < tsize; i++) {
2696 tmp = PyTuple_GET_ITEM(digits, i);
2697 if (!PyLong_Check(tmp)) {
2698 PyErr_SetString(PyExc_ValueError,
2699 "coefficient must be a tuple of digits");
2700 goto error;
2701 }
2702 l = PyLong_AsLong(tmp);
2703 if (l == -1 && PyErr_Occurred()) {
2704 goto error;
2705 }
2706 if (l < 0 || l > 9) {
2707 PyErr_SetString(PyExc_ValueError,
2708 "coefficient must be a tuple of digits");
2709 goto error;
2710 }
2711 if (is_infinite) {
2712 /* accept but ignore any well-formed coefficient for compatibility
2713 with decimal.py */
2714 continue;
2715 }
2716 *cp++ = (char)l + '0';
2717 }
2718 *cp = '\0';
2719
2720 if (sign_special[1] == '\0') {
2721 /* not a special number */
2722 *cp++ = 'E';
2723 n = snprintf(cp, MPD_EXPDIGITS+2, "%" PRI_mpd_ssize_t, exp);
2724 if (n < 0 || n >= MPD_EXPDIGITS+2) {
2725 PyErr_SetString(PyExc_RuntimeError,
2726 "internal error in dec_sequence_as_str");
2727 goto error;
2728 }
2729 }
2730
2731 Py_XDECREF(digits);
2732 return decstring;
2733
2734
2735 error:
2736 Py_XDECREF(digits);
2737 if (decstring) PyMem_Free(decstring);
2738 return NULL;
2739 }
2740
2741 /* Currently accepts tuples and lists. */
2742 static PyObject *
2743 PyDecType_FromSequence(PyTypeObject *type, PyObject *v,
2744 PyObject *context)
2745 {
2746 PyObject *dectuple;
2747 PyObject *dec;
2748 char *s;
2749
2750 dectuple = sequence_as_tuple(v, PyExc_TypeError,
2751 "argument must be a tuple or list");
2752 if (dectuple == NULL) {
2753 return NULL;
2754 }
2755
2756 s = dectuple_as_str(dectuple);
2757 Py_DECREF(dectuple);
2758 if (s == NULL) {
2759 return NULL;
2760 }
2761
2762 dec = PyDecType_FromCString(type, s, context);
2763
2764 PyMem_Free(s);
2765 return dec;
2766 }
2767
2768 /* Currently accepts tuples and lists. */
2769 static PyObject *
2770 PyDecType_FromSequenceExact(PyTypeObject *type, PyObject *v,
2771 PyObject *context)
2772 {
2773 PyObject *dectuple;
2774 PyObject *dec;
2775 char *s;
2776
2777 dectuple = sequence_as_tuple(v, PyExc_TypeError,
2778 "argument must be a tuple or list");
2779 if (dectuple == NULL) {
2780 return NULL;
2781 }
2782
2783 s = dectuple_as_str(dectuple);
2784 Py_DECREF(dectuple);
2785 if (s == NULL) {
2786 return NULL;
2787 }
2788
2789 dec = PyDecType_FromCStringExact(type, s, context);
2790
2791 PyMem_Free(s);
2792 return dec;
2793 }
2794
2795 #define PyDec_FromCString(st, str, context) \
2796 PyDecType_FromCString((st)->PyDec_Type, str, context)
2797 #define PyDec_FromCStringExact(st, str, context) \
2798 PyDecType_FromCStringExact((st)->PyDec_Type, str, context)
2799
2800 #define PyDec_FromUnicode(st, unicode, context) \
2801 PyDecType_FromUnicode((st)->PyDec_Type, unicode, context)
2802 #define PyDec_FromUnicodeExact(st, unicode, context) \
2803 PyDecType_FromUnicodeExact((st)->PyDec_Type, unicode, context)
2804 #define PyDec_FromUnicodeExactWS(st, unicode, context) \
2805 PyDecType_FromUnicodeExactWS((st)->PyDec_Type, unicode, context)
2806
2807 #define PyDec_FromSsize(st, v, context) \
2808 PyDecType_FromSsize((st)->PyDec_Type, v, context)
2809 #define PyDec_FromSsizeExact(st, v, context) \
2810 PyDecType_FromSsizeExact((st)->PyDec_Type, v, context)
2811
2812 #define PyDec_FromLong(st, pylong, context) \
2813 PyDecType_FromLong((st)->PyDec_Type, pylong, context)
2814 #define PyDec_FromLongExact(st, pylong, context) \
2815 PyDecType_FromLongExact((st)->PyDec_Type, pylong, context)
2816
2817 #define PyDec_FromFloat(st, pyfloat, context) \
2818 PyDecType_FromFloat((st)->PyDec_Type, pyfloat, context)
2819 #define PyDec_FromFloatExact(st, pyfloat, context) \
2820 PyDecType_FromFloatExact((st)->PyDec_Type, pyfloat, context)
2821
2822 #define PyDec_FromSequence(st, sequence, context) \
2823 PyDecType_FromSequence((st)->PyDec_Type, sequence, context)
2824 #define PyDec_FromSequenceExact(st, sequence, context) \
2825 PyDecType_FromSequenceExact((st)->PyDec_Type, sequence, context)
2826
2827 /* class method */
2828 static PyObject *
2829 dec_from_float(PyObject *type, PyObject *pyfloat)
2830 {
2831 PyObject *context;
2832 PyObject *result;
2833
2834 decimal_state *state = get_module_state_by_def((PyTypeObject *)type);
2835 CURRENT_CONTEXT(state, context);
2836 result = PyDecType_FromFloatExact(state->PyDec_Type, pyfloat, context);
2837 if (type != (PyObject *)state->PyDec_Type && result != NULL) {
2838 Py_SETREF(result, PyObject_CallFunctionObjArgs(type, result, NULL));
2839 }
2840
2841 return result;
2842 }
2843
2844 /* create_decimal_from_float */
2845 static PyObject *
2846 ctx_from_float(PyObject *context, PyObject *v)
2847 {
2848 decimal_state *state = get_module_state_by_def(Py_TYPE(context));
2849 return PyDec_FromFloat(state, v, context);
2850 }
2851
2852 /* Apply the context to the input operand. Return a new PyDecObject. */
2853 static PyObject *
2854 dec_apply(PyObject *v, PyObject *context)
2855 {
2856 PyObject *result;
2857 uint32_t status = 0;
2858
2859 decimal_state *state = get_module_state_by_def(Py_TYPE(context));
2860 result = dec_alloc(state);
2861 if (result == NULL) {
2862 return NULL;
2863 }
2864
2865 mpd_qcopy(MPD(result), MPD(v), &status);
2866 if (dec_addstatus(context, status)) {
2867 Py_DECREF(result);
2868 return NULL;
2869 }
2870
2871 mpd_qfinalize(MPD(result), CTX(context), &status);
2872 if (dec_addstatus(context, status)) {
2873 Py_DECREF(result);
2874 return NULL;
2875 }
2876
2877 return result;
2878 }
2879
2880 /* 'v' can have any type accepted by the Decimal constructor. Attempt
2881 an exact conversion. If the result does not meet the restrictions
2882 for an mpd_t, fail with InvalidOperation. */
2883 static PyObject *
2884 PyDecType_FromObjectExact(PyTypeObject *type, PyObject *v, PyObject *context)
2885 {
2886 decimal_state *state = get_module_state_by_def(type);
2887 if (v == NULL) {
2888 return PyDecType_FromSsizeExact(type, 0, context);
2889 }
2890 else if (PyDec_Check(state, v)) {
2891 return PyDecType_FromDecimalExact(type, v, context);
2892 }
2893 else if (PyUnicode_Check(v)) {
2894 return PyDecType_FromUnicodeExactWS(type, v, context);
2895 }
2896 else if (PyLong_Check(v)) {
2897 return PyDecType_FromLongExact(type, v, context);
2898 }
2899 else if (PyTuple_Check(v) || PyList_Check(v)) {
2900 return PyDecType_FromSequenceExact(type, v, context);
2901 }
2902 else if (PyFloat_Check(v)) {
2903 if (dec_addstatus(context, MPD_Float_operation)) {
2904 return NULL;
2905 }
2906 return PyDecType_FromFloatExact(type, v, context);
2907 }
2908 else {
2909 PyErr_Format(PyExc_TypeError,
2910 "conversion from %s to Decimal is not supported",
2911 Py_TYPE(v)->tp_name);
2912 return NULL;
2913 }
2914 }
2915
2916 /* The context is used during conversion. This function is the
2917 equivalent of context.create_decimal(). */
2918 static PyObject *
2919 PyDec_FromObject(PyObject *v, PyObject *context)
2920 {
2921 decimal_state *state = get_module_state_by_def(Py_TYPE(context));
2922 if (v == NULL) {
2923 return PyDec_FromSsize(state, 0, context);
2924 }
2925 else if (PyDec_Check(state, v)) {
2926 mpd_context_t *ctx = CTX(context);
2927 if (mpd_isnan(MPD(v)) &&
2928 MPD(v)->digits > ctx->prec - ctx->clamp) {
2929 /* Special case: too many NaN payload digits */
2930 PyObject *result;
2931 if (dec_addstatus(context, MPD_Conversion_syntax)) {
2932 return NULL;
2933 }
2934 result = dec_alloc(state);
2935 if (result == NULL) {
2936 return NULL;
2937 }
2938 mpd_setspecial(MPD(result), MPD_POS, MPD_NAN);
2939 return result;
2940 }
2941 return dec_apply(v, context);
2942 }
2943 else if (PyUnicode_Check(v)) {
2944 return PyDec_FromUnicode(state, v, context);
2945 }
2946 else if (PyLong_Check(v)) {
2947 return PyDec_FromLong(state, v, context);
2948 }
2949 else if (PyTuple_Check(v) || PyList_Check(v)) {
2950 return PyDec_FromSequence(state, v, context);
2951 }
2952 else if (PyFloat_Check(v)) {
2953 if (dec_addstatus(context, MPD_Float_operation)) {
2954 return NULL;
2955 }
2956 return PyDec_FromFloat(state, v, context);
2957 }
2958 else {
2959 PyErr_Format(PyExc_TypeError,
2960 "conversion from %s to Decimal is not supported",
2961 Py_TYPE(v)->tp_name);
2962 return NULL;
2963 }
2964 }
2965
2966 static PyObject *
2967 dec_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2968 {
2969 static char *kwlist[] = {"value", "context", NULL};
2970 PyObject *v = NULL;
2971 PyObject *context = Py_None;
2972
2973 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO", kwlist,
2974 &v, &context)) {
2975 return NULL;
2976 }
2977 decimal_state *state = get_module_state_by_def(type);
2978 CONTEXT_CHECK_VA(state, context);
2979
2980 return PyDecType_FromObjectExact(type, v, context);
2981 }
2982
2983 static PyObject *
2984 ctx_create_decimal(PyObject *context, PyObject *args)
2985 {
2986 PyObject *v = NULL;
2987
2988 if (!PyArg_ParseTuple(args, "|O", &v)) {
2989 return NULL;
2990 }
2991
2992 return PyDec_FromObject(v, context);
2993 }
2994
2995
2996 /******************************************************************************/
2997 /* Implicit conversions to Decimal */
2998 /******************************************************************************/
2999
3000 /* Try to convert PyObject v to a new PyDecObject conv. If the conversion
3001 fails, set conv to NULL (exception is set). If the conversion is not
3002 implemented, set conv to Py_NotImplemented. */
3003 #define NOT_IMPL 0
3004 #define TYPE_ERR 1
3005 Py_LOCAL_INLINE(int)
3006 convert_op(int type_err, PyObject **conv, PyObject *v, PyObject *context)
3007 {
3008 decimal_state *state = get_module_state_by_def(Py_TYPE(context));
3009 if (PyDec_Check(state, v)) {
3010 *conv = Py_NewRef(v);
3011 return 1;
3012 }
3013 if (PyLong_Check(v)) {
3014 *conv = PyDec_FromLongExact(state, v, context);
3015 if (*conv == NULL) {
3016 return 0;
3017 }
3018 return 1;
3019 }
3020
3021 if (type_err) {
3022 PyErr_Format(PyExc_TypeError,
3023 "conversion from %s to Decimal is not supported",
3024 Py_TYPE(v)->tp_name);
3025 }
3026 else {
3027 *conv = Py_NewRef(Py_NotImplemented);
3028 }
3029 return 0;
3030 }
3031
3032 /* Return NotImplemented for unsupported types. */
3033 #define CONVERT_OP(a, v, context) \
3034 if (!convert_op(NOT_IMPL, a, v, context)) { \
3035 return *(a); \
3036 }
3037
3038 #define CONVERT_BINOP(a, b, v, w, context) \
3039 if (!convert_op(NOT_IMPL, a, v, context)) { \
3040 return *(a); \
3041 } \
3042 if (!convert_op(NOT_IMPL, b, w, context)) { \
3043 Py_DECREF(*(a)); \
3044 return *(b); \
3045 }
3046
3047 #define CONVERT_TERNOP(a, b, c, v, w, x, context) \
3048 if (!convert_op(NOT_IMPL, a, v, context)) { \
3049 return *(a); \
3050 } \
3051 if (!convert_op(NOT_IMPL, b, w, context)) { \
3052 Py_DECREF(*(a)); \
3053 return *(b); \
3054 } \
3055 if (!convert_op(NOT_IMPL, c, x, context)) { \
3056 Py_DECREF(*(a)); \
3057 Py_DECREF(*(b)); \
3058 return *(c); \
3059 }
3060
3061 /* Raise TypeError for unsupported types. */
3062 #define CONVERT_OP_RAISE(a, v, context) \
3063 if (!convert_op(TYPE_ERR, a, v, context)) { \
3064 return NULL; \
3065 }
3066
3067 #define CONVERT_BINOP_RAISE(a, b, v, w, context) \
3068 if (!convert_op(TYPE_ERR, a, v, context)) { \
3069 return NULL; \
3070 } \
3071 if (!convert_op(TYPE_ERR, b, w, context)) { \
3072 Py_DECREF(*(a)); \
3073 return NULL; \
3074 }
3075
3076 #define CONVERT_TERNOP_RAISE(a, b, c, v, w, x, context) \
3077 if (!convert_op(TYPE_ERR, a, v, context)) { \
3078 return NULL; \
3079 } \
3080 if (!convert_op(TYPE_ERR, b, w, context)) { \
3081 Py_DECREF(*(a)); \
3082 return NULL; \
3083 } \
3084 if (!convert_op(TYPE_ERR, c, x, context)) { \
3085 Py_DECREF(*(a)); \
3086 Py_DECREF(*(b)); \
3087 return NULL; \
3088 }
3089
3090
3091 /******************************************************************************/
3092 /* Implicit conversions to Decimal for comparison */
3093 /******************************************************************************/
3094
3095 static PyObject *
3096 multiply_by_denominator(PyObject *v, PyObject *r, PyObject *context)
3097 {
3098 PyObject *result;
3099 PyObject *tmp = NULL;
3100 PyObject *denom = NULL;
3101 uint32_t status = 0;
3102 mpd_context_t maxctx;
3103 mpd_ssize_t exp;
3104 mpd_t *vv;
3105
3106 /* v is not special, r is a rational */
3107 tmp = PyObject_GetAttrString(r, "denominator");
3108 if (tmp == NULL) {
3109 return NULL;
3110 }
3111 decimal_state *state = get_module_state_by_def(Py_TYPE(context));
3112 denom = PyDec_FromLongExact(state, tmp, context);
3113 Py_DECREF(tmp);
3114 if (denom == NULL) {
3115 return NULL;
3116 }
3117
3118 vv = mpd_qncopy(MPD(v));
3119 if (vv == NULL) {
3120 Py_DECREF(denom);
3121 PyErr_NoMemory();
3122 return NULL;
3123 }
3124 result = dec_alloc(state);
3125 if (result == NULL) {
3126 Py_DECREF(denom);
3127 mpd_del(vv);
3128 return NULL;
3129 }
3130
3131 mpd_maxcontext(&maxctx);
3132 /* Prevent Overflow in the following multiplication. The result of
3133 the multiplication is only used in mpd_qcmp, which can handle
3134 values that are technically out of bounds, like (for 32-bit)
3135 99999999999999999999...99999999e+425000000. */
3136 exp = vv->exp;
3137 vv->exp = 0;
3138 mpd_qmul(MPD(result), vv, MPD(denom), &maxctx, &status);
3139 MPD(result)->exp = exp;
3140
3141 Py_DECREF(denom);
3142 mpd_del(vv);
3143 /* If any status has been accumulated during the multiplication,
3144 the result is invalid. This is very unlikely, since even the
3145 32-bit version supports 425000000 digits. */
3146 if (status) {
3147 PyErr_SetString(PyExc_ValueError,
3148 "exact conversion for comparison failed");
3149 Py_DECREF(result);
3150 return NULL;
3151 }
3152
3153 return result;
3154 }
3155
3156 static PyObject *
3157 numerator_as_decimal(PyObject *r, PyObject *context)
3158 {
3159 PyObject *tmp, *num;
3160
3161 tmp = PyObject_GetAttrString(r, "numerator");
3162 if (tmp == NULL) {
3163 return NULL;
3164 }
3165
3166 decimal_state *state = get_module_state_by_def(Py_TYPE(context));
3167 num = PyDec_FromLongExact(state, tmp, context);
3168 Py_DECREF(tmp);
3169 return num;
3170 }
3171
3172 /* Convert v and w for comparison. v is a Decimal. If w is a Rational, both
3173 v and w have to be transformed. Return 1 for success, with new references
3174 to the converted objects in vcmp and wcmp. Return 0 for failure. In that
3175 case wcmp is either NULL or Py_NotImplemented (new reference) and vcmp
3176 is undefined. */
3177 static int
3178 convert_op_cmp(PyObject **vcmp, PyObject **wcmp, PyObject *v, PyObject *w,
3179 int op, PyObject *context)
3180 {
3181 mpd_context_t *ctx = CTX(context);
3182
3183 *vcmp = v;
3184
3185 decimal_state *state = get_module_state_by_def(Py_TYPE(context));
3186 if (PyDec_Check(state, w)) {
3187 *wcmp = Py_NewRef(w);
3188 }
3189 else if (PyLong_Check(w)) {
3190 *wcmp = PyDec_FromLongExact(state, w, context);
3191 }
3192 else if (PyFloat_Check(w)) {
3193 if (op != Py_EQ && op != Py_NE &&
3194 dec_addstatus(context, MPD_Float_operation)) {
3195 *wcmp = NULL;
3196 }
3197 else {
3198 ctx->status |= MPD_Float_operation;
3199 *wcmp = PyDec_FromFloatExact(state, w, context);
3200 }
3201 }
3202 else if (PyComplex_Check(w) && (op == Py_EQ || op == Py_NE)) {
3203 Py_complex c = PyComplex_AsCComplex(w);
3204 if (c.real == -1.0 && PyErr_Occurred()) {
3205 *wcmp = NULL;
3206 }
3207 else if (c.imag == 0.0) {
3208 PyObject *tmp = PyFloat_FromDouble(c.real);
3209 if (tmp == NULL) {
3210 *wcmp = NULL;
3211 }
3212 else {
3213 ctx->status |= MPD_Float_operation;
3214 *wcmp = PyDec_FromFloatExact(state, tmp, context);
3215 Py_DECREF(tmp);
3216 }
3217 }
3218 else {
3219 *wcmp = Py_NewRef(Py_NotImplemented);
3220 }
3221 }
3222 else {
3223 int is_rational = PyObject_IsInstance(w, state->Rational);
3224 if (is_rational < 0) {
3225 *wcmp = NULL;
3226 }
3227 else if (is_rational > 0) {
3228 *wcmp = numerator_as_decimal(w, context);
3229 if (*wcmp && !mpd_isspecial(MPD(v))) {
3230 *vcmp = multiply_by_denominator(v, w, context);
3231 if (*vcmp == NULL) {
3232 Py_CLEAR(*wcmp);
3233 }
3234 }
3235 }
3236 else {
3237 *wcmp = Py_NewRef(Py_NotImplemented);
3238 }
3239 }
3240
3241 if (*wcmp == NULL || *wcmp == Py_NotImplemented) {
3242 return 0;
3243 }
3244 if (*vcmp == v) {
3245 Py_INCREF(v);
3246 }
3247 return 1;
3248 }
3249
3250 #define CONVERT_BINOP_CMP(vcmp, wcmp, v, w, op, ctx) \
3251 if (!convert_op_cmp(vcmp, wcmp, v, w, op, ctx)) { \
3252 return *(wcmp); \
3253 } \
3254
3255
3256 /******************************************************************************/
3257 /* Conversions from decimal */
3258 /******************************************************************************/
3259
3260 static PyObject *
3261 unicode_fromascii(const char *s, Py_ssize_t size)
3262 {
3263 PyObject *res;
3264
3265 res = PyUnicode_New(size, 127);
3266 if (res == NULL) {
3267 return NULL;
3268 }
3269
3270 memcpy(PyUnicode_1BYTE_DATA(res), s, size);
3271 return res;
3272 }
3273
3274 /* PyDecObject as a string. The default module context is only used for
3275 the value of 'capitals'. */
3276 static PyObject *
3277 dec_str(PyObject *dec)
3278 {
3279 PyObject *res, *context;
3280 mpd_ssize_t size;
3281 char *cp;
3282
3283 decimal_state *state = get_module_state_by_def(Py_TYPE(dec));
3284 CURRENT_CONTEXT(state, context);
3285 size = mpd_to_sci_size(&cp, MPD(dec), CtxCaps(context));
3286 if (size < 0) {
3287 PyErr_NoMemory();
3288 return NULL;
3289 }
3290
3291 res = unicode_fromascii(cp, size);
3292 mpd_free(cp);
3293 return res;
3294 }
3295
3296 /* Representation of a PyDecObject. */
3297 static PyObject *
3298 dec_repr(PyObject *dec)
3299 {
3300 PyObject *res, *context;
3301 char *cp;
3302 decimal_state *state = get_module_state_by_def(Py_TYPE(dec));
3303 CURRENT_CONTEXT(state, context);
3304 cp = mpd_to_sci(MPD(dec), CtxCaps(context));
3305 if (cp == NULL) {
3306 PyErr_NoMemory();
3307 return NULL;
3308 }
3309
3310 res = PyUnicode_FromFormat("Decimal('%s')", cp);
3311 mpd_free(cp);
3312 return res;
3313 }
3314
3315 /* Return a duplicate of src, copy embedded null characters. */
3316 static char *
3317 dec_strdup(const char *src, Py_ssize_t size)
3318 {
3319 char *dest = PyMem_Malloc(size+1);
3320 if (dest == NULL) {
3321 PyErr_NoMemory();
3322 return NULL;
3323 }
3324
3325 memcpy(dest, src, size);
3326 dest[size] = '\0';
3327 return dest;
3328 }
3329
3330 static void
3331 dec_replace_fillchar(char *dest)
3332 {
3333 while (*dest != '\0') {
3334 if (*dest == '\xff') *dest = '\0';
3335 dest++;
3336 }
3337 }
3338
3339 /* Convert decimal_point or thousands_sep, which may be multibyte or in
3340 the range [128, 255], to a UTF8 string. */
3341 static PyObject *
3342 dotsep_as_utf8(const char *s)
3343 {
3344 PyObject *utf8;
3345 PyObject *tmp;
3346 wchar_t buf[2];
3347 size_t n;
3348
3349 n = mbstowcs(buf, s, 2);
3350 if (n != 1) { /* Issue #7442 */
3351 PyErr_SetString(PyExc_ValueError,
3352 "invalid decimal point or unsupported "
3353 "combination of LC_CTYPE and LC_NUMERIC");
3354 return NULL;
3355 }
3356 tmp = PyUnicode_FromWideChar(buf, n);
3357 if (tmp == NULL) {
3358 return NULL;
3359 }
3360 utf8 = PyUnicode_AsUTF8String(tmp);
3361 Py_DECREF(tmp);
3362 return utf8;
3363 }
3364
3365 static int
3366 dict_get_item_string(PyObject *dict, const char *key, PyObject **valueobj, const char **valuestr)
3367 {
3368 *valueobj = NULL;
3369 PyObject *keyobj = PyUnicode_FromString(key);
3370 if (keyobj == NULL) {
3371 return -1;
3372 }
3373 PyObject *value = PyDict_GetItemWithError(dict, keyobj);
3374 Py_DECREF(keyobj);
3375 if (value == NULL) {
3376 if (PyErr_Occurred()) {
3377 return -1;
3378 }
3379 return 0;
3380 }
3381 value = PyUnicode_AsUTF8String(value);
3382 if (value == NULL) {
3383 return -1;
3384 }
3385 *valueobj = value;
3386 *valuestr = PyBytes_AS_STRING(value);
3387 return 0;
3388 }
3389
3390 /*
3391 * Fallback _pydecimal formatting for new format specifiers that mpdecimal does
3392 * not yet support. As documented, libmpdec follows the PEP-3101 format language:
3393 * https://www.bytereef.org/mpdecimal/doc/libmpdec/assign-convert.html#to-string
3394 */
3395 static PyObject *
3396 pydec_format(PyObject *dec, PyObject *context, PyObject *fmt, decimal_state *state)
3397 {
3398 PyObject *result;
3399 PyObject *pydec;
3400 PyObject *u;
3401
3402 if (state->PyDecimal == NULL) {
3403 state->PyDecimal = _PyImport_GetModuleAttrString("_pydecimal", "Decimal");
3404 if (state->PyDecimal == NULL) {
3405 return NULL;
3406 }
3407 }
3408
3409 u = dec_str(dec);
3410 if (u == NULL) {
3411 return NULL;
3412 }
3413
3414 pydec = PyObject_CallOneArg(state->PyDecimal, u);
3415 Py_DECREF(u);
3416 if (pydec == NULL) {
3417 return NULL;
3418 }
3419
3420 result = PyObject_CallMethod(pydec, "__format__", "(OO)", fmt, context);
3421 Py_DECREF(pydec);
3422
3423 if (result == NULL && PyErr_ExceptionMatches(PyExc_ValueError)) {
3424 /* Do not confuse users with the _pydecimal exception */
3425 PyErr_Clear();
3426 PyErr_SetString(PyExc_ValueError, "invalid format string");
3427 }
3428
3429 return result;
3430 }
3431
3432 /* Formatted representation of a PyDecObject. */
3433 static PyObject *
3434 dec_format(PyObject *dec, PyObject *args)
3435 {
3436 PyObject *result = NULL;
3437 PyObject *override = NULL;
3438 PyObject *dot = NULL;
3439 PyObject *sep = NULL;
3440 PyObject *grouping = NULL;
3441 PyObject *fmtarg;
3442 PyObject *context;
3443 mpd_spec_t spec;
3444 char *fmt;
3445 char *decstring = NULL;
3446 uint32_t status = 0;
3447 int replace_fillchar = 0;
3448 Py_ssize_t size;
3449
3450
3451 decimal_state *state = get_module_state_by_def(Py_TYPE(dec));
3452 CURRENT_CONTEXT(state, context);
3453 if (!PyArg_ParseTuple(args, "O|O", &fmtarg, &override)) {
3454 return NULL;
3455 }
3456
3457 if (PyUnicode_Check(fmtarg)) {
3458 fmt = (char *)PyUnicode_AsUTF8AndSize(fmtarg, &size);
3459 if (fmt == NULL) {
3460 return NULL;
3461 }
3462
3463 if (size > 0 && fmt[size-1] == 'N') {
3464 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3465 "Format specifier 'N' is deprecated and "
3466 "slated for removal in Python 3.18", 1) < 0) {
3467 return NULL;
3468 }
3469 }
3470
3471 if (size > 0 && fmt[0] == '\0') {
3472 /* NUL fill character: must be replaced with a valid UTF-8 char
3473 before calling mpd_parse_fmt_str(). */
3474 replace_fillchar = 1;
3475 fmt = dec_strdup(fmt, size);
3476 if (fmt == NULL) {
3477 return NULL;
3478 }
3479 fmt[0] = '_';
3480 }
3481 }
3482 else {
3483 PyErr_SetString(PyExc_TypeError,
3484 "format arg must be str");
3485 return NULL;
3486 }
3487
3488 if (!mpd_parse_fmt_str(&spec, fmt, CtxCaps(context))) {
3489 if (replace_fillchar) {
3490 PyMem_Free(fmt);
3491 }
3492
3493 return pydec_format(dec, context, fmtarg, state);
3494 }
3495
3496 if (replace_fillchar) {
3497 /* In order to avoid clobbering parts of UTF-8 thousands separators or
3498 decimal points when the substitution is reversed later, the actual
3499 placeholder must be an invalid UTF-8 byte. */
3500 spec.fill[0] = '\xff';
3501 spec.fill[1] = '\0';
3502 }
3503
3504 if (override) {
3505 /* Values for decimal_point, thousands_sep and grouping can
3506 be explicitly specified in the override dict. These values
3507 take precedence over the values obtained from localeconv()
3508 in mpd_parse_fmt_str(). The feature is not documented and
3509 is only used in test_decimal. */
3510 if (!PyDict_Check(override)) {
3511 PyErr_SetString(PyExc_TypeError,
3512 "optional argument must be a dict");
3513 goto finish;
3514 }
3515 if (dict_get_item_string(override, "decimal_point", &dot, &spec.dot) ||
3516 dict_get_item_string(override, "thousands_sep", &sep, &spec.sep) ||
3517 dict_get_item_string(override, "grouping", &grouping, &spec.grouping))
3518 {
3519 goto finish;
3520 }
3521 if (mpd_validate_lconv(&spec) < 0) {
3522 PyErr_SetString(PyExc_ValueError,
3523 "invalid override dict");
3524 goto finish;
3525 }
3526 }
3527 else {
3528 size_t n = strlen(spec.dot);
3529 if (n > 1 || (n == 1 && !isascii((unsigned char)spec.dot[0]))) {
3530 /* fix locale dependent non-ascii characters */
3531 dot = dotsep_as_utf8(spec.dot);
3532 if (dot == NULL) {
3533 goto finish;
3534 }
3535 spec.dot = PyBytes_AS_STRING(dot);
3536 }
3537 n = strlen(spec.sep);
3538 if (n > 1 || (n == 1 && !isascii((unsigned char)spec.sep[0]))) {
3539 /* fix locale dependent non-ascii characters */
3540 sep = dotsep_as_utf8(spec.sep);
3541 if (sep == NULL) {
3542 goto finish;
3543 }
3544 spec.sep = PyBytes_AS_STRING(sep);
3545 }
3546 }
3547
3548
3549 decstring = mpd_qformat_spec(MPD(dec), &spec, CTX(context), &status);
3550 if (decstring == NULL) {
3551 if (status & MPD_Malloc_error) {
3552 PyErr_NoMemory();
3553 }
3554 else {
3555 PyErr_SetString(PyExc_ValueError,
3556 "format specification exceeds internal limits of _decimal");
3557 }
3558 goto finish;
3559 }
3560 size = strlen(decstring);
3561 if (replace_fillchar) {
3562 dec_replace_fillchar(decstring);
3563 }
3564
3565 result = PyUnicode_DecodeUTF8(decstring, size, NULL);
3566
3567
3568 finish:
3569 Py_XDECREF(grouping);
3570 Py_XDECREF(sep);
3571 Py_XDECREF(dot);
3572 if (replace_fillchar) PyMem_Free(fmt);
3573 if (decstring) mpd_free(decstring);
3574 return result;
3575 }
3576
3577 /* Return a PyLongObject from a PyDecObject, using the specified rounding
3578 * mode. The context precision is not observed. */
3579 static PyObject *
3580 dec_as_long(PyObject *dec, PyObject *context, int round)
3581 {
3582 PyLongObject *pylong;
3583 digit *ob_digit;
3584 size_t n;
3585 mpd_t *x;
3586 mpd_context_t workctx;
3587 uint32_t status = 0;
3588
3589 if (mpd_isspecial(MPD(dec))) {
3590 if (mpd_isnan(MPD(dec))) {
3591 PyErr_SetString(PyExc_ValueError,
3592 "cannot convert NaN to integer");
3593 }
3594 else {
3595 PyErr_SetString(PyExc_OverflowError,
3596 "cannot convert Infinity to integer");
3597 }
3598 return NULL;
3599 }
3600
3601 x = mpd_qnew();
3602 if (x == NULL) {
3603 PyErr_NoMemory();
3604 return NULL;
3605 }
3606 workctx = *CTX(context);
3607 workctx.round = round;
3608 mpd_qround_to_int(x, MPD(dec), &workctx, &status);
3609 if (dec_addstatus(context, status)) {
3610 mpd_del(x);
3611 return NULL;
3612 }
3613
3614 status = 0;
3615 ob_digit = NULL;
3616 #if PYLONG_BITS_IN_DIGIT == 30
3617 n = mpd_qexport_u32(&ob_digit, 0, PyLong_BASE, x, &status);
3618 #elif PYLONG_BITS_IN_DIGIT == 15
3619 n = mpd_qexport_u16(&ob_digit, 0, PyLong_BASE, x, &status);
3620 #else
3621 #error "PYLONG_BITS_IN_DIGIT should be 15 or 30"
3622 #endif
3623
3624 if (n == SIZE_MAX) {
3625 PyErr_NoMemory();
3626 mpd_del(x);
3627 return NULL;
3628 }
3629
3630 if (n == 1) {
3631 sdigit val = mpd_arith_sign(x) * ob_digit[0];
3632 mpd_free(ob_digit);
3633 mpd_del(x);
3634 return PyLong_FromLong(val);
3635 }
3636
3637 assert(n > 0);
3638 assert(!mpd_iszero(x));
3639 pylong = _PyLong_FromDigits(mpd_isnegative(x), n, ob_digit);
3640 mpd_free(ob_digit);
3641 mpd_del(x);
3642 return (PyObject *) pylong;
3643 }
3644
3645 /* Convert a Decimal to its exact integer ratio representation. */
3646 static PyObject *
3647 dec_as_integer_ratio(PyObject *self, PyObject *args UNUSED)
3648 {
3649 PyObject *numerator = NULL;
3650 PyObject *denominator = NULL;
3651 PyObject *exponent = NULL;
3652 PyObject *result = NULL;
3653 PyObject *tmp;
3654 mpd_ssize_t exp;
3655 PyObject *context;
3656 uint32_t status = 0;
3657
3658 if (mpd_isspecial(MPD(self))) {
3659 if (mpd_isnan(MPD(self))) {
3660 PyErr_SetString(PyExc_ValueError,
3661 "cannot convert NaN to integer ratio");
3662 }
3663 else {
3664 PyErr_SetString(PyExc_OverflowError,
3665 "cannot convert Infinity to integer ratio");
3666 }
3667 return NULL;
3668 }
3669
3670 decimal_state *state = get_module_state_by_def(Py_TYPE(self));
3671 CURRENT_CONTEXT(state, context);
3672
3673 tmp = dec_alloc(state);
3674 if (tmp == NULL) {
3675 return NULL;
3676 }
3677
3678 if (!mpd_qcopy(MPD(tmp), MPD(self), &status)) {
3679 Py_DECREF(tmp);
3680 PyErr_NoMemory();
3681 return NULL;
3682 }
3683
3684 exp = mpd_iszero(MPD(tmp)) ? 0 : MPD(tmp)->exp;
3685 MPD(tmp)->exp = 0;
3686
3687 /* context and rounding are unused here: the conversion is exact */
3688 numerator = dec_as_long(tmp, context, MPD_ROUND_FLOOR);
3689 Py_DECREF(tmp);
3690 if (numerator == NULL) {
3691 goto error;
3692 }
3693
3694 exponent = PyLong_FromSsize_t(exp < 0 ? -exp : exp);
3695 if (exponent == NULL) {
3696 goto error;
3697 }
3698
3699 tmp = PyLong_FromLong(10);
3700 if (tmp == NULL) {
3701 goto error;
3702 }
3703
3704 Py_SETREF(exponent, state->_py_long_power(tmp, exponent, Py_None));
3705 Py_DECREF(tmp);
3706 if (exponent == NULL) {
3707 goto error;
3708 }
3709
3710 if (exp >= 0) {
3711 Py_SETREF(numerator, state->_py_long_multiply(numerator, exponent));
3712 if (numerator == NULL) {
3713 goto error;
3714 }
3715 denominator = PyLong_FromLong(1);
3716 if (denominator == NULL) {
3717 goto error;
3718 }
3719 }
3720 else {
3721 denominator = exponent;
3722 exponent = NULL;
3723 tmp = _PyLong_GCD(numerator, denominator);
3724 if (tmp == NULL) {
3725 goto error;
3726 }
3727 Py_SETREF(numerator, state->_py_long_floor_divide(numerator, tmp));
3728 if (numerator == NULL) {
3729 Py_DECREF(tmp);
3730 goto error;
3731 }
3732 Py_SETREF(denominator, state->_py_long_floor_divide(denominator, tmp));
3733 Py_DECREF(tmp);
3734 if (denominator == NULL) {
3735 goto error;
3736 }
3737 }
3738
3739 result = PyTuple_Pack(2, numerator, denominator);
3740
3741
3742 error:
3743 Py_XDECREF(exponent);
3744 Py_XDECREF(denominator);
3745 Py_XDECREF(numerator);
3746 return result;
3747 }
3748
3749 static PyObject *
3750 PyDec_ToIntegralValue(PyObject *dec, PyObject *args, PyObject *kwds)
3751 {
3752 static char *kwlist[] = {"rounding", "context", NULL};
3753 PyObject *result;
3754 PyObject *rounding = Py_None;
3755 PyObject *context = Py_None;
3756 uint32_t status = 0;
3757 mpd_context_t workctx;
3758
3759 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO", kwlist,
3760 &rounding, &context)) {
3761 return NULL;
3762 }
3763 decimal_state *state = get_module_state_by_def(Py_TYPE(dec));
3764 CONTEXT_CHECK_VA(state, context);
3765
3766 workctx = *CTX(context);
3767 if (rounding != Py_None) {
3768 int round = getround(state, rounding);
3769 if (round < 0) {
3770 return NULL;
3771 }
3772 if (!mpd_qsetround(&workctx, round)) {
3773 INTERNAL_ERROR_PTR("PyDec_ToIntegralValue"); /* GCOV_NOT_REACHED */
3774 }
3775 }
3776
3777 result = dec_alloc(state);
3778 if (result == NULL) {
3779 return NULL;
3780 }
3781
3782 mpd_qround_to_int(MPD(result), MPD(dec), &workctx, &status);
3783 if (dec_addstatus(context, status)) {
3784 Py_DECREF(result);
3785 return NULL;
3786 }
3787
3788 return result;
3789 }
3790
3791 static PyObject *
3792 PyDec_ToIntegralExact(PyObject *dec, PyObject *args, PyObject *kwds)
3793 {
3794 static char *kwlist[] = {"rounding", "context", NULL};
3795 PyObject *result;
3796 PyObject *rounding = Py_None;
3797 PyObject *context = Py_None;
3798 uint32_t status = 0;
3799 mpd_context_t workctx;
3800
3801 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO", kwlist,
3802 &rounding, &context)) {
3803 return NULL;
3804 }
3805 decimal_state *state = get_module_state_by_def(Py_TYPE(dec));
3806 CONTEXT_CHECK_VA(state, context);
3807
3808 workctx = *CTX(context);
3809 if (rounding != Py_None) {
3810 int round = getround(state, rounding);
3811 if (round < 0) {
3812 return NULL;
3813 }
3814 if (!mpd_qsetround(&workctx, round)) {
3815 INTERNAL_ERROR_PTR("PyDec_ToIntegralExact"); /* GCOV_NOT_REACHED */
3816 }
3817 }
3818
3819 result = dec_alloc(state);
3820 if (result == NULL) {
3821 return NULL;
3822 }
3823
3824 mpd_qround_to_intx(MPD(result), MPD(dec), &workctx, &status);
3825 if (dec_addstatus(context, status)) {
3826 Py_DECREF(result);
3827 return NULL;
3828 }
3829
3830 return result;
3831 }
3832
3833 static PyObject *
3834 PyDec_AsFloat(PyObject *dec)
3835 {
3836 PyObject *f, *s;
3837
3838 if (mpd_isnan(MPD(dec))) {
3839 if (mpd_issnan(MPD(dec))) {
3840 PyErr_SetString(PyExc_ValueError,
3841 "cannot convert signaling NaN to float");
3842 return NULL;
3843 }
3844 if (mpd_isnegative(MPD(dec))) {
3845 s = PyUnicode_FromString("-nan");
3846 }
3847 else {
3848 s = PyUnicode_FromString("nan");
3849 }
3850 }
3851 else {
3852 s = dec_str(dec);
3853 }
3854
3855 if (s == NULL) {
3856 return NULL;
3857 }
3858
3859 f = PyFloat_FromString(s);
3860 Py_DECREF(s);
3861
3862 return f;
3863 }
3864
3865 static PyObject *
3866 PyDec_Round(PyObject *dec, PyObject *args)
3867 {
3868 PyObject *result;
3869 PyObject *x = NULL;
3870 uint32_t status = 0;
3871 PyObject *context;
3872
3873 decimal_state *state = get_module_state_by_def(Py_TYPE(dec));
3874 CURRENT_CONTEXT(state, context);
3875 if (!PyArg_ParseTuple(args, "|O", &x)) {
3876 return NULL;
3877 }
3878
3879 if (x) {
3880 mpd_uint_t dq[1] = {1};
3881 mpd_t q = {MPD_STATIC|MPD_CONST_DATA,0,1,1,1,dq};
3882 mpd_ssize_t y;
3883
3884 if (!PyLong_Check(x)) {
3885 PyErr_SetString(PyExc_TypeError,
3886 "optional arg must be an integer");
3887 return NULL;
3888 }
3889
3890 y = PyLong_AsSsize_t(x);
3891 if (y == -1 && PyErr_Occurred()) {
3892 return NULL;
3893 }
3894 result = dec_alloc(state);
3895 if (result == NULL) {
3896 return NULL;
3897 }
3898
3899 q.exp = (y == MPD_SSIZE_MIN) ? MPD_SSIZE_MAX : -y;
3900 mpd_qquantize(MPD(result), MPD(dec), &q, CTX(context), &status);
3901 if (dec_addstatus(context, status)) {
3902 Py_DECREF(result);
3903 return NULL;
3904 }
3905
3906 return result;
3907 }
3908 else {
3909 return dec_as_long(dec, context, MPD_ROUND_HALF_EVEN);
3910 }
3911 }
3912
3913 /* Return the DecimalTuple representation of a PyDecObject. */
3914 static PyObject *
3915 PyDec_AsTuple(PyObject *dec, PyObject *dummy UNUSED)
3916 {
3917 PyObject *result = NULL;
3918 PyObject *sign = NULL;
3919 PyObject *coeff = NULL;
3920 PyObject *expt = NULL;
3921 PyObject *tmp = NULL;
3922 mpd_t *x = NULL;
3923 char *intstring = NULL;
3924 Py_ssize_t intlen, i;
3925
3926
3927 x = mpd_qncopy(MPD(dec));
3928 if (x == NULL) {
3929 PyErr_NoMemory();
3930 goto out;
3931 }
3932
3933 sign = PyLong_FromUnsignedLong(mpd_sign(MPD(dec)));
3934 if (sign == NULL) {
3935 goto out;
3936 }
3937
3938 if (mpd_isinfinite(x)) {
3939 expt = PyUnicode_FromString("F");
3940 if (expt == NULL) {
3941 goto out;
3942 }
3943 /* decimal.py has non-compliant infinity payloads. */
3944 coeff = Py_BuildValue("(i)", 0);
3945 if (coeff == NULL) {
3946 goto out;
3947 }
3948 }
3949 else {
3950 if (mpd_isnan(x)) {
3951 expt = PyUnicode_FromString(mpd_isqnan(x)?"n":"N");
3952 }
3953 else {
3954 expt = PyLong_FromSsize_t(MPD(dec)->exp);
3955 }
3956 if (expt == NULL) {
3957 goto out;
3958 }
3959
3960 /* coefficient is defined */
3961 if (x->len > 0) {
3962
3963 /* make an integer */
3964 x->exp = 0;
3965 /* clear NaN and sign */
3966 mpd_clear_flags(x);
3967 intstring = mpd_to_sci(x, 1);
3968 if (intstring == NULL) {
3969 PyErr_NoMemory();
3970 goto out;
3971 }
3972
3973 intlen = strlen(intstring);
3974 coeff = PyTuple_New(intlen);
3975 if (coeff == NULL) {
3976 goto out;
3977 }
3978
3979 for (i = 0; i < intlen; i++) {
3980 tmp = PyLong_FromLong(intstring[i]-'0');
3981 if (tmp == NULL) {
3982 goto out;
3983 }
3984 PyTuple_SET_ITEM(coeff, i, tmp);
3985 }
3986 }
3987 else {
3988 coeff = PyTuple_New(0);
3989 if (coeff == NULL) {
3990 goto out;
3991 }
3992 }
3993 }
3994
3995 decimal_state *state = get_module_state_by_def(Py_TYPE(dec));
3996 result = PyObject_CallFunctionObjArgs((PyObject *)state->DecimalTuple,
3997 sign, coeff, expt, NULL);
3998
3999 out:
4000 if (x) mpd_del(x);
4001 if (intstring) mpd_free(intstring);
4002 Py_XDECREF(sign);
4003 Py_XDECREF(coeff);
4004 Py_XDECREF(expt);
4005 return result;
4006 }
4007
4008
4009 /******************************************************************************/
4010 /* Macros for converting mpdecimal functions to Decimal methods */
4011 /******************************************************************************/
4012
4013 /* Unary number method that uses the default module context. */
4014 #define Dec_UnaryNumberMethod(MPDFUNC) \
4015 static PyObject * \
4016 nm_##MPDFUNC(PyObject *self) \
4017 { \
4018 PyObject *result; \
4019 PyObject *context; \
4020 uint32_t status = 0; \
4021 \
4022 decimal_state *state = get_module_state_by_def(Py_TYPE(self)); \
4023 CURRENT_CONTEXT(state, context); \
4024 if ((result = dec_alloc(state)) == NULL) { \
4025 return NULL; \
4026 } \
4027 \
4028 MPDFUNC(MPD(result), MPD(self), CTX(context), &status); \
4029 if (dec_addstatus(context, status)) { \
4030 Py_DECREF(result); \
4031 return NULL; \
4032 } \
4033 \
4034 return result; \
4035 }
4036
4037 /* Binary number method that uses default module context. */
4038 #define Dec_BinaryNumberMethod(MPDFUNC) \
4039 static PyObject * \
4040 nm_##MPDFUNC(PyObject *self, PyObject *other) \
4041 { \
4042 PyObject *a, *b; \
4043 PyObject *result; \
4044 PyObject *context; \
4045 uint32_t status = 0; \
4046 \
4047 decimal_state *state = find_state_left_or_right(self, other); \
4048 CURRENT_CONTEXT(state, context) ; \
4049 CONVERT_BINOP(&a, &b, self, other, context); \
4050 \
4051 if ((result = dec_alloc(state)) == NULL) { \
4052 Py_DECREF(a); \
4053 Py_DECREF(b); \
4054 return NULL; \
4055 } \
4056 \
4057 MPDFUNC(MPD(result), MPD(a), MPD(b), CTX(context), &status); \
4058 Py_DECREF(a); \
4059 Py_DECREF(b); \
4060 if (dec_addstatus(context, status)) { \
4061 Py_DECREF(result); \
4062 return NULL; \
4063 } \
4064 \
4065 return result; \
4066 }
4067
4068 /* Boolean function without a context arg. */
4069 #define Dec_BoolFunc(MPDFUNC) \
4070 static PyObject * \
4071 dec_##MPDFUNC(PyObject *self, PyObject *dummy UNUSED) \
4072 { \
4073 return MPDFUNC(MPD(self)) ? incr_true() : incr_false(); \
4074 }
4075
4076 /* Boolean function with an optional context arg. */
4077 #define Dec_BoolFuncVA(MPDFUNC) \
4078 static PyObject * \
4079 dec_##MPDFUNC(PyObject *self, PyObject *args, PyObject *kwds) \
4080 { \
4081 static char *kwlist[] = {"context", NULL}; \
4082 PyObject *context = Py_None; \
4083 \
4084 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O", kwlist, \
4085 &context)) { \
4086 return NULL; \
4087 } \
4088 decimal_state *state = get_module_state_by_def(Py_TYPE(self)); \
4089 CONTEXT_CHECK_VA(state, context); \
4090 \
4091 return MPDFUNC(MPD(self), CTX(context)) ? incr_true() : incr_false(); \
4092 }
4093
4094 /* Unary function with an optional context arg. */
4095 #define Dec_UnaryFuncVA(MPDFUNC) \
4096 static PyObject * \
4097 dec_##MPDFUNC(PyObject *self, PyObject *args, PyObject *kwds) \
4098 { \
4099 static char *kwlist[] = {"context", NULL}; \
4100 PyObject *result; \
4101 PyObject *context = Py_None; \
4102 uint32_t status = 0; \
4103 \
4104 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O", kwlist, \
4105 &context)) { \
4106 return NULL; \
4107 } \
4108 decimal_state *state = \
4109 get_module_state_by_def(Py_TYPE(self)); \
4110 CONTEXT_CHECK_VA(state, context); \
4111 \
4112 if ((result = dec_alloc(state)) == NULL) { \
4113 return NULL; \
4114 } \
4115 \
4116 MPDFUNC(MPD(result), MPD(self), CTX(context), &status); \
4117 if (dec_addstatus(context, status)) { \
4118 Py_DECREF(result); \
4119 return NULL; \
4120 } \
4121 \
4122 return result; \
4123 }
4124
4125 /* Binary function with an optional context arg. */
4126 #define Dec_BinaryFuncVA(MPDFUNC) \
4127 static PyObject * \
4128 dec_##MPDFUNC(PyObject *self, PyObject *args, PyObject *kwds) \
4129 { \
4130 static char *kwlist[] = {"other", "context", NULL}; \
4131 PyObject *other; \
4132 PyObject *a, *b; \
4133 PyObject *result; \
4134 PyObject *context = Py_None; \
4135 uint32_t status = 0; \
4136 \
4137 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O", kwlist, \
4138 &other, &context)) { \
4139 return NULL; \
4140 } \
4141 decimal_state *state = \
4142 get_module_state_by_def(Py_TYPE(self)); \
4143 CONTEXT_CHECK_VA(state, context); \
4144 CONVERT_BINOP_RAISE(&a, &b, self, other, context); \
4145 \
4146 if ((result = dec_alloc(state)) == NULL) { \
4147 Py_DECREF(a); \
4148 Py_DECREF(b); \
4149 return NULL; \
4150 } \
4151 \
4152 MPDFUNC(MPD(result), MPD(a), MPD(b), CTX(context), &status); \
4153 Py_DECREF(a); \
4154 Py_DECREF(b); \
4155 if (dec_addstatus(context, status)) { \
4156 Py_DECREF(result); \
4157 return NULL; \
4158 } \
4159 \
4160 return result; \
4161 }
4162
4163 /* Binary function with an optional context arg. Actual MPDFUNC does
4164 NOT take a context. The context is used to record InvalidOperation
4165 if the second operand cannot be converted exactly. */
4166 #define Dec_BinaryFuncVA_NO_CTX(MPDFUNC) \
4167 static PyObject * \
4168 dec_##MPDFUNC(PyObject *self, PyObject *args, PyObject *kwds) \
4169 { \
4170 static char *kwlist[] = {"other", "context", NULL}; \
4171 PyObject *context = Py_None; \
4172 PyObject *other; \
4173 PyObject *a, *b; \
4174 PyObject *result; \
4175 \
4176 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O", kwlist, \
4177 &other, &context)) { \
4178 return NULL; \
4179 } \
4180 decimal_state *state = \
4181 get_module_state_by_def(Py_TYPE(self)); \
4182 CONTEXT_CHECK_VA(state, context); \
4183 CONVERT_BINOP_RAISE(&a, &b, self, other, context); \
4184 \
4185 if ((result = dec_alloc(state)) == NULL) { \
4186 Py_DECREF(a); \
4187 Py_DECREF(b); \
4188 return NULL; \
4189 } \
4190 \
4191 MPDFUNC(MPD(result), MPD(a), MPD(b)); \
4192 Py_DECREF(a); \
4193 Py_DECREF(b); \
4194 \
4195 return result; \
4196 }
4197
4198 /* Ternary function with an optional context arg. */
4199 #define Dec_TernaryFuncVA(MPDFUNC) \
4200 static PyObject * \
4201 dec_##MPDFUNC(PyObject *self, PyObject *args, PyObject *kwds) \
4202 { \
4203 static char *kwlist[] = {"other", "third", "context", NULL}; \
4204 PyObject *other, *third; \
4205 PyObject *a, *b, *c; \
4206 PyObject *result; \
4207 PyObject *context = Py_None; \
4208 uint32_t status = 0; \
4209 \
4210 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|O", kwlist, \
4211 &other, &third, &context)) { \
4212 return NULL; \
4213 } \
4214 decimal_state *state = get_module_state_by_def(Py_TYPE(self)); \
4215 CONTEXT_CHECK_VA(state, context); \
4216 CONVERT_TERNOP_RAISE(&a, &b, &c, self, other, third, context); \
4217 \
4218 if ((result = dec_alloc(state)) == NULL) { \
4219 Py_DECREF(a); \
4220 Py_DECREF(b); \
4221 Py_DECREF(c); \
4222 return NULL; \
4223 } \
4224 \
4225 MPDFUNC(MPD(result), MPD(a), MPD(b), MPD(c), CTX(context), &status); \
4226 Py_DECREF(a); \
4227 Py_DECREF(b); \
4228 Py_DECREF(c); \
4229 if (dec_addstatus(context, status)) { \
4230 Py_DECREF(result); \
4231 return NULL; \
4232 } \
4233 \
4234 return result; \
4235 }
4236
4237
4238 /**********************************************/
4239 /* Number methods */
4240 /**********************************************/
4241
4242 Dec_UnaryNumberMethod(mpd_qminus)
4243 Dec_UnaryNumberMethod(mpd_qplus)
4244 Dec_UnaryNumberMethod(mpd_qabs)
4245
4246 Dec_BinaryNumberMethod(mpd_qadd)
4247 Dec_BinaryNumberMethod(mpd_qsub)
4248 Dec_BinaryNumberMethod(mpd_qmul)
4249 Dec_BinaryNumberMethod(mpd_qdiv)
4250 Dec_BinaryNumberMethod(mpd_qrem)
4251 Dec_BinaryNumberMethod(mpd_qdivint)
4252
4253 static PyObject *
4254 nm_dec_as_long(PyObject *dec)
4255 {
4256 PyObject *context;
4257 decimal_state *state = get_module_state_by_def(Py_TYPE(dec));
4258 CURRENT_CONTEXT(state, context);
4259 return dec_as_long(dec, context, MPD_ROUND_DOWN);
4260 }
4261
4262 static int
4263 nm_nonzero(PyObject *v)
4264 {
4265 return !mpd_iszero(MPD(v));
4266 }
4267
4268 static PyObject *
4269 nm_mpd_qdivmod(PyObject *v, PyObject *w)
4270 {
4271 PyObject *a, *b;
4272 PyObject *q, *r;
4273 PyObject *context;
4274 uint32_t status = 0;
4275 PyObject *ret;
4276
4277 decimal_state *state = find_state_left_or_right(v, w);
4278 CURRENT_CONTEXT(state, context);
4279 CONVERT_BINOP(&a, &b, v, w, context);
4280
4281 q = dec_alloc(state);
4282 if (q == NULL) {
4283 Py_DECREF(a);
4284 Py_DECREF(b);
4285 return NULL;
4286 }
4287 r = dec_alloc(state);
4288 if (r == NULL) {
4289 Py_DECREF(a);
4290 Py_DECREF(b);
4291 Py_DECREF(q);
4292 return NULL;
4293 }
4294
4295 mpd_qdivmod(MPD(q), MPD(r), MPD(a), MPD(b), CTX(context), &status);
4296 Py_DECREF(a);
4297 Py_DECREF(b);
4298 if (dec_addstatus(context, status)) {
4299 Py_DECREF(r);
4300 Py_DECREF(q);
4301 return NULL;
4302 }
4303
4304 ret = PyTuple_Pack(2, q, r);
4305 Py_DECREF(r);
4306 Py_DECREF(q);
4307 return ret;
4308 }
4309
4310 static PyObject *
4311 nm_mpd_qpow(PyObject *base, PyObject *exp, PyObject *mod)
4312 {
4313 PyObject *a, *b, *c = NULL;
4314 PyObject *result;
4315 PyObject *context;
4316 uint32_t status = 0;
4317
4318 decimal_state *state = find_state_ternary(base, exp, mod);
4319 CURRENT_CONTEXT(state, context);
4320 CONVERT_BINOP(&a, &b, base, exp, context);
4321
4322 if (mod != Py_None) {
4323 if (!convert_op(NOT_IMPL, &c, mod, context)) {
4324 Py_DECREF(a);
4325 Py_DECREF(b);
4326 return c;
4327 }
4328 }
4329
4330 result = dec_alloc(state);
4331 if (result == NULL) {
4332 Py_DECREF(a);
4333 Py_DECREF(b);
4334 Py_XDECREF(c);
4335 return NULL;
4336 }
4337
4338 if (c == NULL) {
4339 mpd_qpow(MPD(result), MPD(a), MPD(b),
4340 CTX(context), &status);
4341 }
4342 else {
4343 mpd_qpowmod(MPD(result), MPD(a), MPD(b), MPD(c),
4344 CTX(context), &status);
4345 Py_DECREF(c);
4346 }
4347 Py_DECREF(a);
4348 Py_DECREF(b);
4349 if (dec_addstatus(context, status)) {
4350 Py_DECREF(result);
4351 return NULL;
4352 }
4353
4354 return result;
4355 }
4356
4357
4358 /******************************************************************************/
4359 /* Decimal Methods */
4360 /******************************************************************************/
4361
4362 /* Unary arithmetic functions, optional context arg */
4363 Dec_UnaryFuncVA(mpd_qexp)
4364 Dec_UnaryFuncVA(mpd_qln)
4365 Dec_UnaryFuncVA(mpd_qlog10)
4366 Dec_UnaryFuncVA(mpd_qnext_minus)
4367 Dec_UnaryFuncVA(mpd_qnext_plus)
4368 Dec_UnaryFuncVA(mpd_qreduce)
4369 Dec_UnaryFuncVA(mpd_qsqrt)
4370
4371 /* Binary arithmetic functions, optional context arg */
4372 Dec_BinaryFuncVA(mpd_qcompare)
4373 Dec_BinaryFuncVA(mpd_qcompare_signal)
4374 Dec_BinaryFuncVA(mpd_qmax)
4375 Dec_BinaryFuncVA(mpd_qmax_mag)
4376 Dec_BinaryFuncVA(mpd_qmin)
4377 Dec_BinaryFuncVA(mpd_qmin_mag)
4378 Dec_BinaryFuncVA(mpd_qnext_toward)
4379 Dec_BinaryFuncVA(mpd_qrem_near)
4380
4381 /* Ternary arithmetic functions, optional context arg */
4382 Dec_TernaryFuncVA(mpd_qfma)
4383
4384 /* Boolean functions, no context arg */
4385 Dec_BoolFunc(mpd_iscanonical)
4386 Dec_BoolFunc(mpd_isfinite)
4387 Dec_BoolFunc(mpd_isinfinite)
4388 Dec_BoolFunc(mpd_isnan)
4389 Dec_BoolFunc(mpd_isqnan)
4390 Dec_BoolFunc(mpd_issnan)
4391 Dec_BoolFunc(mpd_issigned)
4392 Dec_BoolFunc(mpd_iszero)
4393
4394 /* Boolean functions, optional context arg */
4395 Dec_BoolFuncVA(mpd_isnormal)
4396 Dec_BoolFuncVA(mpd_issubnormal)
4397
4398 /* Unary functions, no context arg */
4399 static PyObject *
4400 dec_mpd_adjexp(PyObject *self, PyObject *dummy UNUSED)
4401 {
4402 mpd_ssize_t retval;
4403
4404 if (mpd_isspecial(MPD(self))) {
4405 retval = 0;
4406 }
4407 else {
4408 retval = mpd_adjexp(MPD(self));
4409 }
4410
4411 return PyLong_FromSsize_t(retval);
4412 }
4413
4414 static PyObject *
4415 dec_canonical(PyObject *self, PyObject *dummy UNUSED)
4416 {
4417 return Py_NewRef(self);
4418 }
4419
4420 static PyObject *
4421 dec_conjugate(PyObject *self, PyObject *dummy UNUSED)
4422 {
4423 return Py_NewRef(self);
4424 }
4425
4426 static PyObject *
4427 dec_mpd_radix(PyObject *self, PyObject *dummy UNUSED)
4428 {
4429 PyObject *result;
4430
4431 decimal_state *state = get_module_state_by_def(Py_TYPE(self));
4432 result = dec_alloc(state);
4433 if (result == NULL) {
4434 return NULL;
4435 }
4436
4437 _dec_settriple(result, MPD_POS, 10, 0);
4438 return result;
4439 }
4440
4441 static PyObject *
4442 dec_mpd_qcopy_abs(PyObject *self, PyObject *dummy UNUSED)
4443 {
4444 PyObject *result;
4445 uint32_t status = 0;
4446
4447 decimal_state *state = get_module_state_by_def(Py_TYPE(self));
4448 if ((result = dec_alloc(state)) == NULL) {
4449 return NULL;
4450 }
4451
4452 mpd_qcopy_abs(MPD(result), MPD(self), &status);
4453 if (status & MPD_Malloc_error) {
4454 Py_DECREF(result);
4455 PyErr_NoMemory();
4456 return NULL;
4457 }
4458
4459 return result;
4460 }
4461
4462 static PyObject *
4463 dec_mpd_qcopy_negate(PyObject *self, PyObject *dummy UNUSED)
4464 {
4465 PyObject *result;
4466 uint32_t status = 0;
4467
4468 decimal_state *state = get_module_state_by_def(Py_TYPE(self));
4469 if ((result = dec_alloc(state)) == NULL) {
4470 return NULL;
4471 }
4472
4473 mpd_qcopy_negate(MPD(result), MPD(self), &status);
4474 if (status & MPD_Malloc_error) {
4475 Py_DECREF(result);
4476 PyErr_NoMemory();
4477 return NULL;
4478 }
4479
4480 return result;
4481 }
4482
4483 /* Unary functions, optional context arg */
4484 Dec_UnaryFuncVA(mpd_qinvert)
4485 Dec_UnaryFuncVA(mpd_qlogb)
4486
4487 static PyObject *
4488 dec_mpd_class(PyObject *self, PyObject *args, PyObject *kwds)
4489 {
4490 static char *kwlist[] = {"context", NULL};
4491 PyObject *context = Py_None;
4492 const char *cp;
4493
4494 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O", kwlist,
4495 &context)) {
4496 return NULL;
4497 }
4498 decimal_state *state = get_module_state_by_def(Py_TYPE(self));
4499 CONTEXT_CHECK_VA(state, context);
4500
4501 cp = mpd_class(MPD(self), CTX(context));
4502 return PyUnicode_FromString(cp);
4503 }
4504
4505 static PyObject *
4506 dec_mpd_to_eng(PyObject *self, PyObject *args, PyObject *kwds)
4507 {
4508 static char *kwlist[] = {"context", NULL};
4509 PyObject *result;
4510 PyObject *context = Py_None;
4511 mpd_ssize_t size;
4512 char *s;
4513
4514 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O", kwlist,
4515 &context)) {
4516 return NULL;
4517 }
4518 decimal_state *state = get_module_state_by_def(Py_TYPE(self));
4519 CONTEXT_CHECK_VA(state, context);
4520
4521 size = mpd_to_eng_size(&s, MPD(self), CtxCaps(context));
4522 if (size < 0) {
4523 PyErr_NoMemory();
4524 return NULL;
4525 }
4526
4527 result = unicode_fromascii(s, size);
4528 mpd_free(s);
4529
4530 return result;
4531 }
4532
4533 /* Binary functions, optional context arg for conversion errors */
4534 Dec_BinaryFuncVA_NO_CTX(mpd_compare_total)
4535 Dec_BinaryFuncVA_NO_CTX(mpd_compare_total_mag)
4536
4537 static PyObject *
4538 dec_mpd_qcopy_sign(PyObject *self, PyObject *args, PyObject *kwds)
4539 {
4540 static char *kwlist[] = {"other", "context", NULL};
4541 PyObject *other;
4542 PyObject *a, *b;
4543 PyObject *result;
4544 PyObject *context = Py_None;
4545 uint32_t status = 0;
4546
4547 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O", kwlist,
4548 &other, &context)) {
4549 return NULL;
4550 }
4551 decimal_state *state = get_module_state_by_def(Py_TYPE(self));
4552 CONTEXT_CHECK_VA(state, context);
4553 CONVERT_BINOP_RAISE(&a, &b, self, other, context);
4554
4555 result = dec_alloc(state);
4556 if (result == NULL) {
4557 Py_DECREF(a);
4558 Py_DECREF(b);
4559 return NULL;
4560 }
4561
4562 mpd_qcopy_sign(MPD(result), MPD(a), MPD(b), &status);
4563 Py_DECREF(a);
4564 Py_DECREF(b);
4565 if (dec_addstatus(context, status)) {
4566 Py_DECREF(result);
4567 return NULL;
4568 }
4569
4570 return result;
4571 }
4572
4573 static PyObject *
4574 dec_mpd_same_quantum(PyObject *self, PyObject *args, PyObject *kwds)
4575 {
4576 static char *kwlist[] = {"other", "context", NULL};
4577 PyObject *other;
4578 PyObject *a, *b;
4579 PyObject *result;
4580 PyObject *context = Py_None;
4581
4582 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O", kwlist,
4583 &other, &context)) {
4584 return NULL;
4585 }
4586 decimal_state *state = get_module_state_by_def(Py_TYPE(self));
4587 CONTEXT_CHECK_VA(state, context);
4588 CONVERT_BINOP_RAISE(&a, &b, self, other, context);
4589
4590 result = mpd_same_quantum(MPD(a), MPD(b)) ? incr_true() : incr_false();
4591 Py_DECREF(a);
4592 Py_DECREF(b);
4593
4594 return result;
4595 }
4596
4597 /* Binary functions, optional context arg */
4598 Dec_BinaryFuncVA(mpd_qand)
4599 Dec_BinaryFuncVA(mpd_qor)
4600 Dec_BinaryFuncVA(mpd_qxor)
4601
4602 Dec_BinaryFuncVA(mpd_qrotate)
4603 Dec_BinaryFuncVA(mpd_qscaleb)
4604 Dec_BinaryFuncVA(mpd_qshift)
4605
4606 static PyObject *
4607 dec_mpd_qquantize(PyObject *v, PyObject *args, PyObject *kwds)
4608 {
4609 static char *kwlist[] = {"exp", "rounding", "context", NULL};
4610 PyObject *rounding = Py_None;
4611 PyObject *context = Py_None;
4612 PyObject *w, *a, *b;
4613 PyObject *result;
4614 uint32_t status = 0;
4615 mpd_context_t workctx;
4616
4617 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OO", kwlist,
4618 &w, &rounding, &context)) {
4619 return NULL;
4620 }
4621 decimal_state *state = get_module_state_by_def(Py_TYPE(v));
4622 CONTEXT_CHECK_VA(state, context);
4623
4624 workctx = *CTX(context);
4625 if (rounding != Py_None) {
4626 int round = getround(state, rounding);
4627 if (round < 0) {
4628 return NULL;
4629 }
4630 if (!mpd_qsetround(&workctx, round)) {
4631 INTERNAL_ERROR_PTR("dec_mpd_qquantize"); /* GCOV_NOT_REACHED */
4632 }
4633 }
4634
4635 CONVERT_BINOP_RAISE(&a, &b, v, w, context);
4636
4637 result = dec_alloc(state);
4638 if (result == NULL) {
4639 Py_DECREF(a);
4640 Py_DECREF(b);
4641 return NULL;
4642 }
4643
4644 mpd_qquantize(MPD(result), MPD(a), MPD(b), &workctx, &status);
4645 Py_DECREF(a);
4646 Py_DECREF(b);
4647 if (dec_addstatus(context, status)) {
4648 Py_DECREF(result);
4649 return NULL;
4650 }
4651
4652 return result;
4653 }
4654
4655 /* Special methods */
4656 static PyObject *
4657 dec_richcompare(PyObject *v, PyObject *w, int op)
4658 {
4659 PyObject *a;
4660 PyObject *b;
4661 PyObject *context;
4662 uint32_t status = 0;
4663 int a_issnan, b_issnan;
4664 int r;
4665 decimal_state *state = find_state_left_or_right(v, w);
4666
4667 #ifdef Py_DEBUG
4668 assert(PyDec_Check(state, v));
4669 #endif
4670 CURRENT_CONTEXT(state, context);
4671 CONVERT_BINOP_CMP(&a, &b, v, w, op, context);
4672
4673 a_issnan = mpd_issnan(MPD(a));
4674 b_issnan = mpd_issnan(MPD(b));
4675
4676 r = mpd_qcmp(MPD(a), MPD(b), &status);
4677 Py_DECREF(a);
4678 Py_DECREF(b);
4679 if (r == INT_MAX) {
4680 /* sNaNs or op={le,ge,lt,gt} always signal. */
4681 if (a_issnan || b_issnan || (op != Py_EQ && op != Py_NE)) {
4682 if (dec_addstatus(context, status)) {
4683 return NULL;
4684 }
4685 }
4686 /* qNaN comparison with op={eq,ne} or comparison
4687 * with InvalidOperation disabled. */
4688 return (op == Py_NE) ? incr_true() : incr_false();
4689 }
4690
4691 switch (op) {
4692 case Py_EQ:
4693 r = (r == 0);
4694 break;
4695 case Py_NE:
4696 r = (r != 0);
4697 break;
4698 case Py_LE:
4699 r = (r <= 0);
4700 break;
4701 case Py_GE:
4702 r = (r >= 0);
4703 break;
4704 case Py_LT:
4705 r = (r == -1);
4706 break;
4707 case Py_GT:
4708 r = (r == 1);
4709 break;
4710 }
4711
4712 return PyBool_FromLong(r);
4713 }
4714
4715 /* __ceil__ */
4716 static PyObject *
4717 dec_ceil(PyObject *self, PyObject *dummy UNUSED)
4718 {
4719 PyObject *context;
4720
4721 decimal_state *state = get_module_state_by_def(Py_TYPE(self));
4722 CURRENT_CONTEXT(state, context);
4723 return dec_as_long(self, context, MPD_ROUND_CEILING);
4724 }
4725
4726 /* __complex__ */
4727 static PyObject *
4728 dec_complex(PyObject *self, PyObject *dummy UNUSED)
4729 {
4730 PyObject *f;
4731 double x;
4732
4733 f = PyDec_AsFloat(self);
4734 if (f == NULL) {
4735 return NULL;
4736 }
4737
4738 x = PyFloat_AsDouble(f);
4739 Py_DECREF(f);
4740 if (x == -1.0 && PyErr_Occurred()) {
4741 return NULL;
4742 }
4743
4744 return PyComplex_FromDoubles(x, 0);
4745 }
4746
4747 /* __copy__ and __deepcopy__ */
4748 static PyObject *
4749 dec_copy(PyObject *self, PyObject *dummy UNUSED)
4750 {
4751 return Py_NewRef(self);
4752 }
4753
4754 /* __floor__ */
4755 static PyObject *
4756 dec_floor(PyObject *self, PyObject *dummy UNUSED)
4757 {
4758 PyObject *context;
4759
4760 decimal_state *state = get_module_state_by_def(Py_TYPE(self));
4761 CURRENT_CONTEXT(state, context);
4762 return dec_as_long(self, context, MPD_ROUND_FLOOR);
4763 }
4764
4765 /* Always uses the module context */
4766 static Py_hash_t
4767 _dec_hash(PyDecObject *v)
4768 {
4769 #if defined(CONFIG_64) && _PyHASH_BITS == 61
4770 /* 2**61 - 1 */
4771 mpd_uint_t p_data[1] = {2305843009213693951ULL};
4772 mpd_t p = {MPD_POS|MPD_STATIC|MPD_CONST_DATA, 0, 19, 1, 1, p_data};
4773 /* Inverse of 10 modulo p */
4774 mpd_uint_t inv10_p_data[1] = {2075258708292324556ULL};
4775 mpd_t inv10_p = {MPD_POS|MPD_STATIC|MPD_CONST_DATA,
4776 0, 19, 1, 1, inv10_p_data};
4777 #elif defined(CONFIG_32) && _PyHASH_BITS == 31
4778 /* 2**31 - 1 */
4779 mpd_uint_t p_data[2] = {147483647UL, 2};
4780 mpd_t p = {MPD_POS|MPD_STATIC|MPD_CONST_DATA, 0, 10, 2, 2, p_data};
4781 /* Inverse of 10 modulo p */
4782 mpd_uint_t inv10_p_data[2] = {503238553UL, 1};
4783 mpd_t inv10_p = {MPD_POS|MPD_STATIC|MPD_CONST_DATA,
4784 0, 10, 2, 2, inv10_p_data};
4785 #else
4786 #error "No valid combination of CONFIG_64, CONFIG_32 and _PyHASH_BITS"
4787 #endif
4788 const Py_hash_t py_hash_inf = 314159;
4789 mpd_uint_t ten_data[1] = {10};
4790 mpd_t ten = {MPD_POS|MPD_STATIC|MPD_CONST_DATA,
4791 0, 2, 1, 1, ten_data};
4792 Py_hash_t result;
4793 mpd_t *exp_hash = NULL;
4794 mpd_t *tmp = NULL;
4795 mpd_ssize_t exp;
4796 uint32_t status = 0;
4797 mpd_context_t maxctx;
4798
4799
4800 if (mpd_isspecial(MPD(v))) {
4801 if (mpd_issnan(MPD(v))) {
4802 PyErr_SetString(PyExc_TypeError,
4803 "Cannot hash a signaling NaN value");
4804 return -1;
4805 }
4806 else if (mpd_isnan(MPD(v))) {
4807 return PyObject_GenericHash((PyObject *)v);
4808 }
4809 else {
4810 return py_hash_inf * mpd_arith_sign(MPD(v));
4811 }
4812 }
4813
4814 mpd_maxcontext(&maxctx);
4815 exp_hash = mpd_qnew();
4816 if (exp_hash == NULL) {
4817 goto malloc_error;
4818 }
4819 tmp = mpd_qnew();
4820 if (tmp == NULL) {
4821 goto malloc_error;
4822 }
4823
4824 /*
4825 * exp(v): exponent of v
4826 * int(v): coefficient of v
4827 */
4828 exp = MPD(v)->exp;
4829 if (exp >= 0) {
4830 /* 10**exp(v) % p */
4831 mpd_qsset_ssize(tmp, exp, &maxctx, &status);
4832 mpd_qpowmod(exp_hash, &ten, tmp, &p, &maxctx, &status);
4833 }
4834 else {
4835 /* inv10_p**(-exp(v)) % p */
4836 mpd_qsset_ssize(tmp, -exp, &maxctx, &status);
4837 mpd_qpowmod(exp_hash, &inv10_p, tmp, &p, &maxctx, &status);
4838 }
4839
4840 /* hash = (int(v) * exp_hash) % p */
4841 if (!mpd_qcopy(tmp, MPD(v), &status)) {
4842 goto malloc_error;
4843 }
4844 tmp->exp = 0;
4845 mpd_set_positive(tmp);
4846
4847 maxctx.prec = MPD_MAX_PREC + 21;
4848 maxctx.emax = MPD_MAX_EMAX + 21;
4849 maxctx.emin = MPD_MIN_EMIN - 21;
4850
4851 mpd_qmul(tmp, tmp, exp_hash, &maxctx, &status);
4852 mpd_qrem(tmp, tmp, &p, &maxctx, &status);
4853
4854 result = mpd_qget_ssize(tmp, &status);
4855 result = mpd_ispositive(MPD(v)) ? result : -result;
4856 result = (result == -1) ? -2 : result;
4857
4858 if (status != 0) {
4859 if (status & MPD_Malloc_error) {
4860 goto malloc_error;
4861 }
4862 else {
4863 PyErr_SetString(PyExc_RuntimeError, /* GCOV_NOT_REACHED */
4864 "dec_hash: internal error: please report"); /* GCOV_NOT_REACHED */
4865 }
4866 result = -1; /* GCOV_NOT_REACHED */
4867 }
4868
4869
4870 finish:
4871 if (exp_hash) mpd_del(exp_hash);
4872 if (tmp) mpd_del(tmp);
4873 return result;
4874
4875 malloc_error:
4876 PyErr_NoMemory();
4877 result = -1;
4878 goto finish;
4879 }
4880
4881 static Py_hash_t
4882 dec_hash(PyDecObject *self)
4883 {
4884 if (self->hash == -1) {
4885 self->hash = _dec_hash(self);
4886 }
4887
4888 return self->hash;
4889 }
4890
4891 /* __reduce__ */
4892 static PyObject *
4893 dec_reduce(PyObject *self, PyObject *dummy UNUSED)
4894 {
4895 PyObject *result, *str;
4896
4897 str = dec_str(self);
4898 if (str == NULL) {
4899 return NULL;
4900 }
4901
4902 result = Py_BuildValue("O(O)", Py_TYPE(self), str);
4903 Py_DECREF(str);
4904
4905 return result;
4906 }
4907
4908 /* __sizeof__ */
4909 static PyObject *
4910 dec_sizeof(PyObject *v, PyObject *dummy UNUSED)
4911 {
4912 size_t res = _PyObject_SIZE(Py_TYPE(v));
4913 if (mpd_isdynamic_data(MPD(v))) {
4914 res += (size_t)MPD(v)->alloc * sizeof(mpd_uint_t);
4915 }
4916 return PyLong_FromSize_t(res);
4917 }
4918
4919 /* __trunc__ */
4920 static PyObject *
4921 dec_trunc(PyObject *self, PyObject *dummy UNUSED)
4922 {
4923 PyObject *context;
4924
4925 decimal_state *state = get_module_state_by_def(Py_TYPE(self));
4926 CURRENT_CONTEXT(state, context);
4927 return dec_as_long(self, context, MPD_ROUND_DOWN);
4928 }
4929
4930 /* real and imag */
4931 static PyObject *
4932 dec_real(PyObject *self, void *closure UNUSED)
4933 {
4934 return Py_NewRef(self);
4935 }
4936
4937 static PyObject *
4938 dec_imag(PyObject *self UNUSED, void *closure UNUSED)
4939 {
4940 PyObject *result;
4941
4942 decimal_state *state = get_module_state_by_def(Py_TYPE(self));
4943 result = dec_alloc(state);
4944 if (result == NULL) {
4945 return NULL;
4946 }
4947
4948 _dec_settriple(result, MPD_POS, 0, 0);
4949 return result;
4950 }
4951
4952
4953 static PyGetSetDef dec_getsets [] =
4954 {
4955 { "real", (getter)dec_real, NULL, NULL, NULL},
4956 { "imag", (getter)dec_imag, NULL, NULL, NULL},
4957 {NULL}
4958 };
4959
4960 static PyMethodDef dec_methods [] =
4961 {
4962 /* Unary arithmetic functions, optional context arg */
4963 { "exp", _PyCFunction_CAST(dec_mpd_qexp), METH_VARARGS|METH_KEYWORDS, doc_exp },
4964 { "ln", _PyCFunction_CAST(dec_mpd_qln), METH_VARARGS|METH_KEYWORDS, doc_ln },
4965 { "log10", _PyCFunction_CAST(dec_mpd_qlog10), METH_VARARGS|METH_KEYWORDS, doc_log10 },
4966 { "next_minus", _PyCFunction_CAST(dec_mpd_qnext_minus), METH_VARARGS|METH_KEYWORDS, doc_next_minus },
4967 { "next_plus", _PyCFunction_CAST(dec_mpd_qnext_plus), METH_VARARGS|METH_KEYWORDS, doc_next_plus },
4968 { "normalize", _PyCFunction_CAST(dec_mpd_qreduce), METH_VARARGS|METH_KEYWORDS, doc_normalize },
4969 { "to_integral", _PyCFunction_CAST(PyDec_ToIntegralValue), METH_VARARGS|METH_KEYWORDS, doc_to_integral },
4970 { "to_integral_exact", _PyCFunction_CAST(PyDec_ToIntegralExact), METH_VARARGS|METH_KEYWORDS, doc_to_integral_exact },
4971 { "to_integral_value", _PyCFunction_CAST(PyDec_ToIntegralValue), METH_VARARGS|METH_KEYWORDS, doc_to_integral_value },
4972 { "sqrt", _PyCFunction_CAST(dec_mpd_qsqrt), METH_VARARGS|METH_KEYWORDS, doc_sqrt },
4973
4974 /* Binary arithmetic functions, optional context arg */
4975 { "compare", _PyCFunction_CAST(dec_mpd_qcompare), METH_VARARGS|METH_KEYWORDS, doc_compare },
4976 { "compare_signal", _PyCFunction_CAST(dec_mpd_qcompare_signal), METH_VARARGS|METH_KEYWORDS, doc_compare_signal },
4977 { "max", _PyCFunction_CAST(dec_mpd_qmax), METH_VARARGS|METH_KEYWORDS, doc_max },
4978 { "max_mag", _PyCFunction_CAST(dec_mpd_qmax_mag), METH_VARARGS|METH_KEYWORDS, doc_max_mag },
4979 { "min", _PyCFunction_CAST(dec_mpd_qmin), METH_VARARGS|METH_KEYWORDS, doc_min },
4980 { "min_mag", _PyCFunction_CAST(dec_mpd_qmin_mag), METH_VARARGS|METH_KEYWORDS, doc_min_mag },
4981 { "next_toward", _PyCFunction_CAST(dec_mpd_qnext_toward), METH_VARARGS|METH_KEYWORDS, doc_next_toward },
4982 { "quantize", _PyCFunction_CAST(dec_mpd_qquantize), METH_VARARGS|METH_KEYWORDS, doc_quantize },
4983 { "remainder_near", _PyCFunction_CAST(dec_mpd_qrem_near), METH_VARARGS|METH_KEYWORDS, doc_remainder_near },
4984
4985 /* Ternary arithmetic functions, optional context arg */
4986 { "fma", _PyCFunction_CAST(dec_mpd_qfma), METH_VARARGS|METH_KEYWORDS, doc_fma },
4987
4988 /* Boolean functions, no context arg */
4989 { "is_canonical", dec_mpd_iscanonical, METH_NOARGS, doc_is_canonical },
4990 { "is_finite", dec_mpd_isfinite, METH_NOARGS, doc_is_finite },
4991 { "is_infinite", dec_mpd_isinfinite, METH_NOARGS, doc_is_infinite },
4992 { "is_nan", dec_mpd_isnan, METH_NOARGS, doc_is_nan },
4993 { "is_qnan", dec_mpd_isqnan, METH_NOARGS, doc_is_qnan },
4994 { "is_snan", dec_mpd_issnan, METH_NOARGS, doc_is_snan },
4995 { "is_signed", dec_mpd_issigned, METH_NOARGS, doc_is_signed },
4996 { "is_zero", dec_mpd_iszero, METH_NOARGS, doc_is_zero },
4997
4998 /* Boolean functions, optional context arg */
4999 { "is_normal", _PyCFunction_CAST(dec_mpd_isnormal), METH_VARARGS|METH_KEYWORDS, doc_is_normal },
5000 { "is_subnormal", _PyCFunction_CAST(dec_mpd_issubnormal), METH_VARARGS|METH_KEYWORDS, doc_is_subnormal },
5001
5002 /* Unary functions, no context arg */
5003 { "adjusted", dec_mpd_adjexp, METH_NOARGS, doc_adjusted },
5004 { "canonical", dec_canonical, METH_NOARGS, doc_canonical },
5005 { "conjugate", dec_conjugate, METH_NOARGS, doc_conjugate },
5006 { "radix", dec_mpd_radix, METH_NOARGS, doc_radix },
5007
5008 /* Unary functions, optional context arg for conversion errors */
5009 { "copy_abs", dec_mpd_qcopy_abs, METH_NOARGS, doc_copy_abs },
5010 { "copy_negate", dec_mpd_qcopy_negate, METH_NOARGS, doc_copy_negate },
5011
5012 /* Unary functions, optional context arg */
5013 { "logb", _PyCFunction_CAST(dec_mpd_qlogb), METH_VARARGS|METH_KEYWORDS, doc_logb },
5014 { "logical_invert", _PyCFunction_CAST(dec_mpd_qinvert), METH_VARARGS|METH_KEYWORDS, doc_logical_invert },
5015 { "number_class", _PyCFunction_CAST(dec_mpd_class), METH_VARARGS|METH_KEYWORDS, doc_number_class },
5016 { "to_eng_string", _PyCFunction_CAST(dec_mpd_to_eng), METH_VARARGS|METH_KEYWORDS, doc_to_eng_string },
5017
5018 /* Binary functions, optional context arg for conversion errors */
5019 { "compare_total", _PyCFunction_CAST(dec_mpd_compare_total), METH_VARARGS|METH_KEYWORDS, doc_compare_total },
5020 { "compare_total_mag", _PyCFunction_CAST(dec_mpd_compare_total_mag), METH_VARARGS|METH_KEYWORDS, doc_compare_total_mag },
5021 { "copy_sign", _PyCFunction_CAST(dec_mpd_qcopy_sign), METH_VARARGS|METH_KEYWORDS, doc_copy_sign },
5022 { "same_quantum", _PyCFunction_CAST(dec_mpd_same_quantum), METH_VARARGS|METH_KEYWORDS, doc_same_quantum },
5023
5024 /* Binary functions, optional context arg */
5025 { "logical_and", _PyCFunction_CAST(dec_mpd_qand), METH_VARARGS|METH_KEYWORDS, doc_logical_and },
5026 { "logical_or", _PyCFunction_CAST(dec_mpd_qor), METH_VARARGS|METH_KEYWORDS, doc_logical_or },
5027 { "logical_xor", _PyCFunction_CAST(dec_mpd_qxor), METH_VARARGS|METH_KEYWORDS, doc_logical_xor },
5028 { "rotate", _PyCFunction_CAST(dec_mpd_qrotate), METH_VARARGS|METH_KEYWORDS, doc_rotate },
5029 { "scaleb", _PyCFunction_CAST(dec_mpd_qscaleb), METH_VARARGS|METH_KEYWORDS, doc_scaleb },
5030 { "shift", _PyCFunction_CAST(dec_mpd_qshift), METH_VARARGS|METH_KEYWORDS, doc_shift },
5031
5032 /* Miscellaneous */
5033 { "from_float", dec_from_float, METH_O|METH_CLASS, doc_from_float },
5034 { "as_tuple", PyDec_AsTuple, METH_NOARGS, doc_as_tuple },
5035 { "as_integer_ratio", dec_as_integer_ratio, METH_NOARGS, doc_as_integer_ratio },
5036
5037 /* Special methods */
5038 { "__copy__", dec_copy, METH_NOARGS, NULL },
5039 { "__deepcopy__", dec_copy, METH_O, NULL },
5040 { "__format__", dec_format, METH_VARARGS, NULL },
5041 { "__reduce__", dec_reduce, METH_NOARGS, NULL },
5042 { "__round__", PyDec_Round, METH_VARARGS, NULL },
5043 { "__ceil__", dec_ceil, METH_NOARGS, NULL },
5044 { "__floor__", dec_floor, METH_NOARGS, NULL },
5045 { "__trunc__", dec_trunc, METH_NOARGS, NULL },
5046 { "__complex__", dec_complex, METH_NOARGS, NULL },
5047 { "__sizeof__", dec_sizeof, METH_NOARGS, NULL },
5048
5049 { NULL, NULL, 1 }
5050 };
5051
5052 static PyType_Slot dec_slots[] = {
5053 {Py_tp_dealloc, dec_dealloc},
5054 {Py_tp_getattro, PyObject_GenericGetAttr},
5055 {Py_tp_traverse, dec_traverse},
5056 {Py_tp_repr, dec_repr},
5057 {Py_tp_hash, dec_hash},
5058 {Py_tp_str, dec_str},
5059 {Py_tp_doc, (void *)doc_decimal},
5060 {Py_tp_richcompare, dec_richcompare},
5061 {Py_tp_methods, dec_methods},
5062 {Py_tp_getset, dec_getsets},
5063 {Py_tp_new, dec_new},
5064
5065 // Number protocol
5066 {Py_nb_add, nm_mpd_qadd},
5067 {Py_nb_subtract, nm_mpd_qsub},
5068 {Py_nb_multiply, nm_mpd_qmul},
5069 {Py_nb_remainder, nm_mpd_qrem},
5070 {Py_nb_divmod, nm_mpd_qdivmod},
5071 {Py_nb_power, nm_mpd_qpow},
5072 {Py_nb_negative, nm_mpd_qminus},
5073 {Py_nb_positive, nm_mpd_qplus},
5074 {Py_nb_absolute, nm_mpd_qabs},
5075 {Py_nb_bool, nm_nonzero},
5076 {Py_nb_int, nm_dec_as_long},
5077 {Py_nb_float, PyDec_AsFloat},
5078 {Py_nb_floor_divide, nm_mpd_qdivint},
5079 {Py_nb_true_divide, nm_mpd_qdiv},
5080 {0, NULL},
5081 };
5082
5083
5084 static PyType_Spec dec_spec = {
5085 .name = "decimal.Decimal",
5086 .basicsize = sizeof(PyDecObject),
5087 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5088 Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE),
5089 .slots = dec_slots,
5090 };
5091
5092
5093 /******************************************************************************/
5094 /* Context Object, Part 2 */
5095 /******************************************************************************/
5096
5097
5098 /************************************************************************/
5099 /* Macros for converting mpdecimal functions to Context methods */
5100 /************************************************************************/
5101
5102 /* Boolean context method. */
5103 #define DecCtx_BoolFunc(MPDFUNC) \
5104 static PyObject * \
5105 ctx_##MPDFUNC(PyObject *context, PyObject *v) \
5106 { \
5107 PyObject *ret; \
5108 PyObject *a; \
5109 \
5110 CONVERT_OP_RAISE(&a, v, context); \
5111 \
5112 ret = MPDFUNC(MPD(a), CTX(context)) ? incr_true() : incr_false(); \
5113 Py_DECREF(a); \
5114 return ret; \
5115 }
5116
5117 /* Boolean context method. MPDFUNC does NOT use a context. */
5118 #define DecCtx_BoolFunc_NO_CTX(MPDFUNC) \
5119 static PyObject * \
5120 ctx_##MPDFUNC(PyObject *context, PyObject *v) \
5121 { \
5122 PyObject *ret; \
5123 PyObject *a; \
5124 \
5125 CONVERT_OP_RAISE(&a, v, context); \
5126 \
5127 ret = MPDFUNC(MPD(a)) ? incr_true() : incr_false(); \
5128 Py_DECREF(a); \
5129 return ret; \
5130 }
5131
5132 /* Unary context method. */
5133 #define DecCtx_UnaryFunc(MPDFUNC) \
5134 static PyObject * \
5135 ctx_##MPDFUNC(PyObject *context, PyObject *v) \
5136 { \
5137 PyObject *result, *a; \
5138 uint32_t status = 0; \
5139 \
5140 CONVERT_OP_RAISE(&a, v, context); \
5141 decimal_state *state = \
5142 get_module_state_by_def(Py_TYPE(context)); \
5143 if ((result = dec_alloc(state)) == NULL) { \
5144 Py_DECREF(a); \
5145 return NULL; \
5146 } \
5147 \
5148 MPDFUNC(MPD(result), MPD(a), CTX(context), &status); \
5149 Py_DECREF(a); \
5150 if (dec_addstatus(context, status)) { \
5151 Py_DECREF(result); \
5152 return NULL; \
5153 } \
5154 \
5155 return result; \
5156 }
5157
5158 /* Binary context method. */
5159 #define DecCtx_BinaryFunc(MPDFUNC) \
5160 static PyObject * \
5161 ctx_##MPDFUNC(PyObject *context, PyObject *args) \
5162 { \
5163 PyObject *v, *w; \
5164 PyObject *a, *b; \
5165 PyObject *result; \
5166 uint32_t status = 0; \
5167 \
5168 if (!PyArg_ParseTuple(args, "OO", &v, &w)) { \
5169 return NULL; \
5170 } \
5171 \
5172 CONVERT_BINOP_RAISE(&a, &b, v, w, context); \
5173 decimal_state *state = \
5174 get_module_state_by_def(Py_TYPE(context)); \
5175 if ((result = dec_alloc(state)) == NULL) { \
5176 Py_DECREF(a); \
5177 Py_DECREF(b); \
5178 return NULL; \
5179 } \
5180 \
5181 MPDFUNC(MPD(result), MPD(a), MPD(b), CTX(context), &status); \
5182 Py_DECREF(a); \
5183 Py_DECREF(b); \
5184 if (dec_addstatus(context, status)) { \
5185 Py_DECREF(result); \
5186 return NULL; \
5187 } \
5188 \
5189 return result; \
5190 }
5191
5192 /*
5193 * Binary context method. The context is only used for conversion.
5194 * The actual MPDFUNC does NOT take a context arg.
5195 */
5196 #define DecCtx_BinaryFunc_NO_CTX(MPDFUNC) \
5197 static PyObject * \
5198 ctx_##MPDFUNC(PyObject *context, PyObject *args) \
5199 { \
5200 PyObject *v, *w; \
5201 PyObject *a, *b; \
5202 PyObject *result; \
5203 \
5204 if (!PyArg_ParseTuple(args, "OO", &v, &w)) { \
5205 return NULL; \
5206 } \
5207 \
5208 CONVERT_BINOP_RAISE(&a, &b, v, w, context); \
5209 decimal_state *state = \
5210 get_module_state_by_def(Py_TYPE(context)); \
5211 if ((result = dec_alloc(state)) == NULL) { \
5212 Py_DECREF(a); \
5213 Py_DECREF(b); \
5214 return NULL; \
5215 } \
5216 \
5217 MPDFUNC(MPD(result), MPD(a), MPD(b)); \
5218 Py_DECREF(a); \
5219 Py_DECREF(b); \
5220 \
5221 return result; \
5222 }
5223
5224 /* Ternary context method. */
5225 #define DecCtx_TernaryFunc(MPDFUNC) \
5226 static PyObject * \
5227 ctx_##MPDFUNC(PyObject *context, PyObject *args) \
5228 { \
5229 PyObject *v, *w, *x; \
5230 PyObject *a, *b, *c; \
5231 PyObject *result; \
5232 uint32_t status = 0; \
5233 \
5234 if (!PyArg_ParseTuple(args, "OOO", &v, &w, &x)) { \
5235 return NULL; \
5236 } \
5237 \
5238 CONVERT_TERNOP_RAISE(&a, &b, &c, v, w, x, context); \
5239 decimal_state *state = get_module_state_by_def(Py_TYPE(context)); \
5240 if ((result = dec_alloc(state)) == NULL) { \
5241 Py_DECREF(a); \
5242 Py_DECREF(b); \
5243 Py_DECREF(c); \
5244 return NULL; \
5245 } \
5246 \
5247 MPDFUNC(MPD(result), MPD(a), MPD(b), MPD(c), CTX(context), &status); \
5248 Py_DECREF(a); \
5249 Py_DECREF(b); \
5250 Py_DECREF(c); \
5251 if (dec_addstatus(context, status)) { \
5252 Py_DECREF(result); \
5253 return NULL; \
5254 } \
5255 \
5256 return result; \
5257 }
5258
5259
5260 /* Unary arithmetic functions */
5261 DecCtx_UnaryFunc(mpd_qabs)
5262 DecCtx_UnaryFunc(mpd_qexp)
5263 DecCtx_UnaryFunc(mpd_qln)
5264 DecCtx_UnaryFunc(mpd_qlog10)
5265 DecCtx_UnaryFunc(mpd_qminus)
5266 DecCtx_UnaryFunc(mpd_qnext_minus)
5267 DecCtx_UnaryFunc(mpd_qnext_plus)
5268 DecCtx_UnaryFunc(mpd_qplus)
5269 DecCtx_UnaryFunc(mpd_qreduce)
5270 DecCtx_UnaryFunc(mpd_qround_to_int)
5271 DecCtx_UnaryFunc(mpd_qround_to_intx)
5272 DecCtx_UnaryFunc(mpd_qsqrt)
5273
5274 /* Binary arithmetic functions */
5275 DecCtx_BinaryFunc(mpd_qadd)
5276 DecCtx_BinaryFunc(mpd_qcompare)
5277 DecCtx_BinaryFunc(mpd_qcompare_signal)
5278 DecCtx_BinaryFunc(mpd_qdiv)
5279 DecCtx_BinaryFunc(mpd_qdivint)
5280 DecCtx_BinaryFunc(mpd_qmax)
5281 DecCtx_BinaryFunc(mpd_qmax_mag)
5282 DecCtx_BinaryFunc(mpd_qmin)
5283 DecCtx_BinaryFunc(mpd_qmin_mag)
5284 DecCtx_BinaryFunc(mpd_qmul)
5285 DecCtx_BinaryFunc(mpd_qnext_toward)
5286 DecCtx_BinaryFunc(mpd_qquantize)
5287 DecCtx_BinaryFunc(mpd_qrem)
5288 DecCtx_BinaryFunc(mpd_qrem_near)
5289 DecCtx_BinaryFunc(mpd_qsub)
5290
5291 static PyObject *
5292 ctx_mpd_qdivmod(PyObject *context, PyObject *args)
5293 {
5294 PyObject *v, *w;
5295 PyObject *a, *b;
5296 PyObject *q, *r;
5297 uint32_t status = 0;
5298 PyObject *ret;
5299
5300 if (!PyArg_ParseTuple(args, "OO", &v, &w)) {
5301 return NULL;
5302 }
5303
5304 CONVERT_BINOP_RAISE(&a, &b, v, w, context);
5305 decimal_state *state = get_module_state_by_def(Py_TYPE(context));
5306 q = dec_alloc(state);
5307 if (q == NULL) {
5308 Py_DECREF(a);
5309 Py_DECREF(b);
5310 return NULL;
5311 }
5312 r = dec_alloc(state);
5313 if (r == NULL) {
5314 Py_DECREF(a);
5315 Py_DECREF(b);
5316 Py_DECREF(q);
5317 return NULL;
5318 }
5319
5320 mpd_qdivmod(MPD(q), MPD(r), MPD(a), MPD(b), CTX(context), &status);
5321 Py_DECREF(a);
5322 Py_DECREF(b);
5323 if (dec_addstatus(context, status)) {
5324 Py_DECREF(r);
5325 Py_DECREF(q);
5326 return NULL;
5327 }
5328
5329 ret = PyTuple_Pack(2, q, r);
5330 Py_DECREF(r);
5331 Py_DECREF(q);
5332 return ret;
5333 }
5334
5335 /* Binary or ternary arithmetic functions */
5336 static PyObject *
5337 ctx_mpd_qpow(PyObject *context, PyObject *args, PyObject *kwds)
5338 {
5339 static char *kwlist[] = {"a", "b", "modulo", NULL};
5340 PyObject *base, *exp, *mod = Py_None;
5341 PyObject *a, *b, *c = NULL;
5342 PyObject *result;
5343 uint32_t status = 0;
5344
5345 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|O", kwlist,
5346 &base, &exp, &mod)) {
5347 return NULL;
5348 }
5349
5350 CONVERT_BINOP_RAISE(&a, &b, base, exp, context);
5351
5352 if (mod != Py_None) {
5353 if (!convert_op(TYPE_ERR, &c, mod, context)) {
5354 Py_DECREF(a);
5355 Py_DECREF(b);
5356 return c;
5357 }
5358 }
5359
5360 decimal_state *state = get_module_state_by_def(Py_TYPE(context));
5361 result = dec_alloc(state);
5362 if (result == NULL) {
5363 Py_DECREF(a);
5364 Py_DECREF(b);
5365 Py_XDECREF(c);
5366 return NULL;
5367 }
5368
5369 if (c == NULL) {
5370 mpd_qpow(MPD(result), MPD(a), MPD(b),
5371 CTX(context), &status);
5372 }
5373 else {
5374 mpd_qpowmod(MPD(result), MPD(a), MPD(b), MPD(c),
5375 CTX(context), &status);
5376 Py_DECREF(c);
5377 }
5378 Py_DECREF(a);
5379 Py_DECREF(b);
5380 if (dec_addstatus(context, status)) {
5381 Py_DECREF(result);
5382 return NULL;
5383 }
5384
5385 return result;
5386 }
5387
5388 /* Ternary arithmetic functions */
5389 DecCtx_TernaryFunc(mpd_qfma)
5390
5391 /* No argument */
5392 static PyObject *
5393 ctx_mpd_radix(PyObject *context, PyObject *dummy)
5394 {
5395 return dec_mpd_radix(context, dummy);
5396 }
5397
5398 /* Boolean functions: single decimal argument */
5399 DecCtx_BoolFunc(mpd_isnormal)
5400 DecCtx_BoolFunc(mpd_issubnormal)
5401 DecCtx_BoolFunc_NO_CTX(mpd_isfinite)
5402 DecCtx_BoolFunc_NO_CTX(mpd_isinfinite)
5403 DecCtx_BoolFunc_NO_CTX(mpd_isnan)
5404 DecCtx_BoolFunc_NO_CTX(mpd_isqnan)
5405 DecCtx_BoolFunc_NO_CTX(mpd_issigned)
5406 DecCtx_BoolFunc_NO_CTX(mpd_issnan)
5407 DecCtx_BoolFunc_NO_CTX(mpd_iszero)
5408
5409 static PyObject *
5410 ctx_iscanonical(PyObject *context, PyObject *v)
5411 {
5412 decimal_state *state = get_module_state_by_def(Py_TYPE(context));
5413 if (!PyDec_Check(state, v)) {
5414 PyErr_SetString(PyExc_TypeError,
5415 "argument must be a Decimal");
5416 return NULL;
5417 }
5418
5419 return mpd_iscanonical(MPD(v)) ? incr_true() : incr_false();
5420 }
5421
5422 /* Functions with a single decimal argument */
5423 static PyObject *
5424 PyDecContext_Apply(PyObject *context, PyObject *v)
5425 {
5426 PyObject *result, *a;
5427
5428 CONVERT_OP_RAISE(&a, v, context);
5429
5430 result = dec_apply(a, context);
5431 Py_DECREF(a);
5432 return result;
5433 }
5434
5435 static PyObject *
5436 ctx_canonical(PyObject *context, PyObject *v)
5437 {
5438 decimal_state *state = get_module_state_by_def(Py_TYPE(context));
5439 if (!PyDec_Check(state, v)) {
5440 PyErr_SetString(PyExc_TypeError,
5441 "argument must be a Decimal");
5442 return NULL;
5443 }
5444
5445 return Py_NewRef(v);
5446 }
5447
5448 static PyObject *
5449 ctx_mpd_qcopy_abs(PyObject *context, PyObject *v)
5450 {
5451 PyObject *result, *a;
5452 uint32_t status = 0;
5453
5454 CONVERT_OP_RAISE(&a, v, context);
5455 decimal_state *state = get_module_state_by_def(Py_TYPE(context));
5456 result = dec_alloc(state);
5457 if (result == NULL) {
5458 Py_DECREF(a);
5459 return NULL;
5460 }
5461
5462 mpd_qcopy_abs(MPD(result), MPD(a), &status);
5463 Py_DECREF(a);
5464 if (dec_addstatus(context, status)) {
5465 Py_DECREF(result);
5466 return NULL;
5467 }
5468
5469 return result;
5470 }
5471
5472 static PyObject *
5473 ctx_copy_decimal(PyObject *context, PyObject *v)
5474 {
5475 PyObject *result;
5476
5477 CONVERT_OP_RAISE(&result, v, context);
5478 return result;
5479 }
5480
5481 static PyObject *
5482 ctx_mpd_qcopy_negate(PyObject *context, PyObject *v)
5483 {
5484 PyObject *result, *a;
5485 uint32_t status = 0;
5486
5487 CONVERT_OP_RAISE(&a, v, context);
5488 decimal_state *state = get_module_state_by_def(Py_TYPE(context));
5489 result = dec_alloc(state);
5490 if (result == NULL) {
5491 Py_DECREF(a);
5492 return NULL;
5493 }
5494
5495 mpd_qcopy_negate(MPD(result), MPD(a), &status);
5496 Py_DECREF(a);
5497 if (dec_addstatus(context, status)) {
5498 Py_DECREF(result);
5499 return NULL;
5500 }
5501
5502 return result;
5503 }
5504
5505 DecCtx_UnaryFunc(mpd_qlogb)
5506 DecCtx_UnaryFunc(mpd_qinvert)
5507
5508 static PyObject *
5509 ctx_mpd_class(PyObject *context, PyObject *v)
5510 {
5511 PyObject *a;
5512 const char *cp;
5513
5514 CONVERT_OP_RAISE(&a, v, context);
5515
5516 cp = mpd_class(MPD(a), CTX(context));
5517 Py_DECREF(a);
5518
5519 return PyUnicode_FromString(cp);
5520 }
5521
5522 static PyObject *
5523 ctx_mpd_to_sci(PyObject *context, PyObject *v)
5524 {
5525 PyObject *result;
5526 PyObject *a;
5527 mpd_ssize_t size;
5528 char *s;
5529
5530 CONVERT_OP_RAISE(&a, v, context);
5531
5532 size = mpd_to_sci_size(&s, MPD(a), CtxCaps(context));
5533 Py_DECREF(a);
5534 if (size < 0) {
5535 PyErr_NoMemory();
5536 return NULL;
5537 }
5538
5539 result = unicode_fromascii(s, size);
5540 mpd_free(s);
5541
5542 return result;
5543 }
5544
5545 static PyObject *
5546 ctx_mpd_to_eng(PyObject *context, PyObject *v)
5547 {
5548 PyObject *result;
5549 PyObject *a;
5550 mpd_ssize_t size;
5551 char *s;
5552
5553 CONVERT_OP_RAISE(&a, v, context);
5554
5555 size = mpd_to_eng_size(&s, MPD(a), CtxCaps(context));
5556 Py_DECREF(a);
5557 if (size < 0) {
5558 PyErr_NoMemory();
5559 return NULL;
5560 }
5561
5562 result = unicode_fromascii(s, size);
5563 mpd_free(s);
5564
5565 return result;
5566 }
5567
5568 /* Functions with two decimal arguments */
5569 DecCtx_BinaryFunc_NO_CTX(mpd_compare_total)
5570 DecCtx_BinaryFunc_NO_CTX(mpd_compare_total_mag)
5571
5572 static PyObject *
5573 ctx_mpd_qcopy_sign(PyObject *context, PyObject *args)
5574 {
5575 PyObject *v, *w;
5576 PyObject *a, *b;
5577 PyObject *result;
5578 uint32_t status = 0;
5579
5580 if (!PyArg_ParseTuple(args, "OO", &v, &w)) {
5581 return NULL;
5582 }
5583
5584 CONVERT_BINOP_RAISE(&a, &b, v, w, context);
5585 decimal_state *state = get_module_state_by_def(Py_TYPE(context));
5586 result = dec_alloc(state);
5587 if (result == NULL) {
5588 Py_DECREF(a);
5589 Py_DECREF(b);
5590 return NULL;
5591 }
5592
5593 mpd_qcopy_sign(MPD(result), MPD(a), MPD(b), &status);
5594 Py_DECREF(a);
5595 Py_DECREF(b);
5596 if (dec_addstatus(context, status)) {
5597 Py_DECREF(result);
5598 return NULL;
5599 }
5600
5601 return result;
5602 }
5603
5604 DecCtx_BinaryFunc(mpd_qand)
5605 DecCtx_BinaryFunc(mpd_qor)
5606 DecCtx_BinaryFunc(mpd_qxor)
5607
5608 DecCtx_BinaryFunc(mpd_qrotate)
5609 DecCtx_BinaryFunc(mpd_qscaleb)
5610 DecCtx_BinaryFunc(mpd_qshift)
5611
5612 static PyObject *
5613 ctx_mpd_same_quantum(PyObject *context, PyObject *args)
5614 {
5615 PyObject *v, *w;
5616 PyObject *a, *b;
5617 PyObject *result;
5618
5619 if (!PyArg_ParseTuple(args, "OO", &v, &w)) {
5620 return NULL;
5621 }
5622
5623 CONVERT_BINOP_RAISE(&a, &b, v, w, context);
5624
5625 result = mpd_same_quantum(MPD(a), MPD(b)) ? incr_true() : incr_false();
5626 Py_DECREF(a);
5627 Py_DECREF(b);
5628
5629 return result;
5630 }
5631
5632
5633 static PyMethodDef context_methods [] =
5634 {
5635 /* Unary arithmetic functions */
5636 { "abs", ctx_mpd_qabs, METH_O, doc_ctx_abs },
5637 { "exp", ctx_mpd_qexp, METH_O, doc_ctx_exp },
5638 { "ln", ctx_mpd_qln, METH_O, doc_ctx_ln },
5639 { "log10", ctx_mpd_qlog10, METH_O, doc_ctx_log10 },
5640 { "minus", ctx_mpd_qminus, METH_O, doc_ctx_minus },
5641 { "next_minus", ctx_mpd_qnext_minus, METH_O, doc_ctx_next_minus },
5642 { "next_plus", ctx_mpd_qnext_plus, METH_O, doc_ctx_next_plus },
5643 { "normalize", ctx_mpd_qreduce, METH_O, doc_ctx_normalize },
5644 { "plus", ctx_mpd_qplus, METH_O, doc_ctx_plus },
5645 { "to_integral", ctx_mpd_qround_to_int, METH_O, doc_ctx_to_integral },
5646 { "to_integral_exact", ctx_mpd_qround_to_intx, METH_O, doc_ctx_to_integral_exact },
5647 { "to_integral_value", ctx_mpd_qround_to_int, METH_O, doc_ctx_to_integral_value },
5648 { "sqrt", ctx_mpd_qsqrt, METH_O, doc_ctx_sqrt },
5649
5650 /* Binary arithmetic functions */
5651 { "add", ctx_mpd_qadd, METH_VARARGS, doc_ctx_add },
5652 { "compare", ctx_mpd_qcompare, METH_VARARGS, doc_ctx_compare },
5653 { "compare_signal", ctx_mpd_qcompare_signal, METH_VARARGS, doc_ctx_compare_signal },
5654 { "divide", ctx_mpd_qdiv, METH_VARARGS, doc_ctx_divide },
5655 { "divide_int", ctx_mpd_qdivint, METH_VARARGS, doc_ctx_divide_int },
5656 { "divmod", ctx_mpd_qdivmod, METH_VARARGS, doc_ctx_divmod },
5657 { "max", ctx_mpd_qmax, METH_VARARGS, doc_ctx_max },
5658 { "max_mag", ctx_mpd_qmax_mag, METH_VARARGS, doc_ctx_max_mag },
5659 { "min", ctx_mpd_qmin, METH_VARARGS, doc_ctx_min },
5660 { "min_mag", ctx_mpd_qmin_mag, METH_VARARGS, doc_ctx_min_mag },
5661 { "multiply", ctx_mpd_qmul, METH_VARARGS, doc_ctx_multiply },
5662 { "next_toward", ctx_mpd_qnext_toward, METH_VARARGS, doc_ctx_next_toward },
5663 { "quantize", ctx_mpd_qquantize, METH_VARARGS, doc_ctx_quantize },
5664 { "remainder", ctx_mpd_qrem, METH_VARARGS, doc_ctx_remainder },
5665 { "remainder_near", ctx_mpd_qrem_near, METH_VARARGS, doc_ctx_remainder_near },
5666 { "subtract", ctx_mpd_qsub, METH_VARARGS, doc_ctx_subtract },
5667
5668 /* Binary or ternary arithmetic functions */
5669 { "power", _PyCFunction_CAST(ctx_mpd_qpow), METH_VARARGS|METH_KEYWORDS, doc_ctx_power },
5670
5671 /* Ternary arithmetic functions */
5672 { "fma", ctx_mpd_qfma, METH_VARARGS, doc_ctx_fma },
5673
5674 /* No argument */
5675 { "Etiny", context_getetiny, METH_NOARGS, doc_ctx_Etiny },
5676 { "Etop", context_getetop, METH_NOARGS, doc_ctx_Etop },
5677 { "radix", ctx_mpd_radix, METH_NOARGS, doc_ctx_radix },
5678
5679 /* Boolean functions */
5680 { "is_canonical", ctx_iscanonical, METH_O, doc_ctx_is_canonical },
5681 { "is_finite", ctx_mpd_isfinite, METH_O, doc_ctx_is_finite },
5682 { "is_infinite", ctx_mpd_isinfinite, METH_O, doc_ctx_is_infinite },
5683 { "is_nan", ctx_mpd_isnan, METH_O, doc_ctx_is_nan },
5684 { "is_normal", ctx_mpd_isnormal, METH_O, doc_ctx_is_normal },
5685 { "is_qnan", ctx_mpd_isqnan, METH_O, doc_ctx_is_qnan },
5686 { "is_signed", ctx_mpd_issigned, METH_O, doc_ctx_is_signed },
5687 { "is_snan", ctx_mpd_issnan, METH_O, doc_ctx_is_snan },
5688 { "is_subnormal", ctx_mpd_issubnormal, METH_O, doc_ctx_is_subnormal },
5689 { "is_zero", ctx_mpd_iszero, METH_O, doc_ctx_is_zero },
5690
5691 /* Functions with a single decimal argument */
5692 { "_apply", PyDecContext_Apply, METH_O, NULL }, /* alias for apply */
5693 #ifdef EXTRA_FUNCTIONALITY
5694 { "apply", PyDecContext_Apply, METH_O, doc_ctx_apply },
5695 #endif
5696 { "canonical", ctx_canonical, METH_O, doc_ctx_canonical },
5697 { "copy_abs", ctx_mpd_qcopy_abs, METH_O, doc_ctx_copy_abs },
5698 { "copy_decimal", ctx_copy_decimal, METH_O, doc_ctx_copy_decimal },
5699 { "copy_negate", ctx_mpd_qcopy_negate, METH_O, doc_ctx_copy_negate },
5700 { "logb", ctx_mpd_qlogb, METH_O, doc_ctx_logb },
5701 { "logical_invert", ctx_mpd_qinvert, METH_O, doc_ctx_logical_invert },
5702 { "number_class", ctx_mpd_class, METH_O, doc_ctx_number_class },
5703 { "to_sci_string", ctx_mpd_to_sci, METH_O, doc_ctx_to_sci_string },
5704 { "to_eng_string", ctx_mpd_to_eng, METH_O, doc_ctx_to_eng_string },
5705
5706 /* Functions with two decimal arguments */
5707 { "compare_total", ctx_mpd_compare_total, METH_VARARGS, doc_ctx_compare_total },
5708 { "compare_total_mag", ctx_mpd_compare_total_mag, METH_VARARGS, doc_ctx_compare_total_mag },
5709 { "copy_sign", ctx_mpd_qcopy_sign, METH_VARARGS, doc_ctx_copy_sign },
5710 { "logical_and", ctx_mpd_qand, METH_VARARGS, doc_ctx_logical_and },
5711 { "logical_or", ctx_mpd_qor, METH_VARARGS, doc_ctx_logical_or },
5712 { "logical_xor", ctx_mpd_qxor, METH_VARARGS, doc_ctx_logical_xor },
5713 { "rotate", ctx_mpd_qrotate, METH_VARARGS, doc_ctx_rotate },
5714 { "same_quantum", ctx_mpd_same_quantum, METH_VARARGS, doc_ctx_same_quantum },
5715 { "scaleb", ctx_mpd_qscaleb, METH_VARARGS, doc_ctx_scaleb },
5716 { "shift", ctx_mpd_qshift, METH_VARARGS, doc_ctx_shift },
5717
5718 /* Set context values */
5719 { "clear_flags", context_clear_flags, METH_NOARGS, doc_ctx_clear_flags },
5720 { "clear_traps", context_clear_traps, METH_NOARGS, doc_ctx_clear_traps },
5721
5722 #ifdef CONFIG_32
5723 /* Unsafe set functions with relaxed range checks */
5724 { "_unsafe_setprec", context_unsafe_setprec, METH_O, NULL },
5725 { "_unsafe_setemin", context_unsafe_setemin, METH_O, NULL },
5726 { "_unsafe_setemax", context_unsafe_setemax, METH_O, NULL },
5727 #endif
5728
5729 /* Miscellaneous */
5730 { "__copy__", (PyCFunction)context_copy, METH_NOARGS, NULL },
5731 { "__reduce__", context_reduce, METH_NOARGS, NULL },
5732 { "copy", (PyCFunction)context_copy, METH_NOARGS, doc_ctx_copy },
5733 { "create_decimal", ctx_create_decimal, METH_VARARGS, doc_ctx_create_decimal },
5734 { "create_decimal_from_float", ctx_from_float, METH_O, doc_ctx_create_decimal_from_float },
5735
5736 { NULL, NULL, 1 }
5737 };
5738
5739 static PyType_Slot context_slots[] = {
5740 {Py_tp_dealloc, context_dealloc},
5741 {Py_tp_traverse, context_traverse},
5742 {Py_tp_clear, context_clear},
5743 {Py_tp_repr, context_repr},
5744 {Py_tp_getattro, context_getattr},
5745 {Py_tp_setattro, context_setattr},
5746 {Py_tp_doc, (void *)doc_context},
5747 {Py_tp_methods, context_methods},
5748 {Py_tp_getset, context_getsets},
5749 {Py_tp_init, context_init},
5750 {Py_tp_new, context_new},
5751 {0, NULL},
5752 };
5753
5754 static PyType_Spec context_spec = {
5755 .name = "decimal.Context",
5756 .basicsize = sizeof(PyDecContextObject),
5757 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5758 Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE),
5759 .slots = context_slots,
5760 };
5761
5762
5763 static PyMethodDef _decimal_methods [] =
5764 {
5765 { "getcontext", (PyCFunction)PyDec_GetCurrentContext, METH_NOARGS, doc_getcontext},
5766 { "setcontext", (PyCFunction)PyDec_SetCurrentContext, METH_O, doc_setcontext},
5767 { "localcontext", _PyCFunction_CAST(ctxmanager_new), METH_VARARGS|METH_KEYWORDS, doc_localcontext},
5768 #ifdef EXTRA_FUNCTIONALITY
5769 { "IEEEContext", (PyCFunction)ieee_context, METH_O, doc_ieee_context},
5770 #endif
5771 { NULL, NULL, 1, NULL }
5772 };
5773
5774
5775 struct ssize_constmap { const char *name; mpd_ssize_t val; };
5776 static struct ssize_constmap ssize_constants [] = {
5777 {"MAX_PREC", MPD_MAX_PREC},
5778 {"MAX_EMAX", MPD_MAX_EMAX},
5779 {"MIN_EMIN", MPD_MIN_EMIN},
5780 {"MIN_ETINY", MPD_MIN_ETINY},
5781 {NULL}
5782 };
5783
5784 struct int_constmap { const char *name; int val; };
5785 static struct int_constmap int_constants [] = {
5786 /* int constants */
5787 #ifdef EXTRA_FUNCTIONALITY
5788 {"DECIMAL32", MPD_DECIMAL32},
5789 {"DECIMAL64", MPD_DECIMAL64},
5790 {"DECIMAL128", MPD_DECIMAL128},
5791 {"IEEE_CONTEXT_MAX_BITS", MPD_IEEE_CONTEXT_MAX_BITS},
5792 /* int condition flags */
5793 {"DecClamped", MPD_Clamped},
5794 {"DecConversionSyntax", MPD_Conversion_syntax},
5795 {"DecDivisionByZero", MPD_Division_by_zero},
5796 {"DecDivisionImpossible", MPD_Division_impossible},
5797 {"DecDivisionUndefined", MPD_Division_undefined},
5798 {"DecFpuError", MPD_Fpu_error},
5799 {"DecInexact", MPD_Inexact},
5800 {"DecInvalidContext", MPD_Invalid_context},
5801 {"DecInvalidOperation", MPD_Invalid_operation},
5802 {"DecIEEEInvalidOperation", MPD_IEEE_Invalid_operation},
5803 {"DecMallocError", MPD_Malloc_error},
5804 {"DecFloatOperation", MPD_Float_operation},
5805 {"DecOverflow", MPD_Overflow},
5806 {"DecRounded", MPD_Rounded},
5807 {"DecSubnormal", MPD_Subnormal},
5808 {"DecUnderflow", MPD_Underflow},
5809 {"DecErrors", MPD_Errors},
5810 {"DecTraps", MPD_Traps},
5811 #endif
5812 {NULL}
5813 };
5814
5815
5816 #define CHECK_INT(expr) \
5817 do { if ((expr) < 0) goto error; } while (0)
5818 #define ASSIGN_PTR(result, expr) \
5819 do { result = (expr); if (result == NULL) goto error; } while (0)
5820 #define CHECK_PTR(expr) \
5821 do { if ((expr) == NULL) goto error; } while (0)
5822
5823
5824 static PyCFunction
5825 cfunc_noargs(PyTypeObject *t, const char *name)
5826 {
5827 struct PyMethodDef *m;
5828
5829 if (t->tp_methods == NULL) {
5830 goto error;
5831 }
5832
5833 for (m = t->tp_methods; m->ml_name != NULL; m++) {
5834 if (strcmp(name, m->ml_name) == 0) {
5835 if (!(m->ml_flags & METH_NOARGS)) {
5836 goto error;
5837 }
5838 return m->ml_meth;
5839 }
5840 }
5841
5842 error:
5843 PyErr_Format(PyExc_RuntimeError,
5844 "internal error: could not find method %s", name);
5845 return NULL;
5846 }
5847
5848 static int minalloc_is_set = 0;
5849
5850 static int
5851 _decimal_exec(PyObject *m)
5852 {
5853 PyObject *numbers = NULL;
5854 PyObject *Number = NULL;
5855 PyObject *collections = NULL;
5856 PyObject *collections_abc = NULL;
5857 PyObject *MutableMapping = NULL;
5858 PyObject *obj = NULL;
5859 DecCondMap *cm;
5860 struct ssize_constmap *ssize_cm;
5861 struct int_constmap *int_cm;
5862 int i;
5863
5864
5865 /* Init libmpdec */
5866 mpd_traphandler = dec_traphandler;
5867 mpd_mallocfunc = PyMem_Malloc;
5868 mpd_reallocfunc = PyMem_Realloc;
5869 mpd_callocfunc = mpd_callocfunc_em;
5870 mpd_free = PyMem_Free;
5871
5872 /* Suppress the warning caused by multi-phase initialization */
5873 if (!minalloc_is_set) {
5874 mpd_setminalloc(_Py_DEC_MINALLOC);
5875 minalloc_is_set = 1;
5876 }
5877
5878 decimal_state *state = get_module_state(m);
5879
5880 /* Init external C-API functions */
5881 state->_py_long_multiply = PyLong_Type.tp_as_number->nb_multiply;
5882 state->_py_long_floor_divide = PyLong_Type.tp_as_number->nb_floor_divide;
5883 state->_py_long_power = PyLong_Type.tp_as_number->nb_power;
5884 state->_py_float_abs = PyFloat_Type.tp_as_number->nb_absolute;
5885 ASSIGN_PTR(state->_py_float_as_integer_ratio,
5886 cfunc_noargs(&PyFloat_Type, "as_integer_ratio"));
5887 ASSIGN_PTR(state->_py_long_bit_length,
5888 cfunc_noargs(&PyLong_Type, "bit_length"));
5889
5890
5891 /* Init types */
5892 #define CREATE_TYPE(mod, tp, spec) do { \
5893 tp = (PyTypeObject *)PyType_FromMetaclass(NULL, mod, spec, NULL); \
5894 CHECK_PTR(tp); \
5895 } while (0)
5896
5897 CREATE_TYPE(m, state->PyDec_Type, &dec_spec);
5898 CREATE_TYPE(m, state->PyDecContext_Type, &context_spec);
5899 CREATE_TYPE(m, state->PyDecContextManager_Type, &ctxmanager_spec);
5900 CREATE_TYPE(m, state->PyDecSignalDictMixin_Type, &signaldict_spec);
5901
5902 #undef CREATE_TYPE
5903
5904 ASSIGN_PTR(obj, PyUnicode_FromString("decimal"));
5905 CHECK_INT(PyDict_SetItemString(state->PyDec_Type->tp_dict, "__module__", obj));
5906 CHECK_INT(PyDict_SetItemString(state->PyDecContext_Type->tp_dict,
5907 "__module__", obj));
5908 Py_CLEAR(obj);
5909
5910
5911 /* Numeric abstract base classes */
5912 ASSIGN_PTR(numbers, PyImport_ImportModule("numbers"));
5913 ASSIGN_PTR(Number, PyObject_GetAttrString(numbers, "Number"));
5914 /* Register Decimal with the Number abstract base class */
5915 ASSIGN_PTR(obj, PyObject_CallMethod(Number, "register", "(O)",
5916 (PyObject *)state->PyDec_Type));
5917 Py_CLEAR(obj);
5918 /* Rational is a global variable used for fraction comparisons. */
5919 ASSIGN_PTR(state->Rational, PyObject_GetAttrString(numbers, "Rational"));
5920 /* Done with numbers, Number */
5921 Py_CLEAR(numbers);
5922 Py_CLEAR(Number);
5923
5924 /* DecimalTuple */
5925 ASSIGN_PTR(collections, PyImport_ImportModule("collections"));
5926 ASSIGN_PTR(obj, PyObject_CallMethod(collections, "namedtuple", "(ss)",
5927 "DecimalTuple",
5928 "sign digits exponent"));
5929 if (!PyType_Check(obj)) {
5930 PyErr_SetString(PyExc_TypeError,
5931 "type is expected from namedtuple call");
5932 goto error;
5933 }
5934 ASSIGN_PTR(state->DecimalTuple, (PyTypeObject *)obj);
5935 ASSIGN_PTR(obj, PyUnicode_FromString("decimal"));
5936 CHECK_INT(PyDict_SetItemString(state->DecimalTuple->tp_dict, "__module__", obj));
5937 Py_CLEAR(obj);
5938
5939 /* MutableMapping */
5940 ASSIGN_PTR(collections_abc, PyImport_ImportModule("collections.abc"));
5941 ASSIGN_PTR(MutableMapping, PyObject_GetAttrString(collections_abc,
5942 "MutableMapping"));
5943 /* Create SignalDict type */
5944 ASSIGN_PTR(state->PyDecSignalDict_Type,
5945 (PyTypeObject *)PyObject_CallFunction(
5946 (PyObject *)&PyType_Type, "s(OO){}",
5947 "SignalDict", state->PyDecSignalDictMixin_Type,
5948 MutableMapping));
5949
5950 /* Done with collections, MutableMapping */
5951 Py_CLEAR(collections);
5952 Py_CLEAR(collections_abc);
5953 Py_CLEAR(MutableMapping);
5954
5955 /* For format specifiers not yet supported by libmpdec */
5956 state->PyDecimal = NULL;
5957
5958 /* Add types to the module */
5959 CHECK_INT(PyModule_AddType(m, state->PyDec_Type));
5960 CHECK_INT(PyModule_AddType(m, state->PyDecContext_Type));
5961 CHECK_INT(PyModule_AddType(m, state->DecimalTuple));
5962
5963 /* Create top level exception */
5964 ASSIGN_PTR(state->DecimalException, PyErr_NewException(
5965 "decimal.DecimalException",
5966 PyExc_ArithmeticError, NULL));
5967 CHECK_INT(PyModule_AddType(m, (PyTypeObject *)state->DecimalException));
5968
5969 /* Create signal tuple */
5970 ASSIGN_PTR(state->SignalTuple, PyTuple_New(SIGNAL_MAP_LEN));
5971
5972 /* Add exceptions that correspond to IEEE signals */
5973 ASSIGN_PTR(state->signal_map, dec_cond_map_init(signal_map_template,
5974 sizeof(signal_map_template)));
5975 for (i = SIGNAL_MAP_LEN-1; i >= 0; i--) {
5976 PyObject *base;
5977
5978 cm = state->signal_map + i;
5979
5980 switch (cm->flag) {
5981 case MPD_Float_operation:
5982 base = PyTuple_Pack(2, state->DecimalException, PyExc_TypeError);
5983 break;
5984 case MPD_Division_by_zero:
5985 base = PyTuple_Pack(2, state->DecimalException,
5986 PyExc_ZeroDivisionError);
5987 break;
5988 case MPD_Overflow:
5989 base = PyTuple_Pack(2, state->signal_map[INEXACT].ex,
5990 state->signal_map[ROUNDED].ex);
5991 break;
5992 case MPD_Underflow:
5993 base = PyTuple_Pack(3, state->signal_map[INEXACT].ex,
5994 state->signal_map[ROUNDED].ex,
5995 state->signal_map[SUBNORMAL].ex);
5996 break;
5997 default:
5998 base = PyTuple_Pack(1, state->DecimalException);
5999 break;
6000 }
6001
6002 if (base == NULL) {
6003 goto error; /* GCOV_NOT_REACHED */
6004 }
6005
6006 ASSIGN_PTR(cm->ex, PyErr_NewException(cm->fqname, base, NULL));
6007 Py_DECREF(base);
6008
6009 /* add to module */
6010 CHECK_INT(PyModule_AddObjectRef(m, cm->name, cm->ex));
6011
6012 /* add to signal tuple */
6013 PyTuple_SET_ITEM(state->SignalTuple, i, Py_NewRef(cm->ex));
6014 }
6015
6016 /*
6017 * Unfortunately, InvalidOperation is a signal that comprises
6018 * several conditions, including InvalidOperation! Naming the
6019 * signal IEEEInvalidOperation would prevent the confusion.
6020 */
6021 ASSIGN_PTR(state->cond_map, dec_cond_map_init(cond_map_template,
6022 sizeof(cond_map_template)));
6023 state->cond_map[0].ex = state->signal_map[0].ex;
6024
6025 /* Add remaining exceptions, inherit from InvalidOperation */
6026 for (cm = state->cond_map+1; cm->name != NULL; cm++) {
6027 PyObject *base;
6028 if (cm->flag == MPD_Division_undefined) {
6029 base = PyTuple_Pack(2, state->signal_map[0].ex, PyExc_ZeroDivisionError);
6030 }
6031 else {
6032 base = PyTuple_Pack(1, state->signal_map[0].ex);
6033 }
6034 if (base == NULL) {
6035 goto error; /* GCOV_NOT_REACHED */
6036 }
6037
6038 ASSIGN_PTR(cm->ex, PyErr_NewException(cm->fqname, base, NULL));
6039 Py_DECREF(base);
6040
6041 CHECK_INT(PyModule_AddObjectRef(m, cm->name, cm->ex));
6042 }
6043
6044
6045 /* Init default context template first */
6046 ASSIGN_PTR(state->default_context_template,
6047 PyObject_CallObject((PyObject *)state->PyDecContext_Type, NULL));
6048 CHECK_INT(PyModule_AddObjectRef(m, "DefaultContext",
6049 state->default_context_template));
6050
6051 #ifndef WITH_DECIMAL_CONTEXTVAR
6052 ASSIGN_PTR(state->tls_context_key,
6053 PyUnicode_FromString("___DECIMAL_CTX__"));
6054 CHECK_INT(PyModule_AddObjectRef(m, "HAVE_CONTEXTVAR", Py_False));
6055 #else
6056 ASSIGN_PTR(state->current_context_var, PyContextVar_New("decimal_context", NULL));
6057 CHECK_INT(PyModule_AddObjectRef(m, "HAVE_CONTEXTVAR", Py_True));
6058 #endif
6059 CHECK_INT(PyModule_AddObjectRef(m, "HAVE_THREADS", Py_True));
6060
6061 /* Init basic context template */
6062 ASSIGN_PTR(state->basic_context_template,
6063 PyObject_CallObject((PyObject *)state->PyDecContext_Type, NULL));
6064 init_basic_context(state->basic_context_template);
6065 CHECK_INT(PyModule_AddObjectRef(m, "BasicContext",
6066 state->basic_context_template));
6067
6068 /* Init extended context template */
6069 ASSIGN_PTR(state->extended_context_template,
6070 PyObject_CallObject((PyObject *)state->PyDecContext_Type, NULL));
6071 init_extended_context(state->extended_context_template);
6072 CHECK_INT(PyModule_AddObjectRef(m, "ExtendedContext",
6073 state->extended_context_template));
6074
6075
6076 /* Init mpd_ssize_t constants */
6077 for (ssize_cm = ssize_constants; ssize_cm->name != NULL; ssize_cm++) {
6078 CHECK_INT(PyModule_Add(m, ssize_cm->name,
6079 PyLong_FromSsize_t(ssize_cm->val)));
6080 }
6081
6082 /* Init int constants */
6083 for (int_cm = int_constants; int_cm->name != NULL; int_cm++) {
6084 CHECK_INT(PyModule_AddIntConstant(m, int_cm->name,
6085 int_cm->val));
6086 }
6087
6088 /* Init string constants */
6089 for (i = 0; i < _PY_DEC_ROUND_GUARD; i++) {
6090 ASSIGN_PTR(state->round_map[i], PyUnicode_InternFromString(mpd_round_string[i]));
6091 CHECK_INT(PyModule_AddObjectRef(m, mpd_round_string[i], state->round_map[i]));
6092 }
6093
6094 /* Add specification version number */
6095 CHECK_INT(PyModule_AddStringConstant(m, "__version__", "1.70"));
6096 CHECK_INT(PyModule_AddStringConstant(m, "__libmpdec_version__", mpd_version()));
6097
6098 return 0;
6099
6100 error:
6101 Py_CLEAR(obj); /* GCOV_NOT_REACHED */
6102 Py_CLEAR(numbers); /* GCOV_NOT_REACHED */
6103 Py_CLEAR(Number); /* GCOV_NOT_REACHED */
6104 Py_CLEAR(collections); /* GCOV_NOT_REACHED */
6105 Py_CLEAR(collections_abc); /* GCOV_NOT_REACHED */
6106 Py_CLEAR(MutableMapping); /* GCOV_NOT_REACHED */
6107
6108 return -1;
6109 }
6110
6111 static int
6112 decimal_traverse(PyObject *module, visitproc visit, void *arg)
6113 {
6114 decimal_state *state = get_module_state(module);
6115 Py_VISIT(state->PyDecContextManager_Type);
6116 Py_VISIT(state->PyDecContext_Type);
6117 Py_VISIT(state->PyDecSignalDictMixin_Type);
6118 Py_VISIT(state->PyDec_Type);
6119 Py_VISIT(state->PyDecSignalDict_Type);
6120 Py_VISIT(state->DecimalTuple);
6121 Py_VISIT(state->DecimalException);
6122
6123 #ifndef WITH_DECIMAL_CONTEXTVAR
6124 Py_VISIT(state->tls_context_key);
6125 Py_VISIT(state->cached_context);
6126 #else
6127 Py_VISIT(state->current_context_var);
6128 #endif
6129
6130 Py_VISIT(state->default_context_template);
6131 Py_VISIT(state->basic_context_template);
6132 Py_VISIT(state->extended_context_template);
6133 Py_VISIT(state->Rational);
6134 Py_VISIT(state->SignalTuple);
6135
6136 if (state->signal_map != NULL) {
6137 for (DecCondMap *cm = state->signal_map; cm->name != NULL; cm++) {
6138 Py_VISIT(cm->ex);
6139 }
6140 }
6141 if (state->cond_map != NULL) {
6142 for (DecCondMap *cm = state->cond_map + 1; cm->name != NULL; cm++) {
6143 Py_VISIT(cm->ex);
6144 }
6145 }
6146 return 0;
6147 }
6148
6149 static int
6150 decimal_clear(PyObject *module)
6151 {
6152 decimal_state *state = get_module_state(module);
6153 Py_CLEAR(state->PyDecContextManager_Type);
6154 Py_CLEAR(state->PyDecContext_Type);
6155 Py_CLEAR(state->PyDecSignalDictMixin_Type);
6156 Py_CLEAR(state->PyDec_Type);
6157 Py_CLEAR(state->PyDecSignalDict_Type);
6158 Py_CLEAR(state->DecimalTuple);
6159 Py_CLEAR(state->DecimalException);
6160
6161 #ifndef WITH_DECIMAL_CONTEXTVAR
6162 Py_CLEAR(state->tls_context_key);
6163 Py_CLEAR(state->cached_context);
6164 #else
6165 Py_CLEAR(state->current_context_var);
6166 #endif
6167
6168 Py_CLEAR(state->default_context_template);
6169 Py_CLEAR(state->basic_context_template);
6170 Py_CLEAR(state->extended_context_template);
6171 Py_CLEAR(state->Rational);
6172 Py_CLEAR(state->SignalTuple);
6173 Py_CLEAR(state->PyDecimal);
6174
6175 if (state->signal_map != NULL) {
6176 for (DecCondMap *cm = state->signal_map; cm->name != NULL; cm++) {
6177 Py_DECREF(cm->ex);
6178 }
6179 PyMem_Free(state->signal_map);
6180 state->signal_map = NULL;
6181 }
6182
6183 if (state->cond_map != NULL) {
6184 // cond_map[0].ex has borrowed a reference from signal_map[0].ex
6185 for (DecCondMap *cm = state->cond_map + 1; cm->name != NULL; cm++) {
6186 Py_DECREF(cm->ex);
6187 }
6188 PyMem_Free(state->cond_map);
6189 state->cond_map = NULL;
6190 }
6191 return 0;
6192 }
6193
6194 static void
6195 decimal_free(void *module)
6196 {
6197 (void)decimal_clear((PyObject *)module);
6198 }
6199
6200 static struct PyModuleDef_Slot _decimal_slots[] = {
6201 {Py_mod_exec, _decimal_exec},
6202 {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
6203 {Py_mod_gil, Py_MOD_GIL_NOT_USED},
6204 {0, NULL},
6205 };
6206
6207 static struct PyModuleDef _decimal_module = {
6208 PyModuleDef_HEAD_INIT,
6209 .m_name = "decimal",
6210 .m_doc = doc__decimal,
6211 .m_size = sizeof(decimal_state),
6212 .m_methods = _decimal_methods,
6213 .m_slots = _decimal_slots,
6214 .m_traverse = decimal_traverse,
6215 .m_clear = decimal_clear,
6216 .m_free = decimal_free,
6217 };
6218
6219 PyMODINIT_FUNC
6220 PyInit__decimal(void)
6221 {
6222 return PyModuleDef_Init(&_decimal_module);
6223 }