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