GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — cpython/Modules/_decimal/_decimal.c at dea4083aa952c955a7c3a7657034bd38889a4e22 · python/cpython Expand file tree/ Copy path_decimal.cMore file actions 8046 lines (6684 loc) · 232 KB / Copy path_decimal.cFile metadata and controls8046 lines (6684 loc) · 232 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 /* * Copyright (c) 2008-2012 Stefan Krah. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef Py_BUILD_CORE_BUILTIN # define Py_BUILD_CORE_MODULE 1 #endif #include <Python.h> #include "pycore_object.h" // _PyObject_VisitType() #include "pycore_pystate.h" // _PyThreadState_GET() #include "pycore_tuple.h" // _PyTuple_FromPair #include "pycore_typeobject.h" #include <mpdecimal.h> // Reuse config from mpdecimal.h if present. #if defined(MPD_CONFIG_64) #ifndef CONFIG_64 #define CONFIG_64 MPD_CONFIG_64 #endif #elif defined(MPD_CONFIG_32) #ifndef CONFIG_32 #define CONFIG_32 MPD_CONFIG_32 #endif #endif #include <ctype.h> // isascii() #include <stdlib.h> #ifdef EXTRA_FUNCTIONALITY #define _PY_DEC_ROUND_GUARD MPD_ROUND_GUARD #else #define _PY_DEC_ROUND_GUARD (MPD_ROUND_GUARD-1) #endif #include "clinic/_decimal.c.h" #define MPD_SPEC_VERSION "1.70" // Highest version of the spec this complies with // See https://speleotrove.com/decimal/decarith.html /*[clinic input] module _decimal class _decimal.Decimal "PyObject *" "&dec_spec" class _decimal.Context "PyObject *" "&context_spec" [clinic start generated code]*/ /*[clinic end generated code: output=da39a3ee5e6b4b0d input=a6a6c0bdf4e576ef]*/ struct PyDecContextObject; struct DecCondMap; typedef struct { PyTypeObject *PyDecContextManager_Type; PyTypeObject *PyDecContext_Type; PyTypeObject *PyDecSignalDictMixin_Type; PyTypeObject *PyDec_Type; PyTypeObject *PyDecSignalDict_Type; PyTypeObject *DecimalTuple; /* Top level Exception; inherits from ArithmeticError */ PyObject *DecimalException; #ifndef WITH_DECIMAL_CONTEXTVAR /* Key for thread state dictionary */ PyObject *tls_context_key; /* Invariant: NULL or a strong reference to the most recently accessed thread local context. */ struct PyDecContextObject *cached_context; /* Not borrowed */ #else PyObject *current_context_var; #endif /* Template for creating new thread contexts, calling Context() without * arguments and initializing the module_context on first access. */ PyObject *default_context_template; /* Basic and extended context templates */ PyObject *basic_context_template; PyObject *extended_context_template; PyObject *round_map[_PY_DEC_ROUND_GUARD]; /* Convert rationals for comparison */ PyObject *Rational; /* Invariant: NULL or pointer to _pydecimal.Decimal */ PyObject *PyDecimal; PyObject *SignalTuple; struct DecCondMap *signal_map; struct DecCondMap *cond_map; /* External C-API functions */ binaryfunc _py_long_multiply; binaryfunc _py_long_floor_divide; ternaryfunc _py_long_power; unaryfunc _py_float_abs; PyCFunction _py_long_bit_length; PyCFunction _py_float_as_integer_ratio; } decimal_state; static inline decimal_state * get_module_state(PyObject *mod) { decimal_state *state = _PyModule_GetState(mod); assert(state != NULL); return state; } static struct PyModuleDef _decimal_module; static PyType_Spec dec_spec; static PyType_Spec context_spec; static inline decimal_state * get_module_state_by_def(PyTypeObject *tp) { PyObject *mod = PyType_GetModuleByDef(tp, &_decimal_module); assert(mod != NULL); return get_module_state(mod); } static inline decimal_state * find_state_left_or_right(PyObject *left, PyObject *right) { PyTypeObject *base; if (PyType_GetBaseByToken(Py_TYPE(left), &dec_spec, &base) != 1) { assert(!PyErr_Occurred()); PyType_GetBaseByToken(Py_TYPE(right), &dec_spec, &base); } assert(base != NULL); void *state = _PyType_GetModuleState(base); assert(state != NULL); Py_DECREF(base); return (decimal_state *)state; } static inline decimal_state * find_state_ternary(PyObject *left, PyObject *right, PyObject *modulus) { PyTypeObject *base; if (PyType_GetBaseByToken(Py_TYPE(left), &dec_spec, &base) != 1) { assert(!PyErr_Occurred()); if (PyType_GetBaseByToken(Py_TYPE(right), &dec_spec, &base) != 1) { assert(!PyErr_Occurred()); PyType_GetBaseByToken(Py_TYPE(modulus), &dec_spec, &base); } } assert(base != NULL); void *state = _PyType_GetModuleState(base); assert(state != NULL); Py_DECREF(base); return (decimal_state *)state; } #if !defined(MPD_VERSION_HEX) || MPD_VERSION_HEX < 0x02050000 #error "libmpdec version >= 2.5.0 required" #endif /* * Type sizes with assertions in mpdecimal.h and pyport.h: * sizeof(size_t) == sizeof(Py_ssize_t) * sizeof(size_t) == sizeof(mpd_uint_t) == sizeof(mpd_ssize_t) */ #ifdef TEST_COVERAGE #undef Py_LOCAL_INLINE #define Py_LOCAL_INLINE Py_LOCAL #endif #define MPD_Float_operation MPD_Not_implemented #define BOUNDS_CHECK(x, MIN, MAX) x = (x < MIN || MAX < x) ? MAX : x /* _Py_DEC_MINALLOC >= MPD_MINALLOC */ #define _Py_DEC_MINALLOC 4 typedef struct { PyObject_HEAD Py_hash_t hash; mpd_t dec; mpd_uint_t data[_Py_DEC_MINALLOC]; } PyDecObject; #define _PyDecObject_CAST(op) ((PyDecObject *)(op)) typedef struct { PyObject_HEAD uint32_t *flags; } PyDecSignalDictObject; #define _PyDecSignalDictObject_CAST(op) ((PyDecSignalDictObject *)(op)) typedef struct PyDecContextObject { PyObject_HEAD mpd_context_t ctx; PyObject *traps; PyObject *flags; int capitals; PyThreadState *tstate; decimal_state *modstate; } PyDecContextObject; #define _PyDecContextObject_CAST(op) ((PyDecContextObject *)(op)) typedef struct { PyObject_HEAD PyObject *local; PyObject *global; } PyDecContextManagerObject; #define _PyDecContextManagerObject_CAST(op) ((PyDecContextManagerObject *)(op)) #undef MPD #undef CTX #define PyDec_CheckExact(st, v) Py_IS_TYPE(v, (st)->PyDec_Type) #define PyDec_Check(st, v) PyObject_TypeCheck(v, (st)->PyDec_Type) #define PyDecSignalDict_Check(st, v) Py_IS_TYPE(v, (st)->PyDecSignalDict_Type) #define PyDecContext_Check(st, v) PyObject_TypeCheck(v, (st)->PyDecContext_Type) #define MPD(v) (&_PyDecObject_CAST(v)->dec) #define SdFlagAddr(v) (_PyDecSignalDictObject_CAST(v)->flags) #define SdFlags(v) (*_PyDecSignalDictObject_CAST(v)->flags) #define CTX(v) (&_PyDecContextObject_CAST(v)->ctx) #define CtxCaps(v) (_PyDecContextObject_CAST(v)->capitals) static inline decimal_state * get_module_state_from_ctx(PyObject *v) { assert(PyType_GetBaseByToken(Py_TYPE(v), &context_spec, NULL) == 1); decimal_state *state = ((PyDecContextObject *)v)->modstate; assert(state != NULL); return state; } Py_LOCAL_INLINE(PyObject *) incr_true(void) { return Py_NewRef(Py_True); } Py_LOCAL_INLINE(PyObject *) incr_false(void) { return Py_NewRef(Py_False); } /* Error codes for functions that return signals or conditions */ #define DEC_INVALID_SIGNALS (MPD_Max_status+1U) #define DEC_ERR_OCCURRED (DEC_INVALID_SIGNALS<<1) #define DEC_ERRORS (DEC_INVALID_SIGNALS|DEC_ERR_OCCURRED) typedef struct DecCondMap { const char *name; /* condition or signal name */ const char *fqname; /* fully qualified name */ uint32_t flag; /* libmpdec flag */ PyObject *ex; /* corresponding exception */ } DecCondMap; /* Exceptions that correspond to IEEE signals */ #define SUBNORMAL 5 #define INEXACT 6 #define ROUNDED 7 #define SIGNAL_MAP_LEN 9 static DecCondMap signal_map_template[] = { {"InvalidOperation", "decimal.InvalidOperation", MPD_IEEE_Invalid_operation, NULL}, {"FloatOperation", "decimal.FloatOperation", MPD_Float_operation, NULL}, {"DivisionByZero", "decimal.DivisionByZero", MPD_Division_by_zero, NULL}, {"Overflow", "decimal.Overflow", MPD_Overflow, NULL}, {"Underflow", "decimal.Underflow", MPD_Underflow, NULL}, {"Subnormal", "decimal.Subnormal", MPD_Subnormal, NULL}, {"Inexact", "decimal.Inexact", MPD_Inexact, NULL}, {"Rounded", "decimal.Rounded", MPD_Rounded, NULL}, {"Clamped", "decimal.Clamped", MPD_Clamped, NULL}, {NULL} }; /* Exceptions that inherit from InvalidOperation */ static DecCondMap cond_map_template[] = { {"InvalidOperation", "decimal.InvalidOperation", MPD_Invalid_operation, NULL}, {"ConversionSyntax", "decimal.ConversionSyntax", MPD_Conversion_syntax, NULL}, {"DivisionImpossible", "decimal.DivisionImpossible", MPD_Division_impossible, NULL}, {"DivisionUndefined", "decimal.DivisionUndefined", MPD_Division_undefined, NULL}, {"InvalidContext", "decimal.InvalidContext", MPD_Invalid_context, NULL}, #ifdef EXTRA_FUNCTIONALITY {"MallocError", "decimal.MallocError", MPD_Malloc_error, NULL}, #endif {NULL} }; /* Return a duplicate of DecCondMap template */ static inline DecCondMap * dec_cond_map_init(DecCondMap *template, Py_ssize_t size) { DecCondMap *cm; cm = PyMem_Malloc(size); if (cm == NULL) { PyErr_NoMemory(); return NULL; } memcpy(cm, template, size); return cm; } static const char *dec_signal_string[MPD_NUM_FLAGS] = { "Clamped", "InvalidOperation", "DivisionByZero", "InvalidOperation", "InvalidOperation", "InvalidOperation", "Inexact", "InvalidOperation", "InvalidOperation", "InvalidOperation", "FloatOperation", "Overflow", "Rounded", "Subnormal", "Underflow", }; static const char *invalid_rounding_err = "valid values for rounding are:\n\ [ROUND_CEILING, ROUND_FLOOR, ROUND_UP, ROUND_DOWN,\n\ ROUND_HALF_UP, ROUND_HALF_DOWN, ROUND_HALF_EVEN,\n\ ROUND_05UP]"; static const char *invalid_signals_err = "valid values for signals are:\n\ [InvalidOperation, FloatOperation, DivisionByZero,\n\ Overflow, Underflow, Subnormal, Inexact, Rounded,\n\ Clamped]"; #ifdef EXTRA_FUNCTIONALITY static const char *invalid_flags_err = "valid values for _flags or _traps are:\n\ signals:\n\ [DecIEEEInvalidOperation, DecFloatOperation, DecDivisionByZero,\n\ DecOverflow, DecUnderflow, DecSubnormal, DecInexact, DecRounded,\n\ DecClamped]\n\ conditions which trigger DecIEEEInvalidOperation:\n\ [DecInvalidOperation, DecConversionSyntax, DecDivisionImpossible,\n\ DecDivisionUndefined, DecFpuError, DecInvalidContext, DecMallocError]"; #endif static int value_error_int(const char *mesg) { PyErr_SetString(PyExc_ValueError, mesg); return -1; } static PyObject * value_error_ptr(const char *mesg) { PyErr_SetString(PyExc_ValueError, mesg); return NULL; } static int type_error_int(const char *mesg) { PyErr_SetString(PyExc_TypeError, mesg); return -1; } static int runtime_error_int(const char *mesg) { PyErr_SetString(PyExc_RuntimeError, mesg); return -1; } #define INTERNAL_ERROR_INT(funcname) \ return runtime_error_int("internal error in " funcname) static PyObject * runtime_error_ptr(const char *mesg) { PyErr_SetString(PyExc_RuntimeError, mesg); return NULL; } #define INTERNAL_ERROR_PTR(funcname) \ return runtime_error_ptr("internal error in " funcname) static void dec_traphandler(mpd_context_t *Py_UNUSED(ctx)) /* GCOV_NOT_REACHED */ { /* GCOV_NOT_REACHED */ return; /* GCOV_NOT_REACHED */ } static PyObject * flags_as_exception(decimal_state *state, uint32_t flags) { DecCondMap *cm; for (cm = state->signal_map; cm->name != NULL; cm++) { if (flags&cm->flag) { return cm->ex; } } INTERNAL_ERROR_PTR("flags_as_exception"); /* GCOV_NOT_REACHED */ } Py_LOCAL_INLINE(uint32_t) exception_as_flag(decimal_state *state, PyObject *ex) { DecCondMap *cm; for (cm = state->signal_map; cm->name != NULL; cm++) { if (cm->ex == ex) { return cm->flag; } } PyErr_SetString(PyExc_KeyError, invalid_signals_err); return DEC_INVALID_SIGNALS; } static PyObject * flags_as_list(decimal_state *state, uint32_t flags) { PyObject *list; DecCondMap *cm; list = PyList_New(0); if (list == NULL) { return NULL; } for (cm = state->cond_map; cm->name != NULL; cm++) { if (flags&cm->flag) { if (PyList_Append(list, cm->ex) < 0) { goto error; } } } for (cm = state->signal_map+1; cm->name != NULL; cm++) { if (flags&cm->flag) { if (PyList_Append(list, cm->ex) < 0) { goto error; } } } return list; error: Py_DECREF(list); return NULL; } static PyObject * signals_as_list(decimal_state *state, uint32_t flags) { PyObject *list; DecCondMap *cm; list = PyList_New(0); if (list == NULL) { return NULL; } for (cm = state->signal_map; cm->name != NULL; cm++) { if (flags&cm->flag) { if (PyList_Append(list, cm->ex) < 0) { Py_DECREF(list); return NULL; } } } return list; } static uint32_t list_as_flags(decimal_state *state, PyObject *list) { PyObject *item; uint32_t flags, x; Py_ssize_t n, j; assert(PyList_Check(list)); n = PyList_Size(list); flags = 0; for (j = 0; j < n; j++) { item = PyList_GetItem(list, j); x = exception_as_flag(state, item); if (x & DEC_ERRORS) { return x; } flags |= x; } return flags; } static PyObject * flags_as_dict(decimal_state *state, uint32_t flags) { DecCondMap *cm; PyObject *dict; dict = PyDict_New(); if (dict == NULL) { return NULL; } for (cm = state->signal_map; cm->name != NULL; cm++) { PyObject *b = flags&cm->flag ? Py_True : Py_False; if (PyDict_SetItem(dict, cm->ex, b) < 0) { Py_DECREF(dict); return NULL; } } return dict; } static uint32_t dict_as_flags(decimal_state *state, PyObject *val) { PyObject *b; DecCondMap *cm; uint32_t flags = 0; int x; if (!PyAnyDict_Check(val)) { PyErr_SetString(PyExc_TypeError, "argument must be a signal dict"); return DEC_INVALID_SIGNALS; } if (PyDict_Size(val) != SIGNAL_MAP_LEN) { PyErr_SetString(PyExc_KeyError, "invalid signal dict"); return DEC_INVALID_SIGNALS; } for (cm = state->signal_map; cm->name != NULL; cm++) { b = PyDict_GetItemWithError(val, cm->ex); if (b == NULL) { if (PyErr_Occurred()) { return DEC_ERR_OCCURRED; } PyErr_SetString(PyExc_KeyError, "invalid signal dict"); return DEC_INVALID_SIGNALS; } x = PyObject_IsTrue(b); if (x < 0) { return DEC_ERR_OCCURRED; } if (x == 1) { flags |= cm->flag; } } return flags; } #ifdef EXTRA_FUNCTIONALITY static uint32_t long_as_flags(PyObject *v) { long x; x = PyLong_AsLong(v); if (x == -1 && PyErr_Occurred()) { return DEC_ERR_OCCURRED; } if (x < 0 || x > (long)MPD_Max_status) { PyErr_SetString(PyExc_TypeError, invalid_flags_err); return DEC_INVALID_SIGNALS; } return x; } #endif static int dec_addstatus(PyObject *context, uint32_t status) { mpd_context_t *ctx = CTX(context); decimal_state *state = get_module_state_from_ctx(context); ctx->status |= status; if (status & (ctx->traps|MPD_Malloc_error)) { PyObject *ex, *siglist; if (status & MPD_Malloc_error) { PyErr_NoMemory(); return 1; } ex = flags_as_exception(state, ctx->traps&status); if (ex == NULL) { return 1; /* GCOV_NOT_REACHED */ } siglist = flags_as_list(state, ctx->traps&status); if (siglist == NULL) { return 1; } PyErr_SetObject(ex, siglist); Py_DECREF(siglist); return 1; } return 0; } static int getround(decimal_state *state, PyObject *v) { int i; if (PyUnicode_Check(v)) { for (i = 0; i < _PY_DEC_ROUND_GUARD; i++) { if (v == state->round_map[i]) { return i; } } for (i = 0; i < _PY_DEC_ROUND_GUARD; i++) { if (PyUnicode_Compare(v, state->round_map[i]) == 0) { return i; } } } return type_error_int(invalid_rounding_err); } /******************************************************************************/ /* SignalDict Object */ /******************************************************************************/ /* The SignalDict is a MutableMapping that provides access to the mpd_context_t flags, which reside in the context object. When a new context is created, context.traps and context.flags are initialized to new SignalDicts. Once a SignalDict is tied to a context, it cannot be deleted. */ static const char *INVALID_SIGNALDICT_ERROR_MSG = "invalid signal dict"; static int signaldict_init(PyObject *self, PyObject *Py_UNUSED(args), PyObject *Py_UNUSED(kwds)) { SdFlagAddr(self) = NULL; return 0; } static Py_ssize_t signaldict_len(PyObject *self) { if (SdFlagAddr(self) == NULL) { return value_error_int(INVALID_SIGNALDICT_ERROR_MSG); } return SIGNAL_MAP_LEN; } static PyObject * signaldict_iter(PyObject *self) { if (SdFlagAddr(self) == NULL) { return value_error_ptr(INVALID_SIGNALDICT_ERROR_MSG); } decimal_state *state = get_module_state_by_def(Py_TYPE(self)); return PyTuple_Type.tp_iter(state->SignalTuple); } static PyObject * signaldict_getitem(PyObject *self, PyObject *key) { uint32_t flag; if (SdFlagAddr(self) == NULL) { return value_error_ptr(INVALID_SIGNALDICT_ERROR_MSG); } decimal_state *state = get_module_state_by_def(Py_TYPE(self)); flag = exception_as_flag(state, key); if (flag & DEC_ERRORS) { return NULL; } return SdFlags(self)&flag ? incr_true() : incr_false(); } static int signaldict_setitem(PyObject *self, PyObject *key, PyObject *value) { uint32_t flag; int x; if (SdFlagAddr(self) == NULL) { return value_error_int(INVALID_SIGNALDICT_ERROR_MSG); } if (value == NULL) { return value_error_int("signal keys cannot be deleted"); } decimal_state *state = get_module_state_by_def(Py_TYPE(self)); flag = exception_as_flag(state, key); if (flag & DEC_ERRORS) { return -1; } x = PyObject_IsTrue(value); if (x < 0) { return -1; } if (x == 1) { SdFlags(self) |= flag; } else { SdFlags(self) &= ~flag; } return 0; } static void signaldict_dealloc(PyObject *self) { PyTypeObject *tp = Py_TYPE(self); PyObject_GC_UnTrack(self); tp->tp_free(self); Py_DECREF(tp); } static PyObject * signaldict_repr(PyObject *self) { DecCondMap *cm; const char *n[SIGNAL_MAP_LEN]; /* name */ const char *b[SIGNAL_MAP_LEN]; /* bool */ int i; if (SdFlagAddr(self) == NULL) { return value_error_ptr(INVALID_SIGNALDICT_ERROR_MSG); } assert(SIGNAL_MAP_LEN == 9); decimal_state *state = get_module_state_by_def(Py_TYPE(self)); for (cm=state->signal_map, i=0; cm->name != NULL; cm++, i++) { n[i] = cm->fqname; b[i] = SdFlags(self)&cm->flag ? "True" : "False"; } return PyUnicode_FromFormat( "{<class '%s'>:%s, <class '%s'>:%s, <class '%s'>:%s, " "<class '%s'>:%s, <class '%s'>:%s, <class '%s'>:%s, " "<class '%s'>:%s, <class '%s'>:%s, <class '%s'>:%s}", n[0], b[0], n[1], b[1], n[2], b[2], n[3], b[3], n[4], b[4], n[5], b[5], n[6], b[6], n[7], b[7], n[8], b[8]); } static PyObject * signaldict_richcompare(PyObject *v, PyObject *w, int op) { PyObject *res = Py_NotImplemented; decimal_state *state = get_module_state_by_def(Py_TYPE(v)); assert(PyDecSignalDict_Check(state, v)); if ((SdFlagAddr(v) == NULL) || (SdFlagAddr(w) == NULL)) { return value_error_ptr(INVALID_SIGNALDICT_ERROR_MSG); } if (op == Py_EQ || op == Py_NE) { if (PyDecSignalDict_Check(state, w)) { res = (SdFlags(v)==SdFlags(w)) ^ (op==Py_NE) ? Py_True : Py_False; } else if (PyAnyDict_Check(w)) { uint32_t flags = dict_as_flags(state, w); if (flags & DEC_ERRORS) { if (flags & DEC_INVALID_SIGNALS) { /* non-comparable: Py_NotImplemented */ PyErr_Clear(); } else { return NULL; } } else { res = (SdFlags(v)==flags) ^ (op==Py_NE) ? Py_True : Py_False; } } } return Py_NewRef(res); } static PyObject * signaldict_copy(PyObject *self, PyObject *Py_UNUSED(dummy)) { if (SdFlagAddr(self) == NULL) { return value_error_ptr(INVALID_SIGNALDICT_ERROR_MSG); } decimal_state *state = get_module_state_by_def(Py_TYPE(self)); return flags_as_dict(state, SdFlags(self)); } static PyMethodDef signaldict_methods[] = { { "copy", signaldict_copy, METH_NOARGS, NULL}, {NULL, NULL} }; static PyType_Slot signaldict_slots[] = { {Py_tp_dealloc, signaldict_dealloc}, {Py_tp_traverse, _PyObject_VisitType}, {Py_tp_repr, signaldict_repr}, {Py_tp_hash, PyObject_HashNotImplemented}, {Py_tp_getattro, PyObject_GenericGetAttr}, {Py_tp_richcompare, signaldict_richcompare}, {Py_tp_iter, signaldict_iter}, {Py_tp_methods, signaldict_methods}, {Py_tp_init, signaldict_init}, // Mapping protocol {Py_mp_length, signaldict_len}, {Py_mp_subscript, signaldict_getitem}, {Py_mp_ass_subscript, signaldict_setitem}, {0, NULL}, }; static PyType_Spec signaldict_spec = { .name = "decimal.SignalDictMixin", .basicsize = sizeof(PyDecSignalDictObject), .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE), .slots = signaldict_slots, }; /******************************************************************************/ /* Context Object, Part 1 */ /******************************************************************************/ #define Dec_CONTEXT_GET_SSIZE(mem) \ static PyObject * \ context_get##mem(PyObject *self, void *Py_UNUSED(closure)) \ { \ return PyLong_FromSsize_t(mpd_get##mem(CTX(self))); \ } #define Dec_CONTEXT_GET_ULONG(mem) \ static PyObject * \ context_get##mem(PyObject *self, void *Py_UNUSED(closure)) \ { \ return PyLong_FromUnsignedLong(mpd_get##mem(CTX(self))); \ } Dec_CONTEXT_GET_SSIZE(prec) Dec_CONTEXT_GET_SSIZE(emax) Dec_CONTEXT_GET_SSIZE(emin) Dec_CONTEXT_GET_SSIZE(clamp) #ifdef EXTRA_FUNCTIONALITY Dec_CONTEXT_GET_ULONG(traps) Dec_CONTEXT_GET_ULONG(status) #endif static PyObject * context_getround(PyObject *self, void *Py_UNUSED(closure)) { int i = mpd_getround(CTX(self)); decimal_state *state = get_module_state_from_ctx(self); return Py_NewRef(state->round_map[i]); } static PyObject * context_getcapitals(PyObject *self, void *Py_UNUSED(closure)) { return PyLong_FromLong(CtxCaps(self)); } #ifdef EXTRA_FUNCTIONALITY static PyObject * context_getallcr(PyObject *self, void *Py_UNUSED(closure)) { return PyLong_FromLong(mpd_getcr(CTX(self))); } #endif /*[clinic input] _decimal.Context.Etiny Return a value equal to Emin - prec + 1. This is the minimum exponent value for subnormal results. When underflow occurs, the exponent is set to Etiny. [clinic start generated code]*/ static PyObject * _decimal_Context_Etiny_impl(PyObject *self) /*[clinic end generated code: output=c9a4a1a3e3575289 input=1274040f303f2244]*/ { return PyLong_FromSsize_t(mpd_etiny(CTX(self))); } /*[clinic input] _decimal.Context.Etop Return a value equal to Emax - prec + 1. This is the maximum exponent if the _clamp field of the context is set to 1 (IEEE clamp mode). Etop() must not be negative. [clinic start generated code]*/ static PyObject * _decimal_Context_Etop_impl(PyObject *self) /*[clinic end generated code: output=f0a3f6e1b829074e input=838a4409316ec728]*/ { return PyLong_FromSsize_t(mpd_etop(CTX(self))); } static int context_setprec(PyObject *self, PyObject *value, void *Py_UNUSED(closure)) { mpd_context_t *ctx; mpd_ssize_t x; x = PyLong_AsSsize_t(value); if (x == -1 && PyErr_Occurred()) { return -1; } ctx = CTX(self); if (!mpd_qsetprec(ctx, x)) { return value_error_int( "valid range for prec is [1, MAX_PREC]"); } return 0; } static int context_setemin(PyObject *self, PyObject *value, void *Py_UNUSED(closure)) { mpd_context_t *ctx; mpd_ssize_t x; x = PyLong_AsSsize_t(value); if (x == -1 && PyErr_Occurred()) { return -1; } ctx = CTX(self); if (!mpd_qsetemin(ctx, x)) { return value_error_int( "valid range for Emin is [MIN_EMIN, 0]"); } return 0; } static int context_setemax(PyObject *self, PyObject *value, void *Py_UNUSED(closure)) { mpd_context_t *ctx; mpd_ssize_t x; x = PyLong_AsSsize_t(value); if (x == -1 && PyErr_Occurred()) { |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |