You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

5784 lines
168 KiB

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