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