[Python-checkins] r77342 - in python/branches/py3k-cdecimal/Modules/cdecimal: basearith.c basearith.h bench.c bits.h cdecimal.c constants.c constants.h context.c convolute.c convolute.h crt.c crt.h difradix2.c difradix2.h docstrings.h error.c fnt.c fnt.h fourstep.c fourstep.h io.c memory.c memory.h mpdecimal.c mpdecimal.h mpdecimal32.h mpdecimal64.h mptypes.h numbertheory.c numbertheory.h sixstep.c sixstep.h transpose.c transpose.h transpose3.c typearith.h umodarith.h vccompat.h vcdiv64.asm vcstdint.h
stefan.krah
python-checkins at python.org
Thu Jan 7 13:02:53 CET 2010
Author: stefan.krah
Date: Thu Jan 7 13:02:51 2010
New Revision: 77342
Log:
Initial import of Modules/cdecimal
Added:
python/branches/py3k-cdecimal/Modules/cdecimal/
python/branches/py3k-cdecimal/Modules/cdecimal/basearith.c (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/basearith.h (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/bench.c (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/bits.h (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/cdecimal.c (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/constants.c (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/constants.h (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/context.c (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/convolute.c (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/convolute.h (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/crt.c (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/crt.h (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/difradix2.c (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/difradix2.h (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/docstrings.h (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/error.c (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/fnt.c (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/fnt.h (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/fourstep.c (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/fourstep.h (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/io.c (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/memory.c (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/memory.h (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/mpdecimal.c (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/mpdecimal.h (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/mpdecimal32.h (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/mpdecimal64.h (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/mptypes.h (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/numbertheory.c (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/numbertheory.h (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/sixstep.c (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/sixstep.h (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/transpose.c (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/transpose.h (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/transpose3.c (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/typearith.h (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/umodarith.h (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/vccompat.h (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/vcdiv64.asm (contents, props changed)
python/branches/py3k-cdecimal/Modules/cdecimal/vcstdint.h (contents, props changed)
Added: python/branches/py3k-cdecimal/Modules/cdecimal/basearith.c
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/basearith.c Thu Jan 7 13:02:51 2010
@@ -0,0 +1,553 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+#include "constants.h"
+#include "memory.h"
+#include "mpdecimal.h"
+#include "typearith.h"
+#include "basearith.h"
+
+
+/*********************************************************************/
+/* Calculations in base MPD_RADIX */
+/*********************************************************************/
+
+
+/*
+ * Knuth, TAOCP, Volume 2, 4.3.1:
+ * w := sum of u (len m) and v (len n)
+ * n > 0 and m >= n
+ * The calling function has to handle a possible final carry.
+ */
+mpd_uint_t
+_mpd_baseadd(mpd_uint_t *w, const mpd_uint_t *u, const mpd_uint_t *v,
+ size_t m, size_t n)
+{
+ mpd_uint_t s;
+ mpd_uint_t carry = 0;
+ size_t i;
+
+ assert(n > 0 && m >= n);
+
+ /* add n members of u and v */
+ for (i = 0; i < n; i++) {
+ s = u[i] + (v[i] + carry);
+ carry = (s < u[i]) | (s >= MPD_RADIX);
+ w[i] = carry ? s-MPD_RADIX : s;
+ }
+ /* if there is a carry, propagate it */
+ for (; carry && i < m; i++) {
+ s = u[i] + carry;
+ carry = (s == MPD_RADIX);
+ w[i] = carry ? 0 : s;
+ }
+ /* copy the rest of u */
+ for (; i < m; i++) {
+ w[i] = u[i];
+ }
+
+ return carry;
+}
+
+/*
+ * Add the contents of u to w. Carries are propagated further. The caller
+ * has to make sure that w is big enough.
+ */
+void
+_mpd_baseaddto(mpd_uint_t *w, const mpd_uint_t *u, size_t n)
+{
+ mpd_uint_t s;
+ mpd_uint_t carry = 0;
+ size_t i;
+
+ if (n == 0) return;
+
+ /* add n members of u to w */
+ for (i = 0; i < n; i++) {
+ s = w[i] + (u[i] + carry);
+ carry = (s < w[i]) | (s >= MPD_RADIX);
+ w[i] = carry ? s-MPD_RADIX : s;
+ }
+ /* if there is a carry, propagate it */
+ for (; carry; i++) {
+ s = w[i] + carry;
+ carry = (s == MPD_RADIX);
+ w[i] = carry ? 0 : s;
+ }
+}
+
+/*
+ * Add v to w (len m). The calling function has to handle a possible
+ * final carry.
+ */
+mpd_uint_t
+_mpd_shortadd(mpd_uint_t *w, size_t m, mpd_uint_t v)
+{
+ mpd_uint_t s;
+ mpd_uint_t carry = 0;
+ size_t i;
+
+ /* add v to u */
+ s = w[0] + v;
+ carry = (s < v) | (s >= MPD_RADIX);
+ w[0] = carry ? s-MPD_RADIX : s;
+
+ /* if there is a carry, propagate it */
+ for (i = 1; carry && i < m; i++) {
+ s = w[i] + carry;
+ carry = (s == MPD_RADIX);
+ w[i] = carry ? 0 : s;
+ }
+
+ return carry;
+}
+
+/* Increment u. The calling function has to handle a possible carry. */
+mpd_uint_t
+_mpd_baseincr(mpd_uint_t *u, size_t n)
+{
+ mpd_uint_t s;
+ mpd_uint_t carry = 1;
+ size_t i;
+
+ assert(n > 0);
+
+ /* if there is a carry, propagate it */
+ for (i = 0; carry && i < n; i++) {
+ s = u[i] + carry;
+ carry = (s == MPD_RADIX);
+ u[i] = carry ? 0 : s;
+ }
+
+ return carry;
+}
+
+/*
+ * Knuth, TAOCP, Volume 2, 4.3.1:
+ * w := difference of u (len m) and v (len n).
+ * number in u >= number in v;
+ */
+void
+_mpd_basesub(mpd_uint_t *w, const mpd_uint_t *u, const mpd_uint_t *v, size_t m, size_t n)
+{
+ mpd_uint_t d;
+ mpd_uint_t borrow = 0;
+ size_t i;
+
+ assert(m > 0 && n > 0);
+
+ /* subtract n members of v from u */
+ for (i = 0; i < n; i++) {
+ d = u[i] - (v[i] + borrow);
+ borrow = (u[i] < d);
+ w[i] = borrow ? d + MPD_RADIX : d;
+ }
+ /* if there is a borrow, propagate it */
+ for (; borrow && i < m; i++) {
+ d = u[i] - borrow;
+ borrow = (u[i] == 0);
+ w[i] = borrow ? MPD_RADIX-1 : d;
+ }
+ /* copy the rest of u */
+ for (; i < m; i++) {
+ w[i] = u[i];
+ }
+}
+
+/*
+ * Subtract the contents of u from w. w is larger than u. Borrows are propagated
+ * further, but eventually w can absorb the final borrow.
+ */
+void
+_mpd_basesubfrom(mpd_uint_t *w, const mpd_uint_t *u, size_t n)
+{
+ mpd_uint_t d;
+ mpd_uint_t borrow = 0;
+ size_t i;
+
+ if (n == 0) return;
+
+ /* subtract n members of u from w */
+ for (i = 0; i < n; i++) {
+ d = w[i] - (u[i] + borrow);
+ borrow = (w[i] < d);
+ w[i] = borrow ? d + MPD_RADIX : d;
+ }
+ /* if there is a borrow, propagate it */
+ for (; borrow; i++) {
+ d = w[i] - borrow;
+ borrow = (w[i] == 0);
+ w[i] = borrow ? MPD_RADIX-1 : d;
+ }
+}
+
+/* w := product of u (len n) and v (single word) */
+void
+_mpd_shortmul(mpd_uint_t *w, const mpd_uint_t *u, size_t n, mpd_uint_t v)
+{
+ mpd_uint_t hi, lo;
+ mpd_uint_t carry = 0;
+ size_t i;
+
+ assert(n > 0);
+
+ for (i=0; i < n; i++) {
+
+ _mpd_mul_words(&hi, &lo, u[i], v);
+ lo = carry + lo;
+ if (lo < carry) hi++;
+
+ _mpd_div_words_r(&carry, &w[i], hi, lo);
+ }
+ w[i] = carry;
+}
+
+/*
+ * Knuth, TAOCP, Volume 2, 4.3.1:
+ * w := product of u (len m) and v (len n)
+ * w must be initialized to zero
+ */
+void
+_mpd_basemul(mpd_uint_t *w, const mpd_uint_t *u, const mpd_uint_t *v, size_t m, size_t n)
+{
+ mpd_uint_t hi, lo;
+ mpd_uint_t carry;
+ size_t i, j;
+
+ assert(m > 0 && n > 0);
+
+ for (j=0; j < n; j++) {
+ carry = 0;
+ for (i=0; i < m; i++) {
+
+ _mpd_mul_words(&hi, &lo, u[i], v[j]);
+ lo = w[i+j] + lo;
+ if (lo < w[i+j]) hi++;
+ lo = carry + lo;
+ if (lo < carry) hi++;
+
+ _mpd_div_words_r(&carry, &w[i+j], hi, lo);
+ }
+ w[j+m] = carry;
+ }
+}
+
+/*
+ * Knuth, TAOCP Volume 2, 4.3.1, exercise 16:
+ * w := quotient of u (len n) divided by a single word v
+ */
+mpd_uint_t
+_mpd_shortdiv(mpd_uint_t *w, const mpd_uint_t *u, size_t n, mpd_uint_t v)
+{
+ mpd_uint_t hi, lo;
+ mpd_uint_t rem = 0;
+ size_t i;
+
+ assert(n > 0);
+
+ for (i=n-1; i != SIZE_MAX; i--) {
+
+ _mpd_mul_words(&hi, &lo, rem, MPD_RADIX);
+ lo = u[i] + lo;
+ if (lo < u[i]) hi++;
+
+ _mpd_div_words(&w[i], &rem, hi, lo, v);
+ }
+
+ return rem;
+}
+
+/*
+ * Knuth, TAOCP Volume 2, 4.3.1:
+ * q, r := quotient and remainder of uconst (len nplusm)
+ * divided by vconst (len n)
+ * nplusm > n
+ *
+ * If r is not NULL, r will contain the remainder. If r is NULL, the
+ * return value indicates if there is a remainder: 1 for true, 0 for
+ * false. A return value of -1 indicates an error.
+ */
+int
+_mpd_basedivmod(mpd_uint_t *q, mpd_uint_t *r, const mpd_uint_t *uconst, const mpd_uint_t *vconst,
+ size_t nplusm, size_t n)
+{
+ mpd_uint_t ustatic[MPD_MINALLOC_MAX];
+ mpd_uint_t vstatic[MPD_MINALLOC_MAX];
+ mpd_uint_t *u = ustatic;
+ mpd_uint_t *v = vstatic;
+ mpd_uint_t d, qhat, rhat, w2[2];
+ mpd_uint_t hi, lo, x;
+ mpd_uint_t carry;
+ size_t i, j, m;
+ int retval = 0;
+
+ assert(n > 1 && nplusm >= n);
+ m = sub_size_t(nplusm, n);
+
+ /* D1: normalize */
+ d = MPD_RADIX / (vconst[n-1] + 1);
+
+ if (nplusm >= MPD_MINALLOC_MAX) {
+ if ((u = mpd_calloc(nplusm+1, sizeof *u)) == NULL) {
+ return -1;
+ }
+ }
+ if (n >= MPD_MINALLOC_MAX) {
+ if ((v = mpd_calloc(n+1, sizeof *v)) == NULL) {
+ mpd_free(u);
+ return -1;
+ }
+ }
+
+ _mpd_shortmul(u, uconst, nplusm, d);
+ _mpd_shortmul(v, vconst, n, d);
+
+ /* D2: loop */
+ rhat = 0;
+ for (j=m; j != SIZE_MAX; j--) {
+
+ /* D3: calculate qhat and rhat */
+ rhat = _mpd_shortdiv(w2, u+j+n-1, 2, v[n-1]);
+ qhat = w2[1] * MPD_RADIX + w2[0];
+
+ while (1) {
+ if (qhat < MPD_RADIX) {
+ _mpd_singlemul(w2, qhat, v[n-2]);
+ if (w2[1] <= rhat) {
+ if (w2[1] != rhat || w2[0] <= u[j+n-2]) {
+ break;
+ }
+ }
+ }
+ qhat -= 1;
+ rhat += v[n-1];
+ if (rhat < v[n-1] || rhat >= MPD_RADIX) {
+ break;
+ }
+ }
+ /* D4: multiply and subtract */
+ carry = 0;
+ for (i=0; i <= n; i++) {
+
+ _mpd_mul_words(&hi, &lo, qhat, v[i]);
+
+ lo = carry + lo;
+ if (lo < carry) hi++;
+
+ _mpd_div_words_r(&hi, &lo, hi, lo);
+
+ x = u[i+j] - lo;
+ carry = (u[i+j] < x);
+ u[i+j] = carry ? x+MPD_RADIX : x;
+ carry += hi;
+ }
+ q[j] = qhat;
+ /* D5: test remainder */
+ if (carry) {
+ q[j] -= 1;
+ /* D6: add back */
+ (void)_mpd_baseadd(u+j, u+j, v, n+1, n);
+ }
+ }
+
+ /* D8: unnormalize */
+ if (r != NULL) {
+ _mpd_shortdiv(r, u, n, d);
+ /* we are not interested in the return value here */
+ retval = 0;
+ }
+ else {
+ retval = !_mpd_isallzero(u, n);
+ }
+
+
+if (u != ustatic) mpd_free(u);
+if (v != vstatic) mpd_free(v);
+return retval;
+}
+
+/* Leftshift of src by shift digits; src may equal dest. */
+void
+_mpd_baseshiftl(mpd_uint_t *dest, mpd_uint_t *src, size_t n, size_t m, size_t shift)
+{
+#if defined(__GNUC__) && !defined(__INTEL_COMPILER)
+ /* spurious uninitialized warnings */
+ mpd_uint_t l=l, lprev=lprev, h=h;
+#else
+ mpd_uint_t l, lprev, h;
+#endif
+ mpd_uint_t q, r;
+ mpd_uint_t ph;
+
+ assert(m > 0 && n >= m);
+
+ _mpd_div_word(&q, &r, (mpd_uint_t)shift, MPD_RDIGITS);
+
+ if (r != 0) {
+
+ ph = mpd_pow10[r];
+
+ --m; --n;
+ _mpd_divmod_pow10(&h, &lprev, src[m--], MPD_RDIGITS-r);
+ if (h != 0) {
+ dest[n--] = h;
+ }
+ for (; m != SIZE_MAX; m--,n--) {
+ _mpd_divmod_pow10(&h, &l, src[m], MPD_RDIGITS-r);
+ dest[n] = ph * lprev + h;
+ lprev = l;
+ }
+ dest[q] = ph * lprev;
+ }
+ else {
+ while (--m != SIZE_MAX) {
+ dest[m+q] = src[m];
+ }
+ }
+
+ mpd_uint_zero(dest, q);
+}
+
+/* Rightshift of src by shift digits; src may equal dest. */
+mpd_uint_t
+_mpd_baseshiftr(mpd_uint_t *dest, mpd_uint_t *src, size_t slen, size_t shift)
+{
+#if defined(__GNUC__) && !defined(__INTEL_COMPILER)
+ /* spurious uninitialized warnings */
+ mpd_uint_t l=l, h=h, hprev=hprev; /* low, high, previous high */
+#else
+ mpd_uint_t l, h, hprev; /* low, high, previous high */
+#endif
+ mpd_uint_t rnd, rest; /* rounding digit, rest */
+ mpd_uint_t q, r;
+ size_t i, j;
+ mpd_uint_t ph;
+
+ assert(slen > 0);
+
+ _mpd_div_word(&q, &r, (mpd_uint_t)shift, MPD_RDIGITS);
+
+ rnd = rest = 0;
+ if (r != 0) {
+
+ ph = mpd_pow10[MPD_RDIGITS-r];
+
+ _mpd_divmod_pow10(&hprev, &rest, src[q], r);
+ _mpd_divmod_pow10(&rnd, &rest, rest, r-1);
+
+ if (rest == 0 && q > 0) {
+ rest = !_mpd_isallzero(src, q);
+ }
+ h = hprev;
+ for (j=0,i=q+1; i<slen; i++,j++) {
+ _mpd_divmod_pow10(&h, &l, src[i], r);
+ dest[j] = ph * l + hprev;
+ hprev = h;
+ }
+ if (hprev != 0) {
+ dest[j] = hprev;
+ }
+ }
+ else {
+ if (q > 0) {
+ _mpd_divmod_pow10(&rnd, &rest, src[q-1], MPD_RDIGITS-1);
+ /* is there any non-zero digit below rnd? */
+ if (rest == 0) rest = !_mpd_isallzero(src, q-1);
+ }
+ for (j = 0; j < slen-q; j++) {
+ dest[j] = src[q+j];
+ }
+ }
+
+ /* 0-4 ==> rnd+rest < 0.5 */
+ /* 5 ==> rnd+rest == 0.5 */
+ /* 6-9 ==> rnd+rest > 0.5 */
+ return (rnd == 0 || rnd == 5) ? rnd + !!rest : rnd;
+}
+
+
+/*********************************************************************/
+/* Calculations in base b */
+/*********************************************************************/
+
+/*
+ * Add v to w (len m). The calling function has to handle a possible
+ * final carry.
+ */
+mpd_uint_t
+_mpd_shortadd_b(mpd_uint_t *w, size_t m, mpd_uint_t v, mpd_uint_t b)
+{
+ mpd_uint_t s;
+ mpd_uint_t carry = 0;
+ size_t i;
+
+ /* add v to u */
+ s = w[0] + v;
+ carry = (s < v) | (s >= b);
+ w[0] = carry ? s-b : s;
+
+ /* if there is a carry, propagate it */
+ for (i = 1; carry && i < m; i++) {
+ s = w[i] + carry;
+ carry = (s == b);
+ w[i] = carry ? 0 : s;
+ }
+
+ return carry;
+}
+
+/* w := product of u (len n) and v (single word) */
+void
+_mpd_shortmul_b(mpd_uint_t *w, const mpd_uint_t *u, size_t n, mpd_uint_t v, mpd_uint_t b)
+{
+ mpd_uint_t hi, lo;
+ mpd_uint_t carry = 0;
+ size_t i;
+
+ assert(n > 0);
+
+ for (i=0; i < n; i++) {
+
+ _mpd_mul_words(&hi, &lo, u[i], v);
+ lo = carry + lo;
+ if (lo < carry) hi++;
+
+ _mpd_div_words(&carry, &w[i], hi, lo, b);
+ }
+ w[i] = carry;
+}
+
+/*
+ * Knuth, TAOCP Volume 2, 4.3.1, exercise 16:
+ * w := quotient of u (len n) divided by a single word v
+ */
+mpd_uint_t
+_mpd_shortdiv_b(mpd_uint_t *w, const mpd_uint_t *u, size_t n, mpd_uint_t v, mpd_uint_t b)
+{
+ mpd_uint_t hi, lo;
+ mpd_uint_t rem = 0;
+ size_t i;
+
+ assert(n > 0);
+
+ for (i=n-1; i != SIZE_MAX; i--) {
+
+ _mpd_mul_words(&hi, &lo, rem, b);
+ lo = u[i] + lo;
+ if (lo < u[i]) hi++;
+
+ _mpd_div_words(&w[i], &rem, hi, lo, v);
+ }
+
+ return rem;
+}
+
+
+
Added: python/branches/py3k-cdecimal/Modules/cdecimal/basearith.h
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/basearith.h Thu Jan 7 13:02:51 2010
@@ -0,0 +1,147 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#ifndef BASEARITH_H
+#define BASEARITH_H
+
+
+#include <stdio.h>
+#include "mpdecimal.h"
+#include "typearith.h"
+
+
+mpd_uint_t _mpd_baseadd(mpd_uint_t *w, const mpd_uint_t *u, const mpd_uint_t *v, size_t m, size_t n);
+void _mpd_baseaddto(mpd_uint_t *w, const mpd_uint_t *u, size_t n);
+mpd_uint_t _mpd_shortadd(mpd_uint_t *w, size_t m, mpd_uint_t v);
+mpd_uint_t _mpd_shortadd_b(mpd_uint_t *w, size_t m, mpd_uint_t v, mpd_uint_t b);
+mpd_uint_t _mpd_baseincr(mpd_uint_t *u, size_t n);
+void _mpd_basesub(mpd_uint_t *w, const mpd_uint_t *u, const mpd_uint_t *v, size_t m, size_t n);
+void _mpd_basesubfrom(mpd_uint_t *w, const mpd_uint_t *u, size_t n);
+void _mpd_basemul(mpd_uint_t *w, const mpd_uint_t *u, const mpd_uint_t *v, size_t m, size_t n);
+void _mpd_shortmul(mpd_uint_t *w, const mpd_uint_t *u, size_t n, mpd_uint_t v);
+void _mpd_shortmul_b(mpd_uint_t *w, const mpd_uint_t *u, size_t n, mpd_uint_t v, mpd_uint_t b);
+mpd_uint_t _mpd_shortdiv(mpd_uint_t *w, const mpd_uint_t *u, size_t n, mpd_uint_t v);
+mpd_uint_t _mpd_shortdiv_b(mpd_uint_t *w, const mpd_uint_t *u, size_t n, mpd_uint_t v, mpd_uint_t b);
+int _mpd_basedivmod(mpd_uint_t *q, mpd_uint_t *r, const mpd_uint_t *uconst, const mpd_uint_t *vconst, size_t nplusm, size_t n);
+void _mpd_baseshiftl(mpd_uint_t *dest, mpd_uint_t *src, size_t n, size_t m, size_t shift);
+mpd_uint_t _mpd_baseshiftr(mpd_uint_t *dest, mpd_uint_t *src, size_t slen, size_t shift);
+
+
+
+#ifdef CONFIG_64
+extern const mpd_uint_t mprime_rdx;
+
+/*
+ * Algorithm from: Division by Invariant Integers using Multiplication,
+ * T. Granlund and P. L. Montgomery, Proceedings of the SIGPLAN '94
+ * Conference on Programming Language Design and Implementation.
+ *
+ * http://gmplib.org/~tege/divcnst-pldi94.pdf
+ */
+static inline void
+_mpd_div_words_r(mpd_uint_t *q, mpd_uint_t *r, mpd_uint_t hi, mpd_uint_t lo)
+{
+ mpd_uint_t n_adj, h, l, t;
+ mpd_uint_t n1_neg;
+
+ n1_neg = (lo & (1ULL<<63)) ? MPD_UINT_MAX : 0;
+ n_adj = lo + (n1_neg & MPD_RADIX);
+
+ _mpd_mul_words(&h, &l, mprime_rdx, hi-n1_neg);
+ l = l + n_adj;
+ if (l < n_adj) h++;
+ t = h + hi; /* q1 */
+
+ t = MPD_UINT_MAX - t;
+
+ _mpd_mul_words(&h, &l, t, MPD_RADIX);
+ l = l + lo;
+ if (l < lo) h++;
+ h += hi;
+ h -= MPD_RADIX;
+
+ *q = (h - t);
+ *r = l + (MPD_RADIX & h);
+}
+#else
+static inline void
+_mpd_div_words_r(mpd_uint_t *q, mpd_uint_t *r, mpd_uint_t hi, mpd_uint_t lo)
+{
+ _mpd_div_words(q, r, hi, lo, MPD_RADIX);
+}
+#endif
+
+
+/* Multiply two single base b words, store result in array w[2]. */
+static inline void
+_mpd_singlemul(mpd_uint_t w[2], mpd_uint_t u, mpd_uint_t v)
+{
+ mpd_uint_t hi, lo;
+
+ _mpd_mul_words(&hi, &lo, u, v);
+ _mpd_div_words_r(&w[1], &w[0], hi, lo);
+}
+
+/* Multiply u (len 2) and v (len 1 or 2). */
+static inline void
+_mpd_mul_2_le2(mpd_uint_t w[4], mpd_uint_t u[2], mpd_uint_t v[2], mpd_ssize_t m)
+{
+ mpd_uint_t hi, lo;
+
+ _mpd_mul_words(&hi, &lo, u[0], v[0]);
+ _mpd_div_words_r(&w[1], &w[0], hi, lo);
+
+ _mpd_mul_words(&hi, &lo, u[1], v[0]);
+ lo = w[1] + lo;
+ if (lo < w[1]) hi++;
+ _mpd_div_words_r(&w[2], &w[1], hi, lo);
+ if (m == 1) return;
+
+ _mpd_mul_words(&hi, &lo, u[0], v[1]);
+ lo = w[1] + lo;
+ if (lo < w[1]) hi++;
+ _mpd_div_words_r(&w[3], &w[1], hi, lo);
+
+ _mpd_mul_words(&hi, &lo, u[1], v[1]);
+ lo = w[2] + lo;
+ if (lo < w[2]) hi++;
+ lo = w[3] + lo;
+ if (lo < w[3]) hi++;
+ _mpd_div_words_r(&w[3], &w[2], hi, lo);
+}
+
+
+/*
+ * Test if all words from data[len-1] to data[0] are zero. If len is 0, nothing
+ * is tested and the coefficient is regarded as "all zero".
+ */
+static inline int
+_mpd_isallzero(const mpd_uint_t *data, mpd_ssize_t len)
+{
+ while (--len >= 0) {
+ if (data[len] != 0) return 0;
+ }
+ return 1;
+}
+
+/*
+ * Test if all words from data[len-1] to data[0] are MPD_RADIX-1 (all nines).
+ * Assumes that len > 0.
+ */
+static inline int
+_mpd_isallnine(const mpd_uint_t *data, mpd_ssize_t len)
+{
+ while (--len >= 0) {
+ if (data[len] != MPD_RADIX-1) return 0;
+ }
+ return 1;
+}
+
+
+#endif /* BASEARITH_H */
+
+
+
Added: python/branches/py3k-cdecimal/Modules/cdecimal/bench.c
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/bench.c Thu Jan 7 13:02:51 2010
@@ -0,0 +1,152 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#include <stdio.h>
+#include <time.h>
+#include "mpdecimal.h"
+
+
+/*
+ * Example from: http://en.wikipedia.org/wiki/Mandelbrot_set
+ *
+ * Escape time algorithm for drawing the set:
+ *
+ * Point x0, y0 is deemed to be in the Mandelbrot set if the return
+ * value is maxiter. Lower return values indicate how quickly points
+ * escaped and can be used for coloring.
+ */
+int
+color_point(mpd_t *x0, mpd_t *y0, int maxiter, mpd_context_t *ctx)
+{
+ mpd_t *x, *y, *sq_x, *sq_y;
+ mpd_t *two, *four, *c;
+ int i;
+
+ x = mpd_new(ctx);
+ y = mpd_new(ctx);
+ mpd_set_u32(x, 0, ctx);
+ mpd_set_u32(y, 0, ctx);
+
+ sq_x = mpd_new(ctx);
+ sq_y = mpd_new(ctx);
+ mpd_set_u32(sq_x, 0, ctx);
+ mpd_set_u32(sq_y, 0, ctx);
+
+ two = mpd_new(ctx);
+ four = mpd_new(ctx);
+ mpd_set_u32(two, 2, ctx);
+ mpd_set_u32(four, 4, ctx);
+
+ c = mpd_new(ctx);
+ mpd_set_u32(c, 0, ctx);
+
+ for (i = 0; i < maxiter && mpd_cmp(c, four, ctx) <= 0; i++) {
+
+ mpd_mul(y, x, y, ctx);
+ mpd_mul(y, y, two, ctx);
+ mpd_add(y, y, y0, ctx);
+
+ mpd_sub(x, sq_x, sq_y, ctx);
+ mpd_add(x, x, x0, ctx);
+
+ mpd_mul(sq_x, x, x, ctx);
+ mpd_mul(sq_y, y, y, ctx);
+ mpd_add(c, sq_x, sq_y, ctx);
+ }
+
+ mpd_del(x);
+ mpd_del(y);
+ mpd_del(sq_x);
+ mpd_del(sq_y);
+ mpd_del(two);
+ mpd_del(four);
+ mpd_del(c);
+
+ return i;
+}
+
+int
+main(int argc, char **argv)
+{
+ mpd_context_t ctx;
+ mpd_t *x0, *y0;
+ mpd_t *sqrt_2, *xstep, *ystep;
+ uint32_t prec = 19;
+
+ int iter = 1000;
+ int points[40][80];
+ int i, j;
+ clock_t start_clock, end_clock;
+
+
+ if (argc != 3) {
+ fprintf(stderr, "usage: ./bench prec iter\n");
+ exit(1);
+ }
+ prec = strtoul(argv[1], NULL, 10);
+ iter = strtol(argv[2], NULL, 10);
+
+ mpd_init(&ctx, prec);
+ /* no more MPD_MINALLOC changes after here */
+
+ sqrt_2 = mpd_new(&ctx);
+ xstep = mpd_new(&ctx);
+ ystep = mpd_new(&ctx);
+ x0 = mpd_new(&ctx);
+ y0 = mpd_new(&ctx);
+
+ mpd_set_u32(sqrt_2, 2, &ctx);
+ mpd_sqrt(sqrt_2, sqrt_2, &ctx);
+ mpd_div_u32(xstep, sqrt_2, 40, &ctx);
+ mpd_div_u32(ystep, sqrt_2, 20, &ctx);
+
+ start_clock = clock();
+ mpd_copy(y0, sqrt_2, &ctx);
+ for (i = 0; i < 40; i++) {
+ mpd_copy(x0, sqrt_2, &ctx);
+ mpd_set_negative(x0);
+ for (j = 0; j < 80; j++) {
+ points[i][j] = color_point(x0, y0, iter, &ctx);
+ mpd_add(x0, x0, xstep, &ctx);
+ }
+ mpd_sub(y0, y0, ystep, &ctx);
+ }
+ end_clock = clock();
+
+#ifdef BENCH_VERBOSE
+ for (i = 0; i < 40; i++) {
+ for (j = 0; j < 80; j++) {
+ if (points[i][j] == iter) {
+ putchar('*');
+ }
+ else if (points[i][j] >= 10) {
+ putchar('+');
+ }
+ else if (points[i][j] >= 5) {
+ putchar('.');
+ }
+ else {
+ putchar(' ');
+ }
+ }
+ putchar('\n');
+ }
+ putchar('\n');
+#endif
+
+ printf("time: %f\n\n", (double)(end_clock-start_clock)/(double)CLOCKS_PER_SEC);
+
+ mpd_del(x0);
+ mpd_del(y0);
+ mpd_del(sqrt_2);
+ mpd_del(xstep);
+ mpd_del(ystep);
+
+ return 0;
+}
+
+
+
Added: python/branches/py3k-cdecimal/Modules/cdecimal/bits.h
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/bits.h Thu Jan 7 13:02:51 2010
@@ -0,0 +1,172 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#ifndef BITS_H
+#define BITS_H
+
+
+#include <stdio.h>
+#include "vccompat.h"
+
+
+/* Check if n is a power of 2 */
+static inline int
+ispower2(size_t n)
+{
+ return n != 0 && (n & (n-1)) == 0;
+}
+
+/*
+ * Returns the most significant bit position of n from 0 to 32 (64).
+ * Caller has to make sure that n is not 0.
+ */
+static inline int
+std_bsr(size_t n)
+{
+ int pos = 0;
+ size_t tmp;
+
+#ifdef CONFIG_64
+ tmp = n >> 32;
+ if (tmp != 0) { n = tmp; pos += 32; }
+#endif
+ tmp = n >> 16;
+ if (tmp != 0) { n = tmp; pos += 16; }
+ tmp = n >> 8;
+ if (tmp != 0) { n = tmp; pos += 8; }
+ tmp = n >> 4;
+ if (tmp != 0) { n = tmp; pos += 4; }
+ tmp = n >> 2;
+ if (tmp != 0) { n = tmp; pos += 2; }
+ tmp = n >> 1;
+ if (tmp != 0) { n = tmp; pos += 1; }
+
+ return pos + (int)n - 1;
+}
+
+
+/*
+ * Returns the least significant bit position of n from 0 to 32 (64).
+ * Caller has to make sure that n is not 0.
+ */
+static inline int
+std_bsf(size_t n)
+{
+ int pos;
+
+#ifdef CONFIG_64
+ pos = 63;
+ if (n & 0x00000000FFFFFFFFULL) { pos -= 32; } else { n >>= 32; }
+ if (n & 0x000000000000FFFFULL) { pos -= 16; } else { n >>= 16; }
+ if (n & 0x00000000000000FFULL) { pos -= 8; } else { n >>= 8; }
+ if (n & 0x000000000000000FULL) { pos -= 4; } else { n >>= 4; }
+ if (n & 0x0000000000000003ULL) { pos -= 2; } else { n >>= 2; }
+ if (n & 0x0000000000000001ULL) { pos -= 1; }
+#else
+ pos = 31;
+ if (n & 0x000000000000FFFFUL) { pos -= 16; } else { n >>= 16; }
+ if (n & 0x00000000000000FFUL) { pos -= 8; } else { n >>= 8; }
+ if (n & 0x000000000000000FUL) { pos -= 4; } else { n >>= 4; }
+ if (n & 0x0000000000000003UL) { pos -= 2; } else { n >>= 2; }
+ if (n & 0x0000000000000001UL) { pos -= 1; }
+#endif
+ return pos;
+}
+
+
+#ifdef __GNUC__
+/*
+ * Bit scan reverse.
+ * Caller has to make sure that a is not 0.
+ */
+static inline int
+x86_bsr(size_t a)
+{
+ size_t retval;
+
+ __asm__ (
+#ifdef CONFIG_64
+ "bsrq %1, %0\n\t"
+#else
+ "bsr %1, %0\n\t"
+#endif
+ :"=r" (retval)
+ :"r" (a)
+ :"cc"
+ );
+
+ return (int)retval;
+}
+
+/*
+ * Bit scan forward.
+ * Caller has to make sure that a is not 0.
+ */
+static inline int
+x86_bsf(size_t a)
+{
+ size_t retval;
+
+ __asm__ (
+#ifdef CONFIG_64
+ "bsfq %1, %0"
+#else
+ "bsf %1, %0"
+#endif
+ :"=r" (retval)
+ :"r" (a)
+ :"cc"
+ );
+
+ return (int)retval;
+}
+#endif /* __GNUC__ */
+
+
+#ifdef _MSC_VER
+#include <intrin.h>
+/*
+ * Bit scan reverse.
+ * Caller has to make sure that a is not 0.
+ */
+static inline int __cdecl
+x86_bsr(size_t a)
+{
+ unsigned long retval;
+
+#ifdef CONFIG_64
+ _BitScanReverse64(&retval, a);
+#else
+ _BitScanReverse(&retval, a);
+#endif
+
+ return (int)retval;
+}
+
+/*
+ * Bit scan forward.
+ * Caller has to make sure that a is not 0.
+ */
+static inline int __cdecl
+x86_bsf(size_t a)
+{
+ unsigned long retval;
+
+#ifdef CONFIG_64
+ _BitScanForward64(&retval, a);
+#else
+ _BitScanForward(&retval, a);
+#endif
+
+ return (int)retval;
+}
+#endif /* _MSC_VER */
+
+
+#endif /* BITS_H */
+
+
+
Added: python/branches/py3k-cdecimal/Modules/cdecimal/cdecimal.c
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/cdecimal.c Thu Jan 7 13:02:51 2010
@@ -0,0 +1,4861 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#include <Python.h>
+#include <stdlib.h>
+#include "longintrepr.h"
+#include "pythread.h"
+#include "structmember.h"
+
+#include "docstrings.h"
+#include "memory.h"
+#include "mpdecimal.h"
+#include "mptypes.h"
+
+
+#if defined(_MSC_VER) && defined (CONFIG_64)
+ #define _PyLong_AsMpdSsize PyLong_AsLongLong
+ #define _PyInt_AsMpdSsize PyInt_AsSsize_t
+ #define _PyInt_FromMpdSsize PyInt_FromSsize_t
+ #define _PyLong_FromMpdSsize PyLong_FromSsize_t
+#else
+ #define _PyLong_AsMpdSsize PyLong_AsLong
+ #define _PyInt_AsMpdSsize PyInt_AsLong
+ #define _PyInt_FromMpdSsize PyInt_FromLong
+ #define _PyLong_FromMpdSsize PyLong_FromLong
+#endif
+
+
+#if PY_VERSION_HEX < 0x03000000
+ #error "Python versions < 3.0 not supported"
+#endif
+
+#define Dec_INCREF_TRUE (Py_INCREF(Py_True), Py_True)
+#define Dec_INCREF_FALSE (Py_INCREF(Py_False), Py_False)
+#define Dec_INCREF_NONE (Py_INCREF(Py_None), Py_None)
+
+
+typedef struct {
+ PyObject_HEAD
+ mpd_t *dec;
+} PyDecObject;
+
+typedef struct {
+ PyDictObject dict;
+ uint32_t *flags;
+} PyDecSignalDictObject;
+
+typedef struct {
+ PyObject_HEAD
+ mpd_context_t ctx;
+ PyObject *traps;
+ PyObject *flags;
+ int capitals;
+} PyDecContextObject;
+
+typedef struct {
+ PyObject_HEAD
+ PyObject *local;
+ PyObject *global;
+} PyDecContextManagerObject;
+
+
+static PyTypeObject PyDec_Type;
+static PyTypeObject PyDecSignalDict_Type;
+static PyTypeObject PyDecContext_Type;
+static PyTypeObject PyDecContextManager_Type;
+#define PyDec_CheckExact(v) (Py_TYPE(v) == &PyDec_Type)
+#define PyDec_Check(v) PyObject_TypeCheck(v, &PyDec_Type)
+#define PyDecSignalDict_Check(v) (Py_TYPE(v) == &PyDecSignalDict_Type)
+#define PyDecContext_Check(v) (Py_TYPE(v) == &PyDecContext_Type)
+#define DecAddr(v) (((PyDecObject *)v)->dec)
+#define SdFlagAddr(v) (((PyDecSignalDictObject *)v)->flags)
+#define SdFlags(v) (*((PyDecSignalDictObject *)v)->flags)
+#define CtxAddr(v) (&((PyDecContextObject *)v)->ctx)
+
+
+/* Default module context */
+static PyObject *module_context = NULL;
+/* Basic and extended contexts */
+static PyObject *basic_context = NULL;
+static PyObject *ext_context = NULL;
+/* Thread local objects */
+static PyObject *tls = NULL;
+
+
+typedef struct {
+ const char *name;
+ const char *fqname;
+ uint32_t mpd_cond;
+ PyObject *dec_cond;
+} DecCondMap;
+
+/* Top level Exception; inherits from ArithmeticError */
+static PyObject *DecimalException = NULL;
+
+/* Exceptions that correspond to IEEE signals; inherit from DecimalException */
+static DecCondMap signal_map[] = {
+ {"InvalidOperation", "cdecimal.InvalidOperation", MPD_IEEE_Invalid_operation, NULL},
+ {"DivisionByZero", "cdecimal.DivisionByZero", MPD_Division_by_zero, NULL},
+ {"Overflow", "cdecimal.Overflow", MPD_Overflow, NULL},
+ {"Underflow", "cdecimal.Underflow", MPD_Underflow, NULL},
+ {"Subnormal", "cdecimal.Subnormal", MPD_Subnormal, NULL},
+ {"Inexact", "cdecimal.Inexact", MPD_Inexact, NULL},
+ {"Rounded", "cdecimal.Rounded", MPD_Rounded, NULL},
+ {"Clamped", "cdecimal.Clamped", MPD_Clamped, NULL},
+ {NULL}
+};
+
+/* Exceptions that inherit from InvalidOperation */
+static DecCondMap cond_map[] = {
+ {"InvalidOperation", "cdecimal.InvalidOperation", MPD_Invalid_operation, NULL},
+ {"ConversionSyntax", "cdecimal.ConversionSyntax", MPD_Conversion_syntax, NULL},
+ {"DivisionImpossible", "cdecimal.DivisionImpossible", MPD_Division_impossible, NULL},
+ {"DivisionUndefined", "cdecimal.DivisionUndefined", MPD_Division_undefined, NULL},
+ {"FpuError", "cdecimal.FpuError", MPD_Fpu_error, NULL},
+ {"InvalidContext", "cdecimal.InvalidContext", MPD_Invalid_context, NULL},
+ {"MallocError", "cdecimal.MallocError", MPD_Malloc_error, NULL},
+ {NULL}
+};
+
+static const char *dec_signal_string[MPD_NUM_FLAGS] = {
+ "Clamped",
+ "InvalidOperation",
+ "DivisionByZero",
+ "InvalidOperation",
+ "InvalidOperation",
+ "InvalidOperation",
+ "Inexact",
+ "InvalidOperation",
+ "InvalidOperation",
+ "InvalidOperation",
+ "NotImplemented",
+ "Overflow",
+ "Rounded",
+ "Subnormal",
+ "Underflow",
+};
+
+static void
+dec_traphandler(mpd_context_t *ctx UNUSED)
+{
+ return;
+}
+
+static PyObject *
+flags_as_exception(uint32_t flags)
+{
+ DecCondMap *cm;
+
+ for (cm = signal_map; cm->name != NULL; cm++) {
+ if (flags&cm->mpd_cond) {
+ return cm->dec_cond;
+ }
+ }
+
+ PyErr_SetString(PyExc_ValueError, "invalid flag value");
+ return NULL;
+}
+
+static uint32_t
+exception_as_flags(PyObject *ex)
+{
+ DecCondMap *cm;
+
+ for (cm = signal_map; cm->name != NULL; cm++) {
+ if (cm->dec_cond == ex) {
+ return cm->mpd_cond;
+ }
+ }
+
+ PyErr_SetString(PyExc_ValueError, "invalid signal value");
+ return UINT32_MAX;
+}
+
+static PyObject *
+flags_as_list(uint32_t flags)
+{
+ PyObject *list;
+ DecCondMap *cm;
+
+ if ((list = PyList_New(0)) == NULL) {
+ return NULL;
+ }
+
+ for (cm = cond_map; cm->name != NULL; cm++) {
+ if (flags&cm->mpd_cond) {
+ PyList_Append(list, cm->dec_cond);
+ }
+ }
+ for (cm = signal_map+1; cm->name != NULL; cm++) {
+ if (flags&cm->mpd_cond) {
+ PyList_Append(list, cm->dec_cond);
+ }
+ }
+
+ return list;
+}
+
+static uint32_t
+list_as_flags(PyObject *list)
+{
+ PyObject *item;
+ uint32_t flags, x;
+ ssize_t n, j;
+
+ if (!PyList_Check(list)) {
+ PyErr_Format(PyExc_TypeError, "argument must be a signal list");
+ return UINT32_MAX;
+ }
+
+ n = PyList_Size(list);
+ flags = 0;
+ for (j = 0; j < n; j++) {
+ item = PyList_GetItem(list, j);
+ if ((x = exception_as_flags(item)) == UINT32_MAX) {
+ return UINT32_MAX;
+ }
+ flags |= x;
+ }
+
+ return flags;
+}
+
+static int
+dict_as_flags(PyObject *val)
+{
+ PyObject *b;
+ DecCondMap *cm;
+ uint32_t flags = 0;
+ int x;
+
+ if (!PyDict_Check(val)) {
+ PyErr_SetString(PyExc_ValueError, "argument must be a signal dict");
+ return -1;
+ }
+
+ for (cm = signal_map; cm->name != NULL; cm++) {
+ if ((b = PyDict_GetItem(val, cm->dec_cond)) == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "incomplete signal dict");
+ return UINT32_MAX;
+ }
+
+ if ((x = PyObject_IsTrue(b)) < 0) {
+ return UINT32_MAX;
+ }
+ if (x == 1) {
+ flags |= cm->mpd_cond;
+ }
+ }
+
+ return flags;
+}
+
+static uint32_t
+PyLong_AsMpdFlags(PyObject *v)
+{
+ int overflow;
+ long x;
+
+ if (!PyLong_Check(v)) {
+ PyErr_SetString(PyExc_TypeError, "long argument required");
+ return UINT32_MAX;
+ }
+
+ overflow = 0;
+ x = PyLong_AsLongAndOverflow(v, &overflow);
+ if (overflow != 0 || x < 0 || x > (long)MPD_Max_status) {
+ PyErr_Format(PyExc_ValueError, "invalid flag value");
+ return UINT32_MAX;
+ }
+
+ return x;
+}
+
+static mpd_ssize_t
+PyLong_AsMpdSsize(PyObject *v)
+{
+ mpd_ssize_t x;
+
+ if (!PyLong_Check(v)) {
+ PyErr_SetString(PyExc_TypeError, "long argument required");
+ return MPD_SSIZE_MAX;
+ }
+
+ x = _PyLong_AsMpdSsize(v);
+ if (PyErr_Occurred()) {
+ return MPD_SSIZE_MAX;
+ }
+
+ return x;
+}
+
+static int
+dec_addstatus(mpd_context_t *ctx, uint32_t status)
+{
+ ctx->status |= status;
+ if (ctx->traps&status) {
+ PyObject *ex, *siglist;
+
+ if ((ex = flags_as_exception(ctx->traps&status)) == NULL) {
+ return 1;
+ }
+ if ((siglist = flags_as_list(ctx->traps&status)) == NULL) {
+ return 1;
+ }
+
+ PyErr_SetObject(ex, siglist);
+ Py_DECREF(siglist);
+ return 1;
+ }
+ return 0;
+}
+
+
+/******************************************************************************/
+/* SignalDict Object */
+/******************************************************************************/
+
+static int
+signaldict_init(PyObject *self, PyObject *args, PyObject *kwds)
+{
+ if (PyDict_Type.tp_init(self, args, kwds) < 0) {
+ return -1;
+ }
+
+ SdFlagAddr(self) = NULL;
+ return 0;
+}
+
+/* sync flags and dictionary, using the flags as the master */
+static void
+signaldict_update(PyObject *self)
+{
+ PyObject *b;
+ DecCondMap *cm;
+ uint32_t flags;
+
+ flags = SdFlags(self);
+
+ for (cm = signal_map; cm->name != NULL; cm++) {
+ b = (flags&cm->mpd_cond) ? Py_True : Py_False;
+ PyDict_SetItem(self, cm->dec_cond, b);
+ }
+}
+
+/* set all flags to false */
+static int
+signaldict_clear_all(PyObject *self)
+{
+ DecCondMap *cm;
+
+ SdFlags(self) = 0;
+
+ for (cm = signal_map; cm->name != NULL; cm++) {
+ if (PyDict_SetItem(self, cm->dec_cond, Py_False) < 0) {
+ return -1;
+ }
+ }
+ return 0;
+}
+
+static int
+signaldict_setitem(PyObject *self, PyObject *key, PyObject *value)
+{
+ uint32_t flag;
+ int x;
+
+ if ((flag = exception_as_flags(key)) == UINT_MAX) {
+ PyErr_SetString(PyExc_ValueError, "invalid signal key");
+ return -1;
+ }
+
+ if ((x = PyObject_IsTrue(value)) < 0) {
+ return -1;
+ }
+ if (x == 1) {
+ SdFlags(self) |= flag;
+ PyDict_SetItem(self, key, Py_True);
+ return 0;
+ }
+ else {
+ SdFlags(self) &= ~flag;
+ PyDict_SetItem(self, key, Py_False);
+ return 0;
+ }
+}
+
+static PyObject *
+signaldict_call_unary(PyObject *self, const char *name)
+{
+ PyObject *result, *s;
+
+ if ((s = Py_BuildValue("s", name)) == NULL) {
+ return NULL;
+ }
+
+ signaldict_update(self);
+ result = PyObject_CallMethodObjArgs(self, s, NULL);
+
+ Py_DECREF(s);
+ return result;
+}
+
+static PyObject *
+signaldict_call_binary(PyObject *self, const char *name, PyObject *arg)
+{
+ PyObject *result, *s;
+
+ if ((s = Py_BuildValue("s", name)) == NULL) {
+ return NULL;
+ }
+
+ signaldict_update(self);
+ result = PyObject_CallMethodObjArgs(self, s, arg, NULL);
+
+ Py_DECREF(s);
+ return result;
+}
+
+static PyObject *
+signaldict_richcompare(PyObject *a, PyObject *b, int op)
+{
+ if (PyDecSignalDict_Check(a)) {
+ signaldict_update(a);
+ }
+ if (PyDecSignalDict_Check(b)) {
+ signaldict_update(b);
+ }
+ return PyDict_Type.tp_richcompare(a, b, op);
+}
+
+static int
+signaldict_contains(PyObject *self, PyObject *key)
+{
+ signaldict_update(self);
+ return PyDict_Contains(self, key);
+}
+
+static PyObject *
+signaldict_copy(PyObject *self)
+{
+ signaldict_update(self);
+ return PyDict_Copy(self);
+}
+
+static PyObject *
+signaldict_get(PyObject *self, PyObject *args)
+{
+ return signaldict_call_binary(self, "get", args);
+}
+
+static PyObject *
+signaldict_has_key(PyObject *self, PyObject *key)
+{
+ return signaldict_call_binary(self, "has_key", key);
+}
+
+static PyObject *
+signaldict_items(PyObject *self)
+{
+ signaldict_update(self);
+ return PyDict_Items(self);
+}
+
+static PyObject *
+signaldict_iter(PyObject *self)
+{
+ return PyDict_Type.tp_iter(self);
+}
+
+static PyObject *
+signaldict_iterkeys(PyObject *self)
+{
+ return signaldict_call_unary(self, "iterkeys");
+}
+
+static PyObject *
+signaldict_itervalues(PyObject *self)
+{
+ return signaldict_call_unary(self, "itervalues");
+}
+
+static PyObject *
+signaldict_iteritems(PyObject *self)
+{
+ return signaldict_call_unary(self, "iteritems");
+}
+
+static PyObject *
+signaldict_keys(PyObject *self)
+{
+ signaldict_update(self);
+ return PyDict_Keys(self);
+}
+
+static Py_ssize_t
+signaldict_length(PyObject *self)
+{
+ signaldict_update(self);
+ return PyDict_Type.tp_as_mapping->mp_length(self);
+}
+
+static int
+signaldict_print(PyObject *self, FILE *fp, int flags)
+{
+ signaldict_update(self);
+ return PyDict_Type.tp_print(self, fp, flags);
+}
+
+static PyObject *
+signaldict_repr(PyObject *self)
+{
+ signaldict_update(self);
+ return PyDict_Type.tp_repr(self);
+}
+
+static PyObject *
+signaldict_sizeof(PyObject *self)
+{
+ return signaldict_call_unary(self, "__sizeof__");
+}
+
+static int
+signaldict_ass_sub(PyObject *self, PyObject *v, PyObject *w)
+{
+ if (w == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "signal keys cannot be deleted");
+ return -1;
+ }
+ else {
+ return signaldict_setitem(self, v, w);
+ }
+}
+
+static PyObject *
+signaldict_subscript(PyObject *self, PyObject *key)
+{
+ signaldict_update(self);
+ return PyDict_Type.tp_as_mapping->mp_subscript(self, key);
+}
+
+static PyObject *
+signaldict_values(PyObject *self)
+{
+ signaldict_update(self);
+ return PyDict_Values(self);
+}
+
+
+static PyMappingMethods signaldict_as_mapping = {
+ (lenfunc)signaldict_length, /*mp_length*/
+ (binaryfunc)signaldict_subscript, /*mp_subscript*/
+ (objobjargproc)signaldict_ass_sub /*mp_ass_subscript*/
+};
+
+static PySequenceMethods signaldict_as_sequence = {
+ 0, /* sq_length */
+ 0, /* sq_concat */
+ 0, /* sq_repeat */
+ 0, /* sq_item */
+ 0, /* sq_slice */
+ 0, /* sq_ass_item */
+ 0, /* sq_ass_slice */
+ signaldict_contains, /* sq_contains */
+ 0, /* sq_inplace_concat */
+ 0, /* sq_inplace_repeat */
+};
+
+static PyMethodDef mapp_methods[] = {
+ {"__contains__", (PyCFunction)signaldict_contains, METH_O|METH_COEXIST, NULL},
+ {"__getitem__", (PyCFunction)signaldict_subscript, METH_O|METH_COEXIST, NULL},
+ {"__sizeof__", (PyCFunction)signaldict_sizeof, METH_NOARGS, NULL},
+ {"has_key", (PyCFunction)signaldict_has_key, METH_O, NULL},
+ {"get", (PyCFunction)signaldict_get, METH_VARARGS, NULL},
+ {"keys", (PyCFunction)signaldict_keys, METH_NOARGS, NULL},
+ {"items", (PyCFunction)signaldict_items, METH_NOARGS, NULL},
+ {"values", (PyCFunction)signaldict_values, METH_NOARGS, NULL},
+ {"copy", (PyCFunction)signaldict_copy, METH_NOARGS, NULL},
+ {"iterkeys", (PyCFunction)signaldict_iterkeys, METH_NOARGS, NULL},
+ {"itervalues", (PyCFunction)signaldict_itervalues, METH_NOARGS, NULL},
+ {"iteritems", (PyCFunction)signaldict_iteritems, METH_NOARGS, NULL},
+ {NULL, NULL}
+};
+
+static PyTypeObject PyDecSignalDict_Type =
+{
+ PyVarObject_HEAD_INIT(0, 0)
+ "cdecimal.SignalDict", /* tp_name */
+ sizeof(PyDecSignalDictObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ (printfunc)signaldict_print, /* tp_print */
+ (getattrfunc) 0, /* tp_getattr */
+ (setattrfunc) 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ (reprfunc) signaldict_repr, /* tp_repr */
+ 0, /* tp_as_number */
+ &signaldict_as_sequence, /* tp_as_sequence */
+ &signaldict_as_mapping, /* tp_as_mapping */
+ (hashfunc) PyObject_HashNotImplemented, /* tp_hash */
+ 0, /* tp_call */
+ (reprfunc) 0, /* tp_str */
+ (getattrofunc) PyObject_GenericGetAttr, /* tp_getattro */
+ (setattrofunc) 0, /* tp_setattro */
+ (PyBufferProcs *) 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ 0, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ signaldict_richcompare, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ (getiterfunc)signaldict_iter, /* tp_iter */
+ 0, /* tp_iternext */
+ mapp_methods, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)signaldict_init, /* tp_init */
+};
+
+
+/******************************************************************************/
+/* Context Object, Part 1 */
+/******************************************************************************/
+
+static PyObject *
+context_getprec(PyObject *self, void *closure UNUSED)
+{
+ mpd_context_t *ctx;
+
+ ctx = CtxAddr(self);
+ return Py_BuildValue(CONV_mpd_ssize_t, mpd_getprec(ctx));
+}
+
+static PyObject *
+context_getemax(PyObject *self, void *closure UNUSED)
+{
+ mpd_context_t *ctx;
+
+ ctx = CtxAddr(self);
+ return Py_BuildValue(CONV_mpd_ssize_t, mpd_getemax(ctx));
+}
+
+static PyObject *
+context_getemin(PyObject *self, void *closure UNUSED)
+{
+ mpd_context_t *ctx;
+
+ ctx = CtxAddr(self);
+ return Py_BuildValue(CONV_mpd_ssize_t, mpd_getemin(ctx));
+}
+
+static PyObject *
+context_getetiny(PyObject *self, PyObject *dummy UNUSED)
+{
+ mpd_context_t *ctx;
+
+ ctx = CtxAddr(self);
+ return Py_BuildValue(CONV_mpd_ssize_t, mpd_etiny(ctx));
+}
+
+static PyObject *
+context_getetop(PyObject *self, PyObject *dummy UNUSED)
+{
+ mpd_context_t *ctx;
+
+ ctx = CtxAddr(self);
+ return Py_BuildValue(CONV_mpd_ssize_t, mpd_etop(ctx));
+}
+
+static PyObject *
+context_getround(PyObject *self, void *closure UNUSED)
+{
+ mpd_context_t *ctx;
+
+ ctx = CtxAddr(self);
+ return Py_BuildValue("i", mpd_getround(ctx));
+}
+
+static PyObject *
+context_getcapitals(PyObject *self, void *closure UNUSED)
+{
+ return Py_BuildValue("i", ((PyDecContextObject *)self)->capitals);
+}
+
+static PyObject *
+context_gettraps(PyObject *self, void *closure UNUSED)
+{
+ mpd_context_t *ctx;
+
+ ctx = CtxAddr(self);
+ return Py_BuildValue("i", mpd_gettraps(ctx));
+}
+
+static PyObject *
+context_getstatus(PyObject *self, void *closure UNUSED)
+{
+ mpd_context_t *ctx;
+
+ ctx = CtxAddr(self);
+ return Py_BuildValue("i", mpd_getstatus(ctx));
+}
+
+static PyObject *
+context_getclamp(PyObject *self, void *closure UNUSED)
+{
+ mpd_context_t *ctx;
+
+ ctx = CtxAddr(self);
+ return Py_BuildValue("i", mpd_getclamp(ctx));
+}
+
+static PyObject *
+context_getallcr(PyObject *self, void *closure UNUSED)
+{
+ mpd_context_t *ctx;
+
+ ctx = CtxAddr(self);
+ return Py_BuildValue("i", mpd_getcr(ctx));
+}
+
+static int
+context_setprec(PyObject *self, PyObject *value, void *closure UNUSED)
+{
+ mpd_context_t *ctx;
+ mpd_ssize_t x;
+
+ if ((x = PyLong_AsMpdSsize(value)) == MPD_SSIZE_MAX) {
+ return -1;
+ }
+
+ ctx = CtxAddr(self);
+ if (!mpd_qsetprec(ctx, x)) {
+ if (dec_addstatus(ctx, MPD_Invalid_context)) {
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+static int
+context_setemin(PyObject *self, PyObject *value, void *closure UNUSED)
+{
+ mpd_context_t *ctx;
+ mpd_ssize_t x;
+
+ if ((x = PyLong_AsMpdSsize(value)) == MPD_SSIZE_MAX) {
+ return -1;
+ }
+
+ ctx = CtxAddr(self);
+ if (!mpd_qsetemin(ctx, x)) {
+ if (dec_addstatus(ctx, MPD_Invalid_context)) {
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+static int
+context_setemax(PyObject *self, PyObject *value, void *closure UNUSED)
+{
+ mpd_context_t *ctx;
+ mpd_ssize_t x;
+
+ if ((x = PyLong_AsMpdSsize(value)) == MPD_SSIZE_MAX) {
+ return -1;
+ }
+
+ ctx = CtxAddr(self);
+ if (!mpd_qsetemax(ctx, x)) {
+ if (dec_addstatus(ctx, MPD_Invalid_context)) {
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+static PyObject *
+context_unsafe_setprec(PyObject *self, PyObject *value, void *closure UNUSED)
+{
+ mpd_context_t *ctx = CtxAddr(self);
+
+ if ((ctx->prec = PyLong_AsMpdSsize(value)) == MPD_SSIZE_MAX) {
+ return NULL;
+ }
+
+ Py_RETURN_NONE;
+}
+
+static PyObject *
+context_unsafe_setemin(PyObject *self, PyObject *value, void *closure UNUSED)
+{
+ mpd_context_t *ctx = CtxAddr(self);
+
+ if ((ctx->emin = PyLong_AsMpdSsize(value)) == MPD_SSIZE_MAX) {
+ return NULL;
+ }
+
+ Py_RETURN_NONE;
+}
+
+static PyObject *
+context_unsafe_setemax(PyObject *self, PyObject *value, void *closure UNUSED)
+{
+ mpd_context_t *ctx = CtxAddr(self);
+
+ if ((ctx->emax = PyLong_AsMpdSsize(value)) == MPD_SSIZE_MAX) {
+ return NULL;
+ }
+
+ Py_RETURN_NONE;
+}
+
+static int
+context_setround(PyObject *self, PyObject *value, void *closure UNUSED)
+{
+ mpd_context_t *ctx;
+ mpd_ssize_t x;
+
+ if ((x = PyLong_AsMpdSsize(value)) == MPD_SSIZE_MAX) {
+ return -1;
+ }
+ if (x < 0 || x >= MPD_ROUND_GUARD) {
+ PyErr_SetString(PyExc_TypeError, "invalid value for context.round");
+ return -1;
+ }
+
+ ctx = CtxAddr(self);
+ if (!mpd_qsetround(ctx, (int)x)) {
+ if (dec_addstatus(ctx, MPD_Invalid_context)) {
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+static int
+context_setcapitals(PyObject *self, PyObject *value, void *closure UNUSED)
+{
+ mpd_ssize_t x;
+
+ if ((x = PyLong_AsMpdSsize(value)) == MPD_SSIZE_MAX) {
+ return -1;
+ }
+ if (x != 0 && x != 1) {
+ PyErr_SetString(PyExc_TypeError, "invalid value for context.capitals");
+ return -1;
+ }
+
+ ((PyDecContextObject *)self)->capitals = x;
+
+ return 0;
+}
+
+static int
+context_settraps(PyObject *self, PyObject *value, void *closure UNUSED)
+{
+ mpd_context_t *ctx;
+ uint32_t flags;
+
+ flags = PyLong_AsMpdFlags(value);
+ if (flags == UINT32_MAX) {
+ return -1;
+ }
+
+ ctx = CtxAddr(self);
+ if (!mpd_qsettraps(ctx, (uint32_t)flags)) {
+ if (dec_addstatus(ctx, MPD_Invalid_context)) {
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+static int
+context_settraps_list(PyObject *self, PyObject *value)
+{
+ mpd_context_t *ctx;
+ uint32_t flags;
+
+ if ((flags = list_as_flags(value)) == UINT32_MAX) {
+ return -1;
+ }
+
+ ctx = CtxAddr(self);
+ if (!mpd_qsettraps(ctx, flags)) {
+ if (dec_addstatus(ctx, MPD_Invalid_context)) {
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+static int
+context_settraps_dict(PyObject *self, PyObject *value)
+{
+ mpd_context_t *ctx;
+ uint32_t flags;
+
+ if ((flags = dict_as_flags(value)) == UINT32_MAX) {
+ return -1;
+ }
+
+ ctx = CtxAddr(self);
+ if (!mpd_qsettraps(ctx, flags)) {
+ if (dec_addstatus(ctx, MPD_Invalid_context)) {
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+static int
+context_setstatus(PyObject *self, PyObject *value, void *closure UNUSED)
+{
+ mpd_context_t *ctx;
+ uint32_t flags;
+
+ flags = PyLong_AsMpdFlags(value);
+ if (flags == UINT32_MAX) {
+ return -1;
+ }
+
+ ctx = CtxAddr(self);
+ if (!mpd_qsetstatus(ctx, (uint32_t)flags)) {
+ if (dec_addstatus(ctx, MPD_Invalid_context)) {
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+static int
+context_setstatus_list(PyObject *self, PyObject *value)
+{
+ mpd_context_t *ctx;
+ uint32_t flags;
+
+ if ((flags = list_as_flags(value)) == UINT32_MAX) {
+ return -1;
+ }
+
+ ctx = CtxAddr(self);
+ if (!mpd_qsetstatus(ctx, flags)) {
+ if (dec_addstatus(ctx, MPD_Invalid_context)) {
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+static int
+context_setstatus_dict(PyObject *self, PyObject *value)
+{
+ mpd_context_t *ctx;
+ uint32_t flags;
+
+ if ((flags = dict_as_flags(value)) == UINT32_MAX) {
+ return -1;
+ }
+
+ ctx = CtxAddr(self);
+ if (!mpd_qsetstatus(ctx, flags)) {
+ if (dec_addstatus(ctx, MPD_Invalid_context)) {
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+static int
+context_setclamp(PyObject *self, PyObject *value, void *closure UNUSED)
+{
+ mpd_context_t *ctx;
+ mpd_ssize_t x;
+
+ if ((x = PyLong_AsMpdSsize(value)) == MPD_SSIZE_MAX) {
+ return -1;
+ }
+
+ ctx = CtxAddr(self);
+ if (!mpd_qsetclamp(ctx, (int)x)) {
+ if (dec_addstatus(ctx, MPD_Invalid_context)) {
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+static int
+context_setallcr(PyObject *self, PyObject *value, void *closure UNUSED)
+{
+ mpd_context_t *ctx;
+ mpd_ssize_t x;
+
+ if ((x = PyLong_AsMpdSsize(value)) == MPD_SSIZE_MAX) {
+ return -1;
+ }
+
+ ctx = CtxAddr(self);
+ if (!mpd_qsetcr(ctx, (int)x)) {
+ if (dec_addstatus(ctx, MPD_Invalid_context)) {
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+static PyObject *
+context_getattr(PyObject *self, PyObject *name)
+{
+ PyObject *retval, *s;
+
+ if ((s = PyUnicode_AsASCIIString(name)) == NULL) {
+ return NULL;
+ }
+
+ if (strcmp(PyBytes_AS_STRING(s), "traps") == 0) {
+ retval = ((PyDecContextObject *)self)->traps;
+ Py_INCREF(retval);
+ }
+ else if (strcmp(PyBytes_AS_STRING(s), "flags") == 0) {
+ retval = ((PyDecContextObject *)self)->flags;
+ Py_INCREF(retval);
+ }
+ else {
+ retval = PyObject_GenericGetAttr(self, name);
+ }
+
+ Py_DECREF(s);
+ return retval;
+}
+
+static int
+context_setattr(PyObject *self, PyObject *name, PyObject *value)
+{
+ PyObject *s;
+ int retval = 0;
+
+ if ((s = PyUnicode_AsASCIIString(name)) == NULL) {
+ return -1;
+ }
+
+ if (strcmp(PyBytes_AS_STRING(s), "traps") == 0) {
+ if (context_settraps_dict(self, value) < 0) {
+ retval = -1;
+ }
+ }
+ else if (strcmp(PyBytes_AS_STRING(s), "flags") == 0) {
+ if (context_setstatus_dict(self, value) < 0) {
+ retval = -1;
+ }
+ }
+ else {
+ retval = PyObject_GenericSetAttr(self, name, value);
+ }
+
+ Py_DECREF(s);
+ return retval;
+}
+
+static PyObject *
+context_clear_traps(PyObject *self, PyObject *dummy UNUSED)
+{
+ PyDecContextObject *decctx = (PyDecContextObject *)self;
+
+ if (signaldict_clear_all(decctx->traps) < 0) {
+ return NULL;
+ }
+ Py_RETURN_NONE;
+}
+
+static PyObject *
+context_clear_flags(PyObject *self, PyObject *dummy UNUSED)
+{
+ PyDecContextObject *decctx = (PyDecContextObject *)self;
+
+ if (signaldict_clear_all(decctx->flags) < 0) {
+ return NULL;
+ }
+ Py_RETURN_NONE;
+}
+
+static PyObject *
+context_new(PyTypeObject *type UNUSED, PyObject *args UNUSED,
+ PyObject *kwds UNUSED)
+{
+ PyDecContextObject *self = NULL;
+ mpd_context_t *ctx;
+
+ self = PyObject_New(PyDecContextObject, &PyDecContext_Type);
+ if (self == NULL) {
+ return NULL;
+ }
+ self->traps = PyObject_CallObject((PyObject *)&PyDecSignalDict_Type, NULL);
+ if (self->traps == NULL) {
+ Py_DECREF(self);
+ return NULL;
+ }
+ self->flags = PyObject_CallObject((PyObject *)&PyDecSignalDict_Type, NULL);
+ if (self->flags == NULL) {
+ Py_DECREF(self->traps);
+ Py_DECREF(self);
+ return NULL;
+ }
+
+ ctx = CtxAddr(self);
+ SdFlagAddr(self->traps) = &ctx->traps;
+ SdFlagAddr(self->flags) = &ctx->status;
+
+ return (PyObject *)self;
+}
+
+static void
+context_dealloc(PyDecContextObject *self)
+{
+ Py_DECREF(self->traps);
+ Py_DECREF(self->flags);
+ PyObject_Del(self);
+}
+
+static int
+context_init(PyObject *self, PyObject *args, PyObject *kwds)
+{
+ static char *kwlist[] = {
+ "prec", "Emin", "Emax", "rounding", "capitals",
+ "traps", "flags", "_clamp", "_allcr", NULL
+ };
+ PyObject *traps = NULL;
+ PyObject *status = NULL;
+ mpd_context_t *ctx, t;
+ int capitals = 1;
+
+ assert(PyTuple_Check(args));
+ ctx = CtxAddr(self);
+
+ mpd_defaultcontext(&t);
+ if (!PyArg_ParseTupleAndKeywords(
+ args, kwds,
+ "|"CONV_mpd_ssize_t CONV_mpd_ssize_t CONV_mpd_ssize_t"iiOOii",
+ kwlist,
+ &t.prec, &t.emin, &t.emax, &t.round, &capitals,
+ &traps, &status, &t.clamp, &t.allcr
+ )) {
+ return -1;
+ }
+
+ if (!mpd_qsetprec(ctx, t.prec) ||
+ !mpd_qsetemin(ctx, t.emin) ||
+ !mpd_qsetemax(ctx, t.emax) ||
+ !mpd_qsetround(ctx, t.round) ||
+ !mpd_qsettraps(ctx, t.traps) ||
+ !mpd_qsetstatus(ctx, t.status) ||
+ !mpd_qsetclamp(ctx, t.clamp) ||
+ !mpd_qsetcr(ctx, t.allcr)) {
+ if (dec_addstatus(ctx, MPD_Invalid_context)) {
+ return -1;
+ }
+ }
+
+ if (capitals != 0 && capitals != 1) {
+ PyErr_SetString(PyExc_ValueError, "invalid value for capitals");
+ return -1;
+ }
+ ((PyDecContextObject *)self)->capitals = capitals;
+
+ if (traps != NULL) {
+ if (PyLong_Check(traps)) {
+ return context_settraps(self, traps, NULL);
+ }
+ else if (PyList_Check(traps)) {
+ return context_settraps_list(self, traps);
+ }
+ else {
+ return context_settraps_dict(self, traps);
+ }
+ }
+ if (status != NULL) {
+ if (PyLong_Check(status)) {
+ return context_setstatus(self, status, NULL);
+ }
+ else if (PyList_Check(status)) {
+ return context_setstatus_list(self, status);
+ }
+ else {
+ return context_setstatus_dict(self, status);
+ }
+ }
+
+ return 0;
+}
+
+#define FD_CTX_LEN 640
+static PyObject *
+context_repr(PyDecContextObject *self)
+{
+ mpd_context_t *ctx;
+ char s[FD_CTX_LEN];
+ char *cp;
+ ssize_t n, mem;
+
+ assert(PyDecContext_Check(self));
+ ctx = CtxAddr(self);
+
+ cp = s; mem = FD_CTX_LEN;
+ n = snprintf(cp, mem, "Context(prec=%"PRI_mpd_ssize_t", Emin=%"PRI_mpd_ssize_t""
+ ", Emax=%"PRI_mpd_ssize_t", rounding=%s, capitals=%d, traps=",
+ ctx->prec, ctx->emin, ctx->emax, mpd_round_string[ctx->round],
+ self->capitals);
+ if (n < 0 || n >= mem) return NULL;
+ cp += n; mem -= n;
+
+ n = mpd_lsnprint_signals(cp, mem, ctx->traps, dec_signal_string);
+ if (n < 0 || n >= mem) return NULL;
+ cp += n; mem -= n;
+
+ n = snprintf(cp, mem, ", flags=");
+ if (n < 0 || n >= mem) return NULL;
+ cp += n; mem -= n;
+
+ n = mpd_lsnprint_signals(cp, mem, ctx->status, dec_signal_string);
+ if (n < 0 || n >= mem) return NULL;
+ cp += n; mem -= n;
+
+ n = snprintf(cp, mem, ")");
+ if (n < 0 || n >= mem) return NULL;
+
+ return PyUnicode_FromString(s);
+}
+
+/* New copy with all settings except the status */
+static PyObject *
+context_copy(PyObject *self)
+{
+ PyObject *newob;
+ mpd_context_t *ctx;
+
+ newob = PyObject_CallObject((PyObject *)&PyDecContext_Type, NULL);
+ if (newob == NULL) {
+ return NULL;
+ }
+
+ ctx = CtxAddr(newob);
+
+ *ctx = *CtxAddr(self);
+ ctx->status = 0;
+ ctx->newtrap = 0;
+ ((PyDecContextObject *)newob)->capitals = ((PyDecContextObject *)self)->capitals;
+
+ return newob;
+}
+
+static PyObject *
+context_reduce(PyObject *self, PyObject *args UNUSED)
+{
+ mpd_context_t *ctx = CtxAddr(self);
+
+ return Py_BuildValue(
+ "O("CONV_mpd_ssize_t CONV_mpd_ssize_t CONV_mpd_ssize_t \
+ "iiiiii)",
+ Py_TYPE(self), ctx->prec, ctx->emin, ctx->emax,
+ ctx->round, ((PyDecContextObject *)self)->capitals,
+ ctx->traps, ctx->status, ctx->clamp, ctx->allcr
+ );
+}
+
+
+static PyGetSetDef context_getsets [] =
+{
+ { "prec", (getter)context_getprec, (setter)context_setprec, NULL, NULL},
+ { "Emax", (getter)context_getemax, (setter)context_setemax, NULL, NULL},
+ { "Emin", (getter)context_getemin, (setter)context_setemin, NULL, NULL},
+ { "rounding", (getter)context_getround, (setter)context_setround, NULL, NULL},
+ { "capitals", (getter)context_getcapitals, (setter)context_setcapitals, NULL, NULL},
+ { "_clamp", (getter)context_getclamp, (setter)context_setclamp, NULL, NULL},
+ { "_allcr", (getter)context_getallcr, (setter)context_setallcr, NULL, NULL},
+ { "_traps", (getter)context_gettraps, (setter)context_settraps, NULL, NULL},
+ { "_flags", (getter)context_getstatus, (setter)context_setstatus, NULL, NULL},
+ {NULL}
+};
+
+
+#define CONTEXT_CHECK(obj) \
+ if (!PyDecContext_Check(obj)) { \
+ PyErr_SetString( PyExc_TypeError, \
+ "argument must be a context" ); \
+ return NULL; \
+ }
+
+#define CONTEXT_CHECK_VA(obj) \
+ if (!PyDecContext_Check(obj)) { \
+ PyErr_SetString( PyExc_TypeError, \
+ "optional argument must be a context" ); \
+ return NULL; \
+ }
+
+
+/******************************************************************************/
+/* Global, thread local and temporary contexts */
+/******************************************************************************/
+
+
+#ifndef USE_THREAD_LOCAL_STORAGE /* Recommended: No TLS */
+/* Internal: return borrowed reference to default context object */
+static inline PyObject *
+dflt_ctx(void)
+{
+ return module_context;
+}
+
+/* Internal: set default context, preserve old reference */
+static inline PyObject *
+set_dflt_ctx(PyObject *obj)
+{
+ module_context = obj;
+ return Py_None;
+}
+
+/* Internal: return convenience pointer to raw default context */
+static inline mpd_context_t *
+mpd_ctx(void)
+{
+ return CtxAddr(module_context);
+}
+
+/* Return context object, increment reference */
+static PyObject *
+PyDec_GetDefaultContext(void)
+{
+ Py_INCREF(module_context);
+ return module_context;
+}
+
+/* Set the module context to a new context object */
+static PyObject *
+PyDec_SetDefaultContext(PyObject *self UNUSED, PyObject *obj)
+{
+ CONTEXT_CHECK(obj);
+
+ Py_DECREF(module_context);
+ module_context = obj;
+ Py_INCREF(module_context);
+ Py_RETURN_NONE;
+}
+#else
+/*
+ * Thread local storage for the context is not a good idea. All functions
+ * that map Python's arithmetic operators to mpdecimal functions have to
+ * look up the default context for each and every operation. This is more
+ * than twice as slow as using the module context.
+ *
+ * This section is here for compatibility with decimal.py, but compiling
+ * with USE_THREAD_LOCAL_STORAGE is strongly discouraged.
+ *
+ * If you need threads in your application, simply create a context for
+ * each thread and only use the functions that accept a context parameter.
+ */
+
+/* Internal: return borrowed reference to thread local default context object */
+static PyObject *
+dflt_ctx(void)
+{
+ PyObject *obj = NULL;
+
+ if ((obj = PyObject_GetAttrString(tls, "default_context")) != NULL) {
+ /* We already have a thread local context and return a
+ * borrowed reference. */
+ assert(PyDecContext_Check(obj));
+ Py_DECREF(obj);
+ return obj;
+ }
+
+ /* Otherwise, set the default context attribute */
+ PyErr_Clear();
+ if ((obj = (PyObject *)context_copy(module_context)) == NULL) {
+ return NULL;
+ }
+ if (PyObject_SetAttrString(tls, "default_context", obj) == -1) {
+ Py_DECREF(obj);
+ return NULL;
+ }
+ Py_DECREF(obj);
+
+ /* refcount is 1 */
+ return obj;
+}
+
+/* Internal: set thread local default context, preserve old reference */
+static PyObject *
+set_dflt_ctx(PyObject *obj)
+{
+ /* Preserve a reference to the previous context. */
+ Py_INCREF(dflt_ctx());
+ /* This decrements the refcount of a previous context. */
+ if (PyObject_SetAttrString(tls, "default_context", obj) == -1) {
+ return NULL;
+ }
+ return Py_None;
+}
+
+/* Internal: return convenience pointer to thread local raw context */
+static mpd_context_t *
+mpd_ctx(void)
+{
+ PyObject *obj;
+
+ if ((obj = dflt_ctx()) == NULL) {
+ /* XXX The alternative is to add even more error handling code
+ * to the arithmetic functions. This would punish users who do
+ * not use TLS. */
+ mpd_err_fatal("Retrieving thread local context failed.");
+ /* Not reached */
+ }
+ return CtxAddr(obj);
+}
+
+/* Return thread local default context object with incremented refcount */
+static PyObject *
+PyDec_GetDefaultContext(void)
+{
+ PyObject *obj;
+
+ if ((obj = dflt_ctx()) == NULL) {
+ return NULL;
+ }
+ Py_INCREF(obj);
+ return obj;
+}
+
+/* Set thread local context object */
+static PyObject *
+PyDec_SetDefaultContext(PyObject *self UNUSED, PyObject *obj)
+{
+ CONTEXT_CHECK(obj);
+
+ /* This clears one reference to a previous context. */
+ if (PyObject_SetAttrString(tls, "default_context", obj) == -1) {
+ return NULL;
+ }
+
+ Py_RETURN_NONE;
+}
+#endif
+
+
+/* For the "with" statement: return a context manager object */
+static PyObject *
+ctxmanager_new(PyObject *self UNUSED, PyObject *args)
+{
+ PyDecContextManagerObject *ctx_mgr;
+ PyObject *src;
+
+ src = dflt_ctx();
+ if (!PyArg_ParseTuple(args, "|O", &src)) {
+ return NULL;
+ }
+ CONTEXT_CHECK_VA(src);
+
+ ctx_mgr = PyObject_New(PyDecContextManagerObject, &PyDecContextManager_Type);
+ if (ctx_mgr == NULL) {
+ return NULL;
+ }
+
+ ctx_mgr->local = context_copy(src);
+ if (ctx_mgr->local == NULL) {
+ Py_DECREF(ctx_mgr);
+ return NULL;
+ }
+
+ ctx_mgr->global = dflt_ctx();
+ if (ctx_mgr->global == NULL) {
+ Py_DECREF(ctx_mgr->local);
+ Py_DECREF(ctx_mgr);
+ return NULL;
+ }
+
+ return (PyObject *)ctx_mgr;
+}
+
+static void
+ctxmanager_dealloc(PyDecContextObject *self)
+{
+ PyObject_Del(self);
+}
+
+static PyObject *
+ctxmanager_set_local(PyDecContextManagerObject *self, PyObject *args UNUSED)
+{
+ if (set_dflt_ctx(self->local) == NULL) {
+ return NULL;
+ }
+ return (PyObject *)self->local;
+}
+
+static PyObject *
+ctxmanager_restore_default(PyDecContextManagerObject *self, PyObject *args UNUSED)
+{
+ if (set_dflt_ctx(self->global) == NULL) {
+ return NULL;
+ }
+ return Dec_INCREF_FALSE;
+}
+
+
+static PyMethodDef ctxmanager_methods[] = {
+ {"__enter__", (PyCFunction)ctxmanager_set_local, METH_NOARGS, NULL},
+ {"__exit__", (PyCFunction)ctxmanager_restore_default, METH_VARARGS, NULL},
+ {NULL, NULL}
+};
+
+static PyTypeObject PyDecContextManager_Type =
+{
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "cdecimal.ContextManager", /* tp_name */
+ sizeof(PyDecContextManagerObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ (destructor) ctxmanager_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ (getattrfunc) 0, /* tp_getattr */
+ (setattrfunc) 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc) 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ (getattrofunc) PyObject_GenericGetAttr, /* tp_getattro */
+ (setattrofunc) 0, /* tp_setattro */
+ (PyBufferProcs *) 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ 0, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ ctxmanager_methods, /* tp_methods */
+};
+
+
+/******************************************************************************/
+/* Decimal Object */
+/******************************************************************************/
+
+static PyDecObject *
+dec_alloc(void)
+{
+ PyDecObject * self;
+
+ if ((self = PyObject_New(PyDecObject, &PyDec_Type)) == NULL) {
+ return NULL;
+ }
+ if ((self->dec = mpd_qnew()) == NULL) {
+ PyErr_NoMemory();
+ PyObject_Del(self);
+ return NULL;
+ }
+
+ return self;
+}
+
+static void
+dec_dealloc(PyObject *self)
+{
+ mpd_del(DecAddr(self));
+ Py_TYPE(self)->tp_free(self);
+}
+
+
+/*******************************************************/
+/* Conversions to decimal */
+/*******************************************************/
+
+/* Caller guarantees types. */
+static PyObject *
+_PyDec_FromUnicode(PyObject *v, mpd_context_t *ctx)
+{
+ PyDecObject *newob;
+ uint32_t status = 0;
+ char *cp;
+
+ if((newob = dec_alloc()) == NULL) {
+ return NULL;
+ }
+ if ((cp = PyMem_Malloc(PyUnicode_GET_SIZE(v)+1)) == NULL) {
+ Py_DECREF(newob);
+ PyErr_NoMemory();
+ return NULL;
+ }
+ if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
+ PyUnicode_GET_SIZE(v),
+ cp, NULL)) {
+ Py_DECREF(newob);
+ PyMem_Free(cp);
+ return NULL;
+ }
+
+ mpd_qset_string(newob->dec, cp, ctx, &status);
+ PyMem_Free(cp);
+ if (dec_addstatus(ctx, status)) {
+ Py_DECREF(newob);
+ return NULL;
+ }
+
+ return (PyObject *)newob;
+}
+
+/* Caller guarantees types. */
+static PyObject *
+_PyDec_FromLong(PyObject *v, mpd_context_t *ctx)
+{
+ PyDecObject *newob;
+ PyLongObject *l = (PyLongObject *)v;
+ Py_ssize_t ob_size;
+ uint32_t status = 0;
+ size_t len;
+ uint8_t sign;
+
+ if((newob = dec_alloc()) == NULL) {
+ return NULL;
+ }
+
+ ob_size = Py_SIZE(l);
+ if (ob_size == 0) {
+ newob->dec->exp = 0;
+ newob->dec->data[0] = 0;
+ newob->dec->len = 1;
+ newob->dec->digits = 1;
+ return (PyObject *)newob;
+ }
+
+ if (ob_size < 0) {
+ len = -ob_size;
+ sign = MPD_NEG;
+ }
+ else {
+ len = ob_size;
+ sign = MPD_POS;
+ }
+
+#if PYLONG_BITS_IN_DIGIT == 30
+ mpd_qimport_u32(newob->dec, l->ob_digit, len, sign, PyLong_BASE,
+ ctx, &status);
+#elif PYLONG_BITS_IN_DIGIT == 15
+ mpd_qimport_u16(newob->dec, l->ob_digit, len, sign, PyLong_BASE,
+ ctx, &status);
+#else
+ #error "PYLONG_BITS_IN_DIGIT should be 15 or 30"
+#endif
+ if (dec_addstatus(ctx, status)) {
+ Py_DECREF(newob);
+ return NULL;
+ }
+
+ return (PyObject *)newob;
+}
+
+/*
+ * The following conversion functions read with a maxcontext in order
+ * to emulate limitless reading of decimals. If the decimal cannot be
+ * read exactly due to the limits of the maxcontext, InvalidOperation
+ * is raised.
+ *
+ * Leading and trailing whitespace is allowed.
+ */
+static char *
+strip_ws(const char *x)
+{
+ char *s, *t;
+ char *y;
+ size_t n;
+
+ s = (char *)x;
+ while (isspace((unsigned char)*s))
+ s++;
+
+ t = y = s+strlen(s);
+ while (t > s && isspace((unsigned char)*(t-1)))
+ t--;
+
+ if (s != x || t != y) {
+ n = t-s;
+ if ((y = PyMem_Malloc(n+1)) == NULL) {
+ return NULL;
+ }
+ strncpy(y, s, n);
+ y[n] = '\0';
+ return y;
+ }
+
+ return (char *)x;
+}
+
+/* Caller guarantees types. */
+static PyObject *
+_PyDec_FromUnicode_Max(PyObject *v, mpd_context_t *ctx)
+{
+ PyDecObject *newob;
+ mpd_context_t maxctx;
+ uint32_t status = 0;
+ char *cp, *stripped;
+
+ if((newob = dec_alloc()) == NULL) {
+ return NULL;
+ }
+ if ((cp = PyMem_Malloc(PyUnicode_GET_SIZE(v)+1)) == NULL) {
+ Py_DECREF(newob);
+ PyErr_NoMemory();
+ return NULL;
+ }
+ if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
+ PyUnicode_GET_SIZE(v),
+ cp, NULL)) {
+ Py_DECREF(newob);
+ PyMem_Free(cp);
+ return NULL;
+ }
+
+ mpd_maxcontext(&maxctx);
+ if ((stripped = strip_ws(cp)) == NULL) {
+ Py_DECREF(newob);
+ PyMem_Free(cp);
+ PyErr_NoMemory();
+ return NULL;
+ }
+
+ mpd_qset_string(newob->dec, stripped, &maxctx, &status);
+ if (stripped != cp) {
+ PyMem_Free(stripped);
+ }
+ PyMem_Free(cp);
+ if (status&(MPD_Inexact|MPD_Rounded)) {
+ /* we want exact results */
+ mpd_seterror(newob->dec, MPD_Invalid_operation, &status);
+ }
+ status &= MPD_Errors;
+ if (dec_addstatus(ctx, status)) {
+ Py_DECREF(newob);
+ return NULL;
+ }
+
+ return (PyObject *)newob;
+}
+
+/* Caller guarantees types. */
+static PyObject *
+_PyDec_FromLong_Max(PyObject *v, mpd_context_t *ctx)
+{
+ PyDecObject *newob;
+ PyLongObject *l = (PyLongObject *)v;
+ Py_ssize_t ob_size;
+ mpd_context_t maxctx;
+ uint32_t status = 0;
+ size_t len;
+ uint8_t sign;
+
+ if((newob = dec_alloc()) == NULL) {
+ return NULL;
+ }
+
+ ob_size = Py_SIZE(l);
+ if (ob_size == 0) {
+ newob->dec->exp = 0;
+ newob->dec->data[0] = 0;
+ newob->dec->len = 1;
+ newob->dec->digits = 1;
+ return (PyObject *)newob;
+ }
+
+ if (ob_size < 0) {
+ len = -ob_size;
+ sign = MPD_NEG;
+ }
+ else {
+ len = ob_size;
+ sign = MPD_POS;
+ }
+
+ mpd_maxcontext(&maxctx);
+
+#if PYLONG_BITS_IN_DIGIT == 30
+ mpd_qimport_u32(newob->dec, l->ob_digit, len, sign, PyLong_BASE,
+ &maxctx, &status);
+#elif PYLONG_BITS_IN_DIGIT == 15
+ mpd_qimport_u16(newob->dec, l->ob_digit, len, sign, PyLong_BASE,
+ &maxctx, &status);
+#else
+ #error "PYLONG_BITS_IN_DIGIT should be 15 or 30"
+#endif
+
+ if (status&(MPD_Inexact|MPD_Rounded)) {
+ /* we want exact results */
+ mpd_seterror(newob->dec, MPD_Invalid_operation, &status);
+ }
+ status &= MPD_Errors;
+ if (dec_addstatus(ctx, status)) {
+ Py_DECREF(newob);
+ return NULL;
+ }
+
+ return (PyObject *)newob;
+}
+
+/* Caller guarantees types. */
+static PyObject *
+_PyDec_FromTuple_Max(PyObject *v, mpd_context_t *ctx)
+{
+ PyObject *result;
+ PyObject *tmp, *dtuple;
+ char *decstring, *cp;
+ char sign_special[6];
+ long sign, l;
+ mpd_ssize_t exp = 0;
+ Py_ssize_t i, mem, tsize;
+ int n;
+
+ if (PyTuple_Size(v) != 3) {
+ PyErr_SetString(PyExc_ValueError,
+ "argument must be a tuple of length 3");
+ return NULL;
+ }
+
+ tmp = PyTuple_GET_ITEM(v, 0);
+ sign = PyLong_AsLong(tmp);
+ if (!PyLong_Check(tmp) || (sign != 0 && sign != 1)) {
+ PyErr_SetString(PyExc_ValueError,
+ "sign must be 0 or 1");
+ return NULL;
+ }
+ sign_special[0] = sign ? '-' : '+';
+ sign_special[1] = '\0';
+
+ tmp = PyTuple_GET_ITEM(v, 2);
+ if (PyUnicode_Check(tmp)) {
+ tmp = PyUnicode_AsASCIIString(tmp);
+ if (tmp == NULL) {
+ return NULL;
+ }
+ if (strcmp(PyBytes_AS_STRING(tmp), "F") == 0) {
+ strcat(sign_special, "Inf");
+ }
+ else if (strcmp(PyBytes_AS_STRING(tmp), "n") == 0) {
+ strcat(sign_special, "NaN");
+ }
+ else if (strcmp(PyBytes_AS_STRING(tmp), "N") == 0) {
+ strcat(sign_special, "sNaN");
+ }
+ else {
+ Py_DECREF(tmp);
+ PyErr_SetString(PyExc_ValueError,
+ "string argument in the third position"
+ "must be 'F', 'n' or 'N'");
+ return NULL;
+ }
+ Py_DECREF(tmp);
+ }
+ else {
+ exp = PyLong_AsMpdSsize(tmp);
+ if (PyErr_Occurred()) {
+ PyErr_SetString(PyExc_ValueError,
+ "exponent not an integer or "
+ "out of range");
+ return NULL;
+ }
+ }
+
+ dtuple = PyTuple_GET_ITEM(v, 1);
+ if (!PyTuple_Check(dtuple)) {
+ PyErr_SetString(PyExc_ValueError,
+ "coefficient must be a tuple of digits");
+ return NULL;
+ }
+
+ tsize = PyTuple_Size(dtuple);
+ /* [sign][tuple-digits+1][E][-][exp-digits+1]['\0'] */
+ mem = 1 + tsize + 3 + MPD_EXPDIGITS + 2;
+ cp = decstring = PyMem_Malloc(mem);
+ if (decstring == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+
+ n = snprintf(cp, mem, "%s", sign_special);
+ if (n < 0 || n >= mem) return NULL;
+ cp += n;
+
+ if (sign_special[1] == '\0' && tsize == 0) {
+ /* not a special number and empty tuple */
+ *cp++ = '0';
+ }
+ for (i = 0; i < tsize; i++) {
+ tmp = PyTuple_GET_ITEM(dtuple, i);
+ l = PyLong_AsLong(tmp);
+ if (l < 0 || l > 9) {
+ PyMem_Free(decstring);
+ PyErr_SetString(PyExc_ValueError,
+ "coefficient must be a tuple of digits");
+ return NULL;
+ }
+ *cp++ = l + '0';
+ }
+ *cp = '\0';
+
+ if (sign_special[1] == '\0') {
+ /* not a special number */
+ *cp++ = 'E';
+ n = snprintf(cp, MPD_EXPDIGITS+1, "%" PRI_mpd_ssize_t, exp);
+ if (n < 0 || n >= MPD_EXPDIGITS+1) return NULL;
+ }
+
+ tmp = PyUnicode_FromString(decstring);
+ PyMem_Free(decstring);
+ if (tmp == NULL) {
+ return NULL;
+ }
+
+ result = _PyDec_FromUnicode_Max(tmp, ctx);
+ Py_DECREF(tmp);
+ return result;
+}
+
+/* Caller guarantees types. */
+static PyObject *
+dec_apply(PyObject *v, mpd_context_t *ctx)
+{
+ PyDecObject *newob;
+ uint32_t status = 0;
+
+ if((newob = dec_alloc()) == NULL) {
+ return NULL;
+ }
+
+ mpd_qcopy(newob->dec, ((PyDecObject *)v)->dec, &status);
+ if (dec_addstatus(ctx, status)) {
+ Py_DECREF(newob);
+ return NULL;
+ }
+
+ mpd_qfinalize(newob->dec, ctx, &status);
+ if (dec_addstatus(ctx, status)) {
+ Py_DECREF(newob);
+ return NULL;
+ }
+
+ return (PyObject *)newob;
+}
+
+static PyObject *
+PyDec_Apply(PyObject *decobj, PyObject *args)
+{
+ PyObject *ctxobj;
+ mpd_context_t *ctx;
+
+ ctxobj = dflt_ctx();
+ if (!PyArg_ParseTuple(args, "|O", &ctxobj)) {
+ return NULL;
+ }
+
+ CONTEXT_CHECK_VA(ctxobj);
+ ctx = CtxAddr(ctxobj);
+
+ return dec_apply(decobj, ctx);
+}
+
+static PyObject *
+PyDecContext_Apply(PyObject *ctxobj, PyObject *decobj)
+{
+ mpd_context_t *ctx;
+
+ if (!PyDec_Check(decobj)) {
+ PyErr_SetString(PyExc_TypeError, "argument must be a Decimal");
+ return NULL;
+ }
+
+ CONTEXT_CHECK_VA(ctxobj);
+ ctx = CtxAddr(ctxobj);
+
+ return dec_apply(decobj, ctx);
+}
+
+
+/* Conversion functions */
+
+/* Try to convert PyObject v to PyDecObject a. */
+static inline int
+convert_op(PyObject *v, PyDecObject **a, mpd_context_t *ctx)
+{
+
+ if (PyDec_Check(v)) {
+ *a = (PyDecObject *) v;
+ Py_INCREF(v);
+ }
+ else if (PyLong_Check(v)) {
+ if ((*a = (PyDecObject *) _PyDec_FromLong_Max(v, ctx)) == NULL) {
+ return 0;
+ }
+ }
+ else {
+ Py_INCREF(Py_NotImplemented);
+ *a = (PyDecObject *) Py_NotImplemented;
+ return 0;
+ }
+
+ return 1;
+}
+
+#define CONVERT_OP(v, a, ctx) \
+ if (!convert_op(v, a, ctx)) { \
+ return (PyObject *) *(a); \
+ }
+
+#define CONVERT_BINOP(v, w, a, b, ctx) \
+ if (!convert_op(v, a, ctx)) { \
+ return (PyObject *) *(a); \
+ } \
+ if (!convert_op(w, b, ctx)) { \
+ Py_DECREF(*(a)); \
+ return (PyObject *) *(b); \
+ }
+
+#define CONVERT_TERNOP(v, w, x, a, b, c, ctx) \
+ if (!convert_op(v, a, ctx)) { \
+ return (PyObject *) *(a); \
+ } \
+ if (!convert_op(w, b, ctx)) { \
+ Py_DECREF(*(a)); \
+ return (PyObject *) *(b); \
+ } \
+ if (!convert_op(x, c, ctx)) { \
+ Py_DECREF(*(a)); \
+ Py_DECREF(*(b)); \
+ return (PyObject *) *(c); \
+ }
+
+
+/* Same as convert_op(), but set an error instead of returning NotImplemented. */
+static int
+convert_op_set(PyObject *v, PyDecObject **a, mpd_context_t *ctx)
+{
+
+ if (PyDec_Check(v)) {
+ *a = (PyDecObject *) v;
+ Py_INCREF(v);
+ }
+ else if (PyLong_Check(v)) {
+ if ((*a = (PyDecObject *) _PyDec_FromLong_Max(v, ctx)) == NULL) {
+ return 0;
+ }
+ }
+ else {
+ PyErr_Format(PyExc_TypeError, "conversion from %s to Decimal is"
+ " not supported", v->ob_type->tp_name);
+ return 0;
+ }
+
+ return 1;
+}
+
+#define CONVERT_OP_SET(v, a, ctx) \
+ if (!convert_op_set(v, a, ctx)) { \
+ return NULL; \
+ }
+
+#define CONVERT_BINOP_SET(v, w, a, b, ctx) \
+ if (!convert_op_set(v, a, ctx)) { \
+ return NULL; \
+ } \
+ if (!convert_op_set(w, b, ctx)) { \
+ Py_DECREF(*(a)); \
+ return NULL; \
+ }
+
+#define CONVERT_TERNOP_SET(v, w, x, a, b, c, ctx) \
+ if (!convert_op_set(v, a, ctx)) { \
+ return NULL; \
+ } \
+ if (!convert_op_set(w, b, ctx)) { \
+ Py_DECREF(*(a)); \
+ return NULL; \
+ } \
+ if (!convert_op_set(x, c, ctx)) { \
+ Py_DECREF(*(a)); \
+ Py_DECREF(*(b)); \
+ return NULL; \
+ }
+
+static PyObject *dec_subtype_new(PyTypeObject *type, PyObject *args,
+ PyObject *kwds);
+
+static PyObject *
+dec_new(PyTypeObject *type, PyObject *args, PyObject *kwds UNUSED)
+{
+ PyObject *v = NULL, *ctxobj = NULL;
+ mpd_context_t *ctx;
+
+ if (type != &PyDec_Type) {
+ return dec_subtype_new(type, args, kwds);
+ }
+
+ ctxobj = dflt_ctx();
+ if (!PyArg_ParseTuple(args, "|OO", &v, &ctxobj)) {
+ return NULL;
+ }
+
+ if (v == NULL) {
+ v = PyLong_FromLong(0);
+ }
+
+ CONTEXT_CHECK_VA(ctxobj);
+ ctx = CtxAddr(ctxobj);
+
+ if (PyDec_Check(v)) {
+ Py_INCREF(v);
+ return v;
+ }
+ else if (PyUnicode_Check(v)) {
+ return _PyDec_FromUnicode_Max(v, ctx);
+ }
+ else if (PyLong_Check(v)) {
+ return _PyDec_FromLong_Max(v, ctx);
+ }
+ else if (PyTuple_Check(v)) {
+ return _PyDec_FromTuple_Max(v, ctx);
+ }
+ else {
+ PyErr_Format(PyExc_TypeError, "conversion from %s to Decimal is"
+ " not supported", v->ob_type->tp_name);
+ return NULL;
+ }
+}
+
+static PyObject *
+dec_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
+{
+ PyObject *tmp, *newobj;
+
+ assert(PyType_IsSubtype(type, &PyDec_Type));
+ tmp = dec_new(&PyDec_Type, args, kwds);
+ if (tmp == NULL) {
+ return NULL;
+ }
+
+ newobj = type->tp_alloc(type, 0);
+ if (newobj == NULL) {
+ Py_DECREF(tmp);
+ return NULL;
+ }
+
+ DecAddr(newobj) = mpd_qncopy(DecAddr(tmp));
+ if (DecAddr(newobj) == NULL) {
+ PyErr_NoMemory();
+ Py_DECREF(tmp);
+ return NULL;
+ }
+
+ Py_DECREF(tmp);
+ return (PyObject *)newobj;
+}
+
+static PyObject *
+PyDecContext_CreateDecimal(PyObject *self, PyObject *args)
+{
+ PyObject *v = NULL;
+ mpd_context_t *ctx;
+
+ if (!PyArg_ParseTuple(args, "|O", &v)) {
+ return NULL;
+ }
+
+ if (v == NULL) {
+ v = PyLong_FromLong(0);
+ }
+
+ ctx = CtxAddr(self);
+
+ if (PyDec_Check(v)) {
+ return dec_apply(v, ctx);
+ }
+ else if (PyUnicode_Check(v)) {
+ return _PyDec_FromUnicode(v, ctx);
+ }
+ else if (PyLong_Check(v)) {
+ return _PyDec_FromLong(v, ctx);
+ }
+ else if (PyTuple_Check(v)) {
+ PyObject *tmp;
+ tmp = _PyDec_FromTuple_Max(v, ctx);
+ if (tmp == NULL) return NULL;
+ v = dec_apply(tmp, ctx);
+ Py_DECREF(tmp);
+ return v;
+ }
+ else {
+ PyErr_Format(PyExc_TypeError, "conversion from %s to Decimal is"
+ " not supported", v->ob_type->tp_name);
+ return NULL;
+ }
+}
+
+static PyObject *
+_PyDec_FromFloat_Max(PyObject *self, PyObject *v)
+{
+ PyObject *result, *tmp;
+ PyObject *n, *d, *n_d;
+ mpd_ssize_t k;
+ double x;
+ int sign;
+ mpd_t *d1, *d2;
+ uint32_t status = 0;
+ mpd_context_t maxctx;
+
+
+ if (PyLong_Check(v)) {
+ return _PyDec_FromLong_Max(v, mpd_ctx());
+ }
+
+ x = PyFloat_AsDouble(v);
+ if (x == -1.0 && PyErr_Occurred()) {
+ return NULL;
+ }
+ sign = (copysign(1.0, x) == 1.0) ? 0 : 1;
+
+ if (Py_IS_NAN(x) || Py_IS_INFINITY(x)) {
+ result = PyObject_CallObject(self, NULL);
+ if (result == NULL) {
+ return NULL;
+ }
+ if (Py_IS_NAN(x)) {
+ /* decimal.py calls repr(float(+-nan)),
+ * which always gives a positive result */
+ mpd_setspecial(DecAddr(result), MPD_POS, MPD_NAN);
+ }
+ else {
+ mpd_setspecial(DecAddr(result), sign, MPD_INF);
+ }
+ return result;
+ }
+
+ if ((tmp = PyObject_CallMethod(v, "__abs__", NULL)) == NULL) {
+ return NULL;
+ }
+ n_d = PyObject_CallMethod(tmp, "as_integer_ratio", NULL);
+ Py_DECREF(tmp);
+ if (n_d == NULL) {
+ return NULL;
+ }
+ if ((n = PyTuple_GetItem(n_d, 0)) == NULL) {
+ Py_DECREF(n_d);
+ return NULL;
+ }
+ if ((d = PyTuple_GetItem(n_d, 1)) == NULL) {
+ Py_DECREF(n_d);
+ return NULL;
+ }
+
+
+ if ((tmp = PyObject_CallMethod(d, "bit_length", NULL)) == NULL) {
+ Py_DECREF(n_d);
+ return NULL;
+ }
+ k = PyLong_AsMpdSsize(tmp);
+ Py_DECREF(tmp);
+ if (k == MPD_SSIZE_MAX) {
+ Py_DECREF(n_d);
+ return NULL;
+ }
+ k--;
+
+ if ((d1 = mpd_qnew()) == NULL) {
+ Py_DECREF(n_d);
+ return NULL;
+ }
+ if ((d2 = mpd_qnew()) == NULL) {
+ mpd_del(d1);
+ Py_DECREF(n_d);
+ return NULL;
+ }
+
+ mpd_maxcontext(&maxctx);
+ mpd_qset_uint(d1, 5, &maxctx, &status);
+ mpd_qset_ssize(d2, k, &maxctx, &status);
+ mpd_qpow(d1, d1, d2, &maxctx, &status);
+ if (dec_addstatus(mpd_ctx(), status)) {
+ mpd_del(d1);
+ mpd_del(d2);
+ Py_DECREF(n_d);
+ return NULL;
+ }
+
+ tmp = Py_BuildValue("(O)", n);
+ result = PyObject_CallObject(self, tmp);
+ Py_DECREF(tmp);
+ Py_DECREF(n_d);
+ if (result == NULL) {
+ mpd_del(d1);
+ mpd_del(d2);
+ return NULL;
+ }
+
+ /* result = n * 5**k */
+ mpd_qmul(DecAddr(result), DecAddr(result), d1, &maxctx, &status);
+ mpd_del(d1);
+ mpd_del(d2);
+ if (dec_addstatus(mpd_ctx(), status)) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ /* result = +- n * 5**k * 10**-k */
+ mpd_set_sign(DecAddr(result), sign);
+ DecAddr(result)->exp = -k;
+
+ return result;
+}
+
+static PyObject *
+PyDecContext_FromFloat(PyObject *self, PyObject *v)
+{
+ PyObject *result;
+ mpd_context_t *ctx;
+ uint32_t status = 0;
+
+ ctx = CtxAddr(self);
+
+ result = _PyDec_FromFloat_Max((PyObject *)&PyDec_Type, v);
+ if (result == NULL) {
+ return NULL;
+ }
+
+ mpd_qfinalize(DecAddr(result), ctx, &status);
+ if (dec_addstatus(ctx, status)) {
+ Py_DECREF(result);
+ return NULL;
+ }
+
+ return result;
+}
+
+
+/*******************************************************/
+/* Conversions from decimal */
+/*******************************************************/
+
+/* Caller guarantees type. Uses default module context. */
+static PyObject *
+_PyInt_FromDec(PyDecObject *self, mpd_context_t *ctx, int round)
+{
+ PyLongObject *newob;
+ mpd_t *intdec;
+ size_t maxsize, n;
+ Py_ssize_t i;
+ mpd_context_t workctx;
+ uint32_t status = 0;
+
+ if (mpd_isspecial(self->dec)) {
+ if (mpd_isnan(self->dec)) {
+ PyErr_SetString(PyExc_ValueError,
+ "cannot convert NaN to integer");
+ }
+ else {
+ PyErr_SetString(PyExc_OverflowError,
+ "cannot convert Infinity to integer");
+ }
+ return NULL;
+ }
+
+ if ((intdec = mpd_qnew()) == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+ workctx = *ctx;
+ workctx.round = round;
+ mpd_qround_to_int(intdec, self->dec, &workctx, &status);
+ if (dec_addstatus(ctx, status)) {
+ mpd_del(intdec);
+ return NULL;
+ }
+
+ maxsize = mpd_sizeinbase(intdec, PyLong_BASE);
+ if (maxsize > PY_SSIZE_T_MAX) {
+ PyErr_NoMemory();
+ mpd_del(intdec);
+ return NULL;
+ }
+ if ((newob = _PyLong_New(maxsize)) == NULL) {
+ mpd_del(intdec);
+ return NULL;
+ }
+
+ status = 0;
+#if PYLONG_BITS_IN_DIGIT == 30
+ n = mpd_qexport_u32(newob->ob_digit, maxsize, PyLong_BASE, intdec, &status);
+#elif PYLONG_BITS_IN_DIGIT == 15
+ n = mpd_qexport_u16(newob->ob_digit, maxsize, PyLong_BASE, intdec, &status);
+#else
+ #error "PYLONG_BITS_IN_DIGIT should be 15 or 30"
+#endif
+ if (dec_addstatus(ctx, status)) {
+ Py_DECREF((PyObject *) newob);
+ mpd_del(intdec);
+ return NULL;
+ }
+
+ i = n;
+ while ((i > 0) && (newob->ob_digit[i-1] == 0)) {
+ i--;
+ }
+
+ Py_SIZE(newob) = i;
+ if (mpd_isnegative(intdec) && !mpd_iszero(intdec)) {
+ Py_SIZE(newob) = -i;
+ }
+
+ mpd_del(intdec);
+ return (PyObject *) newob;
+}
+
+static PyObject *
+PyLong_FromDec(PyDecObject *self)
+{
+ return _PyInt_FromDec(self, mpd_ctx(), MPD_ROUND_DOWN);
+}
+
+/* Caller guarantees type */
+static PyObject *
+PyLong_FromDecCtx(PyDecObject *self, mpd_context_t *ctx)
+{
+ return _PyInt_FromDec(self, ctx, MPD_ROUND_DOWN);
+}
+
+/* Caller guarantees type. Uses default module context. */
+static PyObject *
+PyDec_Trunc(PyObject *self, PyObject *dummy UNUSED)
+{
+ return _PyInt_FromDec((PyDecObject *)self, mpd_ctx(), MPD_ROUND_DOWN);
+}
+
+static PyObject *
+PyDec_ToIntegralValue(PyObject *self, PyObject *args, PyObject *kwds)
+{
+ static char *kwlist[] = {"rounding", "context", NULL};
+ PyDecObject *result;
+ PyObject *dctx;
+ int round = -1;
+ mpd_context_t *ctx, workctx;
+ uint32_t status = 0;
+
+ assert(PyTuple_Check(args));
+ dctx = dflt_ctx();
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO",
+ kwlist, &round, &dctx)) {
+ return NULL;
+ }
+ if (!PyDecContext_Check(dctx)) {
+ PyErr_SetString(PyExc_ValueError,
+ "optional second arg must be a context");
+ return NULL;
+ }
+ if ((result = dec_alloc()) == NULL) {
+ return NULL;
+ }
+
+ ctx = CtxAddr(dctx);
+ workctx = *ctx;
+ if (round >= 0) {
+ workctx.round = round;
+ }
+
+ mpd_qround_to_int(result->dec, DecAddr(self), &workctx, &status);
+ if (dec_addstatus(ctx, status)) {
+ Py_DECREF(result);
+ return NULL;
+ }
+
+ return (PyObject *)result;
+}
+
+static PyObject *
+PyDec_ToIntegralExact(PyObject *self, PyObject *args, PyObject *kwds)
+{
+ static char *kwlist[] = {"rounding", "context", NULL};
+ PyDecObject *result;
+ PyObject *dctx;
+ int round = -1;
+ mpd_context_t *ctx, workctx;
+ uint32_t status = 0;
+
+ assert(PyTuple_Check(args));
+ dctx = dflt_ctx();
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO",
+ kwlist, &round, &dctx)) {
+ return NULL;
+ }
+ if (!PyDecContext_Check(dctx)) {
+ PyErr_SetString(PyExc_ValueError,
+ "optional second arg must be a context");
+ return NULL;
+ }
+ if ((result = dec_alloc()) == NULL) {
+ return NULL;
+ }
+
+ ctx = CtxAddr(dctx);
+ workctx = *ctx;
+ if (round >= 0) {
+ workctx.round = round;
+ }
+
+ mpd_qround_to_intx(result->dec, DecAddr(self), &workctx, &status);
+ if (dec_addstatus(ctx, status)) {
+ Py_DECREF(result);
+ return NULL;
+ }
+
+ return (PyObject *)result;
+}
+
+/* Caller guarantees type */
+static PyObject *
+PyDec_AsTuple(PyObject *self, PyObject *dummy UNUSED)
+{
+ PyObject *o_sign = NULL;
+ PyObject *o_coeff = NULL;
+ PyObject *o_exp = NULL;
+ PyObject *o_tuple = NULL;
+ PyObject *tmp = NULL;
+ mpd_t *selfcpy = NULL;
+ char *intstring = NULL;
+ Py_ssize_t intlen, i;
+
+
+ if ((selfcpy = mpd_qncopy(DecAddr(self))) == NULL) {
+ PyErr_NoMemory();
+ goto error;
+ }
+
+ o_sign = Py_BuildValue("i", mpd_sign(DecAddr(self)));
+ if (o_sign == NULL) goto error;
+
+ if (mpd_isinfinite(selfcpy)) {
+ if ((o_exp = Py_BuildValue("s", "F")) == NULL) {
+ goto error;
+ }
+ if ((o_coeff = PyTuple_New(0)) == NULL) {
+ goto error;
+ }
+ }
+ else {
+ if (mpd_isnan(selfcpy)) {
+ o_exp = Py_BuildValue("s",
+ mpd_isqnan(selfcpy)?"n":"N");
+ }
+ else {
+ o_exp = Py_BuildValue(CONV_mpd_ssize_t,
+ DecAddr(self)->exp);
+ }
+ if (o_exp == NULL) goto error;
+
+ /* coefficient is defined */
+ if (selfcpy->len > 0) {
+
+ /* make an integer */
+ selfcpy->exp = 0;
+ /* clear NaN and sign */
+ mpd_clear_flags(selfcpy);
+ intstring = mpd_to_sci(selfcpy, 1);
+ if (intstring == NULL) {
+ PyErr_NoMemory();
+ goto error;
+ }
+
+ intlen = strlen(intstring);
+ if ((o_coeff = PyTuple_New(intlen)) == NULL) {
+ goto error;
+ }
+
+ for (i = 0; i < intlen; i++) {
+ tmp = Py_BuildValue("i", intstring[i]-'0');
+ if (tmp == NULL) goto error;
+ PyTuple_SET_ITEM(o_coeff, i, tmp);
+ }
+ }
+ else {
+ if ((o_coeff = PyTuple_New(0)) == NULL) {
+ goto error;
+ }
+ }
+ }
+
+ if ((o_tuple = PyTuple_New(3)) == NULL) {
+ goto error;
+ }
+ PyTuple_SET_ITEM(o_tuple, 0, o_sign);
+ PyTuple_SET_ITEM(o_tuple, 1, o_coeff);
+ PyTuple_SET_ITEM(o_tuple, 2, o_exp);
+
+
+out:
+ if (selfcpy) mpd_del(selfcpy);
+ if (intstring) mpd_free(intstring);
+ return o_tuple;
+
+error:
+ if (o_sign) { Py_DECREF(o_sign); }
+ if (o_coeff) { Py_DECREF(o_coeff); }
+ if (o_exp) { Py_DECREF(o_exp); }
+ goto out;
+}
+
+/* Caller guarantees type. Uses default module context. */
+static PyObject *
+dec_str(PyDecObject *self)
+{
+ PyObject *s, *c;
+ char *res;
+
+ c = dflt_ctx();
+ res = mpd_to_sci(self->dec, ((PyDecContextObject *)c)->capitals);
+ if (res == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+
+ s = PyUnicode_FromString(res);
+ mpd_free(res);
+
+ return s;
+}
+
+static const char *dtag = "Decimal('";
+static const size_t dtaglen = 9; /* without NUL terminator */
+
+/* Caller guarantees type. Uses default module context. */
+static PyObject *
+dec_repr(PyDecObject *self)
+{
+ PyObject *s, *c;
+ uint8_t err;
+ char *cp;
+ size_t declen;
+
+ c = dflt_ctx();
+ cp = mpd_to_sci(self->dec, ((PyDecContextObject *)c)->capitals);
+ if (cp == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+ declen = strlen(cp);
+
+ err = 0;
+ cp = mpd_realloc(cp, declen+dtaglen+3, sizeof *cp, &err);
+ if (err) {
+ mpd_free(cp);
+ PyErr_NoMemory();
+ return NULL;
+ }
+
+ memmove(cp+dtaglen, cp, declen);
+ memcpy(cp, dtag, dtaglen);
+ cp[declen+dtaglen] = '\'';
+ cp[declen+dtaglen+1] = ')';
+ cp[declen+dtaglen+2] = '\0';
+
+ s = PyUnicode_FromString(cp);
+
+ mpd_free(cp);
+ return s;
+}
+
+/* Caller guarantees type. Uses default module context. */
+static PyObject *
+PyFloat_FromDec(PyDecObject *self)
+{
+ PyObject *f, *s;
+
+ if ((s = dec_str(self)) == NULL) {
+ return NULL;
+ }
+
+ f = PyFloat_FromString(s);
+ Py_DECREF(s);
+
+ return f;
+}
+
+static PyObject *
+PyDec_Round(PyObject *self, PyObject *args)
+{
+ PyDecObject *a = (PyDecObject *)self;
+ PyDecObject *result;
+ PyObject *x = NULL;
+ mpd_uint_t dq[1] = {1};
+ mpd_t q = {MPD_STATIC|MPD_CONST_DATA,0,1,1,1,dq};
+ uint32_t status = 0;
+ mpd_context_t *ctx;
+
+ if (!PyArg_ParseTuple(args, "|O", &x)) {
+ return NULL;
+ }
+
+ ctx = mpd_ctx();
+
+ if (x) {
+ if (!PyLong_Check(x)) {
+ PyErr_SetString(PyExc_ValueError, "optional arg must be an integer");
+ return NULL;
+ }
+ if ((result = dec_alloc()) == NULL) {
+ return NULL;
+ }
+
+ q.exp = -_PyLong_AsMpdSsize(x);
+ mpd_qquantize(result->dec, a->dec, &q, ctx, &status);
+ if (dec_addstatus(ctx, status)) {
+ Py_DECREF(result);
+ return NULL;
+ }
+
+ return (PyObject *)result;
+ }
+ else {
+ return _PyInt_FromDec(a, ctx, MPD_ROUND_HALF_EVEN);
+ }
+}
+
+static PyObject *
+dec_format(PyObject *self, PyObject *args)
+{
+ PyObject *result = NULL;
+ PyObject *override = NULL;
+ PyObject *dot = NULL;
+ PyObject *sep = NULL;
+ PyObject *grouping = NULL;
+ PyObject *fmtarg, *fmt;
+ PyObject *tmp;
+ mpd_spec_t spec;
+ wchar_t buf[2];
+ char *decstring= NULL;
+ uint32_t status = 0;
+ size_t n;
+
+
+ if (!PyArg_ParseTuple(args, "O|O", &fmtarg, &override)) {
+ return NULL;
+ }
+
+ if (PyBytes_Check(fmtarg)) {
+ fmt = fmtarg;
+ }
+ else if (PyUnicode_Check(fmtarg)) {
+ if ((fmt = PyUnicode_AsUTF8String(fmtarg)) == NULL) {
+ return NULL;
+ }
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError, "format requires bytes or "
+ "unicode arg");
+ return NULL;
+ }
+
+ if (!mpd_parse_fmt_str(&spec, PyBytes_AS_STRING(fmt))) {
+ PyErr_SetString(PyExc_ValueError, "invalid format string");
+ goto finish;
+ }
+ if (override) {
+ if (!PyDict_Check(override)) {
+ PyErr_SetString(PyExc_ValueError, "optional argument "
+ "must be a dict");
+ goto finish;
+ }
+ if ((dot = PyDict_GetItemString(override, "decimal_point"))) {
+ if ((dot = PyUnicode_AsUTF8String(dot)) == NULL) {
+ goto finish;
+ }
+ spec.dot = PyBytes_AS_STRING(dot);
+ }
+ if ((sep = PyDict_GetItemString(override, "thousands_sep"))) {
+ if ((sep = PyUnicode_AsUTF8String(sep)) == NULL) {
+ goto finish;
+ }
+ spec.sep = PyBytes_AS_STRING(sep);
+ }
+ if ((grouping = PyDict_GetItemString(override, "grouping"))) {
+ if ((grouping = PyUnicode_AsUTF8String(grouping)) == NULL) {
+ goto finish;
+ }
+ spec.grouping = PyBytes_AS_STRING(grouping);
+ }
+ }
+ else {
+ n = strlen(spec.dot);
+ if (n > 1 || (n == 1 && !isascii((uchar)spec.dot[0]))) {
+ n = mbstowcs(buf, spec.dot, 2);
+ if (n != 1) {
+ PyErr_SetString(PyExc_ValueError,
+ "invalid decimal point or unsupported "
+ "combination of LC_CTYPE and LC_NUMERIC");
+ goto finish;
+ }
+ if ((tmp = PyUnicode_FromWideChar(buf, n)) == NULL) {
+ goto finish;
+ }
+ if ((dot = PyUnicode_AsUTF8String(tmp)) == NULL) {
+ Py_DECREF(tmp);
+ goto finish;
+ }
+ spec.dot = PyBytes_AS_STRING(dot);
+ Py_DECREF(tmp);
+ }
+ n = strlen(spec.sep);
+ if (n > 1 || (n == 1 && !isascii((uchar)spec.sep[0]))) {
+ n = mbstowcs(buf, spec.sep, 2);
+ if (n != 1) {
+ PyErr_SetString(PyExc_ValueError,
+ "invalid thousands separator or unsupported "
+ "combination of LC_CTYPE and LC_NUMERIC");
+ goto finish;
+ }
+ if ((tmp = PyUnicode_FromWideChar(buf, n)) == NULL) {
+ goto finish;
+ }
+ if ((sep = PyUnicode_AsUTF8String(tmp)) == NULL) {
+ Py_DECREF(tmp);
+ goto finish;
+ }
+ spec.sep = PyBytes_AS_STRING(sep);
+ Py_DECREF(tmp);
+ }
+ }
+
+
+ decstring = mpd_qformat_spec(DecAddr(self), &spec, mpd_ctx(), &status);
+ if (decstring == NULL) {
+ dec_addstatus(mpd_ctx(), status);
+ goto finish;
+ }
+ result = PyUnicode_DecodeUTF8(decstring, strlen(decstring), NULL);
+
+
+finish:
+ if (grouping) { Py_DECREF(grouping); }
+ if (sep) { Py_DECREF(sep); }
+ if (dot) { Py_DECREF(dot); }
+ if (decstring) mpd_free(decstring);
+ if (fmt != fmtarg) { Py_DECREF(fmt); }
+ return result;
+}
+
+
+/********************************************************************/
+/* Macros for converting mpdecimal functions to Decimal methods */
+/********************************************************************/
+
+/* The operand is guaranteed to be a PyDecObject. */
+#define _Dec_BoolFunc(MPDFUNC) \
+static PyObject * \
+_Dec_##MPDFUNC(PyObject *self) \
+{ \
+ PyDecObject *a = (PyDecObject *) self; \
+ return MPDFUNC(a->dec) ? Dec_INCREF_TRUE : Dec_INCREF_FALSE; \
+}
+
+/* The operand is guaranteed to be a PyDecObject. */
+#define _Dec_BoolCFunc(MPDFUNC) \
+static PyObject * \
+_Dec_CFunc_##MPDFUNC(PyObject *self, PyObject *dummy UNUSED) \
+{ \
+ PyDecObject *a = (PyDecObject *) self; \
+ return MPDFUNC(a->dec) ? Dec_INCREF_TRUE : Dec_INCREF_FALSE; \
+}
+
+/* Operand is a PyDecObject. Uses optional context if supplied.
+ * MPDFUNC uses a const context and does not raise. */
+#define _DecOpt_BoolFunc(MPDFUNC) \
+static PyObject * \
+_DecOpt_##MPDFUNC(PyObject *self, PyObject *args) \
+{ \
+ PyDecObject *a = (PyDecObject *) self; \
+ PyObject *ctxobj; \
+ mpd_context_t *ctx; \
+ \
+ ctxobj = dflt_ctx(); \
+ if (!PyArg_ParseTuple(args, "|O", &ctxobj)) { \
+ return NULL; \
+ } \
+ \
+ CONTEXT_CHECK_VA(ctxobj); \
+ ctx = CtxAddr(ctxobj); \
+ \
+ return MPDFUNC(a->dec, ctx) ? Dec_INCREF_TRUE : Dec_INCREF_FALSE; \
+}
+
+/* Operand is a PyDecObject. Uses the default module context.
+ * MPDFUNC is a quiet function. */
+#define _Dec_UnaryFunc(MPDFUNC) \
+static PyObject * \
+_Dec_##MPDFUNC(PyObject *self) \
+{ \
+ PyDecObject *a = (PyDecObject *) self; \
+ PyDecObject *result; \
+ uint32_t status = 0; \
+ mpd_context_t *ctx; \
+ \
+ if ((result = dec_alloc()) == NULL) { \
+ return NULL; \
+ } \
+ \
+ ctx = mpd_ctx(); \
+ MPDFUNC(result->dec, a->dec, ctx, &status); \
+ if (dec_addstatus(ctx, status)) { \
+ Py_DECREF(result); \
+ return NULL; \
+ } \
+ \
+ return (PyObject *) result; \
+}
+
+/* Operand is a PyDecObject. Uses the default module context.
+ * MPDFUNC is a quiet function. */
+#define _Dec_UnaryCFunc(MPDFUNC) \
+static PyObject * \
+_Dec_CFunc_##MPDFUNC(PyObject *self, PyObject *dummy UNUSED) \
+{ \
+ PyDecObject *a = (PyDecObject *) self; \
+ PyDecObject *result; \
+ uint32_t status = 0; \
+ mpd_context_t *ctx; \
+ \
+ if ((result = dec_alloc()) == NULL) { \
+ return NULL; \
+ } \
+ \
+ ctx = mpd_ctx(); \
+ MPDFUNC(result->dec, a->dec, ctx, &status); \
+ if (dec_addstatus(ctx, &status)) { \
+ Py_DECREF(result); \
+ return NULL; \
+ } \
+ \
+ return (PyObject *) result; \
+}
+
+/* Operand is a PyDecObject. Uses optional context if supplied.
+ * MPDFUNC is a quiet function. */
+#define _DecOpt_UnaryFunc(MPDFUNC) \
+static PyObject * \
+_DecOpt_##MPDFUNC(PyObject *self, PyObject *args) \
+{ \
+ PyDecObject *a = (PyDecObject *) self; \
+ PyDecObject *result; \
+ PyObject *ctxobj; \
+ uint32_t status = 0; \
+ mpd_context_t *ctx; \
+ \
+ ctxobj = dflt_ctx(); \
+ if (!PyArg_ParseTuple(args, "|O", &ctxobj)) { \
+ return NULL; \
+ } \
+ \
+ CONTEXT_CHECK_VA(ctxobj); \
+ ctx = CtxAddr(ctxobj); \
+ \
+ if ((result = dec_alloc()) == NULL) { \
+ return NULL; \
+ } \
+ \
+ MPDFUNC(result->dec, a->dec, ctx, &status); \
+ if (dec_addstatus(ctx, status)) { \
+ Py_DECREF(result); \
+ return NULL; \
+ } \
+ \
+ return (PyObject *) result; \
+}
+
+
+/* Operands are Python Objects. Uses default module context.
+ * MPDFUNC is a quiet function. */
+#define _Dec_BinaryFunc(MPDFUNC) \
+static PyObject * \
+_Dec_##MPDFUNC(PyObject *v, PyObject *w) \
+{ \
+ PyDecObject *a, *b; \
+ PyDecObject *result; \
+ uint32_t status = 0; \
+ mpd_context_t *ctx; \
+ \
+ ctx = mpd_ctx(); \
+ CONVERT_BINOP(v, w, &a, &b, ctx); \
+ \
+ if ((result = dec_alloc()) == NULL) { \
+ Py_DECREF(a); \
+ Py_DECREF(b); \
+ return NULL; \
+ } \
+ \
+ MPDFUNC(result->dec, a->dec, b->dec, ctx, &status); \
+ Py_DECREF(a); \
+ Py_DECREF(b); \
+ if (dec_addstatus(ctx, status)) { \
+ Py_DECREF(result); \
+ return NULL; \
+ } \
+ \
+ return (PyObject *) result; \
+}
+
+/* Operands are Python Objects. Uses optional context if supplied.
+ * MPDFUNC is a quiet function. */
+#define _DecOpt_BinaryFunc(MPDFUNC) \
+static PyObject * \
+_DecOpt_##MPDFUNC(PyObject *v, PyObject *args) \
+{ \
+ PyObject *w, *ctxobj; \
+ PyDecObject *a, *b; \
+ PyDecObject *result; \
+ uint32_t status = 0; \
+ mpd_context_t *ctx; \
+ \
+ ctxobj = dflt_ctx(); \
+ if (!PyArg_ParseTuple(args, "O|O", &w, &ctxobj)) { \
+ return NULL; \
+ } \
+ \
+ CONTEXT_CHECK_VA(ctxobj); \
+ ctx = CtxAddr(ctxobj); \
+ \
+ CONVERT_BINOP_SET(v, w, &a, &b, ctx); \
+ \
+ if ((result = dec_alloc()) == NULL) { \
+ Py_DECREF(a); \
+ Py_DECREF(b); \
+ return NULL; \
+ } \
+ \
+ MPDFUNC(result->dec, a->dec, b->dec, ctx, &status); \
+ Py_DECREF(a); \
+ Py_DECREF(b); \
+ if (dec_addstatus(ctx, status)) { \
+ Py_DECREF(result); \
+ return NULL; \
+ } \
+ \
+ return (PyObject *) result; \
+}
+
+/* Operands are Python Objects. Actual MPDFUNC does NOT take a context.
+ * Uses optional context for conversion only. */
+#define _DecOpt_BinaryFunc_NoCtx(MPDFUNC) \
+static PyObject * \
+_DecOpt_##MPDFUNC(PyObject *v, PyObject *args) \
+{ \
+ PyObject *w, *ctxobj; \
+ PyDecObject *a, *b; \
+ PyDecObject *result; \
+ mpd_context_t *ctx; \
+ \
+ ctxobj = dflt_ctx(); \
+ if (!PyArg_ParseTuple(args, "O|O", &w, &ctxobj)) { \
+ return NULL; \
+ } \
+ \
+ CONTEXT_CHECK_VA(ctxobj); \
+ ctx = CtxAddr(ctxobj); \
+ \
+ CONVERT_BINOP_SET(v, w, &a, &b, ctx); \
+ \
+ if ((result = dec_alloc()) == NULL) { \
+ Py_DECREF(a); \
+ Py_DECREF(b); \
+ return NULL; \
+ } \
+ \
+ MPDFUNC(result->dec, a->dec, b->dec); \
+ Py_DECREF(a); \
+ Py_DECREF(b); \
+ \
+ return (PyObject *) result; \
+}
+
+
+/* Operands are Python Objects. Uses optional context if supplied.
+ * MPDFUNC is a quiet function. */
+#define _DecOpt_TernaryFunc(MPDFUNC) \
+static PyObject * \
+_DecOpt_##MPDFUNC(PyObject *v, PyObject *args) \
+{ \
+ PyObject *w, *x, *ctxobj; \
+ PyDecObject *a, *b, *c; \
+ PyDecObject *result; \
+ uint32_t status = 0; \
+ mpd_context_t *ctx; \
+ \
+ ctxobj = dflt_ctx(); \
+ if (!PyArg_ParseTuple(args, "OO|O", &w, &x, &ctxobj)) { \
+ return NULL; \
+ } \
+ \
+ CONTEXT_CHECK_VA(ctxobj); \
+ ctx = CtxAddr(ctxobj); \
+ \
+ CONVERT_TERNOP_SET(v, w, x, &a, &b, &c, ctx); \
+ \
+ if ((result = dec_alloc()) == NULL) { \
+ Py_DECREF(a); \
+ Py_DECREF(b); \
+ Py_DECREF(c); \
+ return NULL; \
+ } \
+ \
+ MPDFUNC(result->dec, a->dec, b->dec, c->dec, ctx, &status); \
+ Py_DECREF(a); \
+ Py_DECREF(b); \
+ Py_DECREF(c); \
+ if (dec_addstatus(ctx, status)) { \
+ Py_DECREF(result); \
+ return NULL; \
+ } \
+ \
+ return (PyObject *) result; \
+}
+
+
+/**********************************************/
+/* Number methods */
+/**********************************************/
+
+_Dec_UnaryFunc(mpd_qminus)
+_Dec_UnaryFunc(mpd_qplus)
+_Dec_UnaryFunc(mpd_qabs)
+
+static PyObject *
+_Dec_mpd_adjexp(PyObject *self, PyObject *dummy UNUSED)
+{
+ mpd_ssize_t retval;
+
+ if (mpd_isspecial(DecAddr(self))) {
+ retval = 0;
+ }
+ else {
+ retval = mpd_adjexp(DecAddr(self));
+ }
+
+ return _PyLong_FromMpdSsize(retval);
+}
+
+_Dec_BinaryFunc(mpd_qadd)
+_Dec_BinaryFunc(mpd_qsub)
+_Dec_BinaryFunc(mpd_qmul)
+_Dec_BinaryFunc(mpd_qdiv)
+_Dec_BinaryFunc(mpd_qrem)
+_Dec_BinaryFunc(mpd_qdivint)
+
+static int
+_Dec_nonzero(PyDecObject *v)
+{
+ return !mpd_iszero(v->dec);
+}
+
+static PyObject *
+_Dec_mpd_qdivmod(PyObject *v, PyObject *w)
+{
+ PyDecObject *a, *b;
+ PyDecObject *q, *r;
+ uint32_t status = 0;
+ mpd_context_t *ctx;
+
+ ctx = mpd_ctx();
+ CONVERT_BINOP(v, w, &a, &b, ctx);
+
+ if ((q = dec_alloc()) == NULL) {
+ Py_DECREF(a);
+ Py_DECREF(b);
+ return NULL;
+ }
+ if ((r = dec_alloc()) == NULL) {
+ Py_DECREF(a);
+ Py_DECREF(b);
+ Py_DECREF(q);
+ return NULL;
+ }
+
+ mpd_qdivmod(q->dec, r->dec, a->dec, b->dec, ctx, &status);
+ Py_DECREF(a);
+ Py_DECREF(b);
+ if (dec_addstatus(ctx, status)) {
+ Py_DECREF(r);
+ Py_DECREF(q);
+ return NULL;
+ }
+
+ return Py_BuildValue("(NN)", q, r);
+}
+
+static PyObject *
+_Dec_mpd_qpow(PyObject *base, PyObject *exp, PyObject *mod)
+{
+ PyDecObject *a, *b, *c = NULL;
+ PyDecObject *result;
+ uint32_t status = 0;
+ mpd_context_t *ctx;
+
+ ctx = mpd_ctx();
+ CONVERT_BINOP(base, exp, &a, &b, ctx);
+
+ if (mod != Py_None) {
+ if (!convert_op(mod, &c, ctx)) {
+ Py_DECREF(a);
+ Py_DECREF(b);
+ return (PyObject *) c;
+ }
+ }
+
+ if ((result = dec_alloc()) == NULL) {
+ return NULL;
+ }
+
+ if (c == NULL) {
+ mpd_qpow(result->dec, a->dec, b->dec, ctx, &status);
+ }
+ else {
+ mpd_qpowmod(result->dec, a->dec, b->dec, c->dec, ctx, &status);
+ Py_DECREF(c);
+ }
+ Py_DECREF(a);
+ Py_DECREF(b);
+ if (dec_addstatus(ctx, status)) {
+ Py_DECREF(result);
+ return NULL;
+ }
+
+ return (PyObject *) result;
+}
+
+
+/******************************************************************************/
+/* Decimal Methods */
+/******************************************************************************/
+
+
+/* Arithmetic operations */
+_DecOpt_UnaryFunc(mpd_qabs)
+_DecOpt_UnaryFunc(mpd_qexp)
+_DecOpt_UnaryFunc(mpd_qinvroot)
+_DecOpt_UnaryFunc(mpd_qln)
+_DecOpt_UnaryFunc(mpd_qlog10)
+_DecOpt_UnaryFunc(mpd_qminus)
+_DecOpt_UnaryFunc(mpd_qnext_minus)
+_DecOpt_UnaryFunc(mpd_qnext_plus)
+_DecOpt_UnaryFunc(mpd_qplus)
+_DecOpt_UnaryFunc(mpd_qreduce)
+_DecOpt_UnaryFunc(mpd_qsqrt)
+
+_DecOpt_BinaryFunc(mpd_qadd)
+_DecOpt_BinaryFunc(mpd_qcompare)
+_DecOpt_BinaryFunc(mpd_qcompare_signal)
+_DecOpt_BinaryFunc(mpd_qdiv)
+_DecOpt_BinaryFunc(mpd_qdivint)
+_DecOpt_BinaryFunc(mpd_qmax)
+_DecOpt_BinaryFunc(mpd_qmax_mag)
+_DecOpt_BinaryFunc(mpd_qmin)
+_DecOpt_BinaryFunc(mpd_qmin_mag)
+_DecOpt_BinaryFunc(mpd_qmul)
+_DecOpt_BinaryFunc(mpd_qnext_toward)
+_DecOpt_BinaryFunc(mpd_qpow)
+_DecOpt_BinaryFunc(mpd_qquantize)
+_DecOpt_BinaryFunc(mpd_qrem)
+_DecOpt_BinaryFunc(mpd_qrem_near)
+_DecOpt_BinaryFunc(mpd_qsub)
+
+_DecOpt_TernaryFunc(mpd_qfma)
+_DecOpt_TernaryFunc(mpd_qpowmod)
+
+/* Miscellaneous */
+_Dec_BoolCFunc(mpd_iscanonical)
+_Dec_BoolCFunc(mpd_isfinite)
+_Dec_BoolCFunc(mpd_isinfinite)
+_Dec_BoolCFunc(mpd_isinteger)
+_Dec_BoolCFunc(mpd_isnan)
+_Dec_BoolCFunc(mpd_isqnan)
+_Dec_BoolCFunc(mpd_issnan)
+_Dec_BoolCFunc(mpd_issigned)
+_Dec_BoolCFunc(mpd_isspecial)
+_Dec_BoolCFunc(mpd_iszero)
+
+_DecOpt_BoolFunc(mpd_isnormal)
+_DecOpt_BoolFunc(mpd_issubnormal)
+
+static PyObject *
+_Dec_mpd_qcopy_abs(PyObject *self, PyObject *dummy UNUSED)
+{
+ PyDecObject *a = (PyDecObject *) self;
+ PyDecObject *result;
+ uint32_t status = 0;
+
+ if ((result = dec_alloc()) == NULL) {
+ return NULL;
+ }
+
+ mpd_qcopy_abs(result->dec, a->dec, &status);
+ if (dec_addstatus(mpd_ctx(), status)) {
+ Py_DECREF(result);
+ return NULL;
+ }
+
+ return (PyObject *) result;
+}
+
+static PyObject *
+_Dec_mpd_qcopy_negate(PyObject *self, PyObject *dummy UNUSED)
+{
+ PyDecObject *a = (PyDecObject *) self;
+ PyDecObject *result;
+ uint32_t status = 0;
+
+ if ((result = dec_alloc()) == NULL) {
+ return NULL;
+ }
+
+ mpd_qcopy_negate(result->dec, a->dec, &status);
+ if (dec_addstatus(mpd_ctx(), status)) {
+ Py_DECREF(result);
+ return NULL;
+ }
+
+ return (PyObject *) result;
+}
+
+_DecOpt_UnaryFunc(mpd_qinvert)
+_DecOpt_UnaryFunc(mpd_qlogb)
+
+_DecOpt_BinaryFunc_NoCtx(mpd_compare_total)
+_DecOpt_BinaryFunc_NoCtx(mpd_compare_total_mag)
+
+static PyObject *
+_Dec_mpd_qcopy_sign(PyObject *v, PyObject *w)
+{
+ PyDecObject *a, *b;
+ PyDecObject *result;
+ uint32_t status = 0;
+ mpd_context_t *ctx;
+
+ ctx = mpd_ctx();
+ CONVERT_BINOP(v, w, &a, &b, ctx);
+
+ if ((result = dec_alloc()) == NULL) {
+ Py_DECREF(a);
+ Py_DECREF(b);
+ return NULL;
+ }
+
+ mpd_qcopy_sign(result->dec, a->dec, b->dec, &status);
+ Py_DECREF(a);
+ Py_DECREF(b);
+ if (dec_addstatus(ctx, status)) {
+ Py_DECREF(result);
+ return NULL;
+ }
+
+ return (PyObject *) result;
+}
+
+_DecOpt_BinaryFunc(mpd_qand)
+_DecOpt_BinaryFunc(mpd_qor)
+_DecOpt_BinaryFunc(mpd_qxor)
+
+_DecOpt_BinaryFunc(mpd_qrotate)
+_DecOpt_BinaryFunc(mpd_qscaleb)
+_DecOpt_BinaryFunc(mpd_qshift)
+
+static PyObject *
+_DecOpt_mpd_class(PyObject *self, PyObject *args)
+{
+ PyDecObject *a = (PyDecObject *) self;
+ PyObject *ctxobj;
+ mpd_context_t *ctx;
+ const char *cp;
+
+ ctxobj = dflt_ctx();
+ if (!PyArg_ParseTuple(args, "|O", &ctxobj)) {
+ return NULL;
+ }
+
+ CONTEXT_CHECK_VA(ctxobj);
+ ctx = CtxAddr(ctxobj);
+
+ cp = mpd_class(a->dec, ctx);
+ return Py_BuildValue("s", cp);
+}
+
+static PyObject *
+_Dec_canonical(PyObject *self, PyObject *dummy UNUSED)
+{
+ Py_INCREF(self);
+ return self;
+}
+
+static PyObject *
+dec_copy(PyObject *self, PyObject *dummy UNUSED)
+{
+ Py_INCREF(self);
+ return self;
+}
+
+static PyObject *
+_DecOpt_mpd_qdivmod(PyObject *v, PyObject *args)
+{
+ PyObject *w, *ctxobj;
+ PyDecObject *a, *b;
+ PyDecObject *q, *r;
+ uint32_t status = 0;
+ mpd_context_t *ctx;
+
+ ctxobj = dflt_ctx();
+ if (!PyArg_ParseTuple(args, "O|O", &w, &ctxobj)) {
+ return NULL;
+ }
+
+ CONTEXT_CHECK_VA(ctxobj);
+ ctx = CtxAddr(ctxobj);
+
+ CONVERT_BINOP_SET(v, w, &a, &b, ctx);
+
+ if ((q = dec_alloc()) == NULL) {
+ Py_DECREF(a);
+ Py_DECREF(b);
+ return NULL;
+ }
+ if ((r = dec_alloc()) == NULL) {
+ Py_DECREF(a);
+ Py_DECREF(b);
+ Py_DECREF(q);
+ return NULL;
+ }
+
+ mpd_qdivmod(q->dec, r->dec, a->dec, b->dec, ctx, &status);
+ Py_DECREF(a);
+ Py_DECREF(b);
+ if (dec_addstatus(ctx, status)) {
+ Py_DECREF(r);
+ Py_DECREF(q);
+ return NULL;
+ }
+
+ return Py_BuildValue("(NN)", q, r);
+}
+
+static PyObject *
+_Dec_mpd_radix(PyObject *self UNUSED, PyObject *dummy UNUSED)
+{
+ return Py_BuildValue("i", 10);
+}
+
+static PyObject *
+_Dec_mpd_same_quantum(PyObject *v, PyObject *args)
+{
+ PyObject *w, *ctxobj, *result;
+ PyDecObject *a, *b;
+ mpd_context_t *ctx;
+
+ ctxobj = dflt_ctx();
+ if (!PyArg_ParseTuple(args, "O|O", &w, &ctxobj)) {
+ return NULL;
+ }
+
+ CONTEXT_CHECK_VA(ctxobj);
+ ctx = CtxAddr(ctxobj);
+
+ CONVERT_BINOP_SET(v, w, &a, &b, ctx);
+
+ result = mpd_same_quantum(a->dec, b->dec) ? Dec_INCREF_TRUE : Dec_INCREF_FALSE;
+ Py_DECREF(a);
+ Py_DECREF(b);
+
+ return result;
+}
+
+static PyObject *
+_Dec_mpd_sign(PyObject *self, PyObject *dummy UNUSED)
+{
+ PyDecObject *a = (PyDecObject *) self;
+
+ return Py_BuildValue("i", mpd_arith_sign(a->dec));
+}
+
+static PyObject *
+_Dec_mpd_to_sci(PyObject *self, PyObject *args)
+{
+ PyDecObject *a = (PyDecObject *)self;
+ PyObject *result, *c;
+ char *s;
+
+ c = dflt_ctx();
+ if (!PyArg_ParseTuple(args, "|O", &c)) {
+ return NULL;
+ }
+ CONTEXT_CHECK_VA(c);
+
+ s = mpd_to_sci(a->dec, ((PyDecContextObject *)c)->capitals);
+ if (s == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+
+ result = PyUnicode_FromString(s);
+ mpd_free(s);
+
+ return result;
+}
+
+static PyObject *
+_Dec_mpd_to_eng(PyObject *self, PyObject *args)
+{
+ PyDecObject *a = (PyDecObject *)self;
+ PyObject *result, *c;
+ char *s;
+
+ c = dflt_ctx();
+ if (!PyArg_ParseTuple(args, "|O", &c)) {
+ return NULL;
+ }
+ CONTEXT_CHECK_VA(c);
+
+ s = mpd_to_eng(a->dec, ((PyDecContextObject *)c)->capitals);
+ if (s == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+
+ result = PyUnicode_FromString(s);
+ mpd_free(s);
+
+ return result;
+}
+
+static PyObject *
+dec_richcompare(PyObject *v, PyObject *w, int op)
+{
+ PyDecObject *a = (PyDecObject *)v;
+ PyDecObject *b;
+ uint32_t status = 0;
+ mpd_context_t *ctx;
+ int r;
+
+ ctx = mpd_ctx();
+ CONVERT_BINOP(v, w, &a, &b, ctx);
+
+ r = mpd_qcmp(a->dec, b->dec, &status);
+ Py_DECREF(a);
+ Py_DECREF(b);
+ /* NaNs always signal, except for Py_EQ and Py_NE. */
+ if (op != Py_EQ && op != Py_NE && dec_addstatus(ctx, status)) {
+ return NULL;
+ }
+ /* NaN comparison with Py_EQ, Py_NE, or InvalidOperation disabled. */
+ if (r == INT_MAX) {
+ return (op == Py_NE) ? Dec_INCREF_TRUE : Dec_INCREF_FALSE;
+ }
+
+ switch (op) {
+ case Py_EQ:
+ r = (r == 0);
+ break;
+ case Py_NE:
+ r = (r != 0);
+ break;
+ case Py_LE:
+ r = (r <= 0);
+ break;
+ case Py_GE:
+ r = (r >= 0);
+ break;
+ case Py_LT:
+ r = (r == -1);
+ break;
+ case Py_GT:
+ r = (r == 1);
+ break;
+ }
+
+ return PyBool_FromLong(r);
+}
+
+/* Always uses the module context */
+static long
+dec_hash(PyObject *v)
+{
+#if defined(CONFIG_64)
+ mpd_uint_t data_two64m1[2] = {8446744073709551615ULL, 1ULL};
+ mpd_t two64m1 = {MPD_POS|MPD_STATIC|MPD_CONST_DATA, 0, 20, 2, 2, data_two64m1};
+#elif defined(CONFIG_32)
+ mpd_uint_t data_two64m1[3] = {709551615UL, 446744073UL, 18UL};
+ mpd_t two64m1 = {MPD_POS|MPD_STATIC|MPD_CONST_DATA, 0, 20, 3, 2, data_two64m1};
+#else
+ #error "CONFIG_64 or CONFIG_32 must be defined."
+#endif
+ mpd_uint_t data_ten[1] = {10};
+ mpd_t ten = {MPD_POS|MPD_STATIC|MPD_CONST_DATA, 0, 2, 1, 1, data_ten};
+
+ PyDecObject *a;
+ PyObject *obj = NULL;
+ mpd_t *tmp = NULL;
+ char *cp = NULL;
+ uint32_t status = 0;
+ mpd_context_t maxcontext, *ctx;
+ long result;
+
+ if ((a = dec_alloc()) == NULL) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ if (!mpd_qcopy(a->dec, ((PyDecObject *) v)->dec, &status)) {
+ PyErr_NoMemory();
+ result = -1;
+ goto finish;
+ }
+
+ if (mpd_isspecial(a->dec)) {
+ if (mpd_isnan(a->dec)) {
+ PyErr_SetString(PyExc_TypeError, "cannot hash a NaN value");
+ result = -1;
+ }
+ else {
+ if ((obj = dec_str(a)) == NULL) {
+ result = -1;
+ goto finish;
+ }
+ result = PyObject_Hash(obj);
+ }
+ }
+ else if (mpd_iszero(a->dec)) {
+ result = 0;
+ }
+ else if (mpd_isinteger(a->dec)) {
+
+ mpd_maxcontext(&maxcontext);
+ ctx = mpd_ctx();
+
+#if PY_VERSION_HEX >= 0x02060000
+ if ((tmp = mpd_qnew()) == NULL) {
+ PyErr_NoMemory();
+ result = -1;
+ goto finish;
+ }
+
+ /* clobbering a function scope object */
+ mpd_qround_to_int(a->dec, a->dec, ctx, &status);
+ mpd_qset_ssize(tmp, a->dec->exp, &maxcontext, &status);
+ mpd_qpowmod(tmp, &ten, tmp, &two64m1, &maxcontext, &status);
+ a->dec->exp = 0;
+ mpd_qmul(a->dec, a->dec, tmp, &maxcontext, &status);
+
+ if (status&MPD_Errors) {
+ if (dec_addstatus(ctx, status)) {
+ result = -1;
+ goto finish;
+ }
+ }
+#endif
+
+ if ((obj = PyLong_FromDecCtx(a, &maxcontext)) == NULL) {
+ result = -1;
+ goto finish;
+ }
+ result = PyObject_Hash(obj);
+ }
+ else {
+ mpd_ssize_t tz;
+ mpd_ssize_t exp;
+ int sign;
+
+ mpd_maxcontext(&maxcontext);
+ tz = mpd_trail_zeros(a->dec);
+ exp = a->dec->exp + a->dec->digits;
+ sign = mpd_sign(a->dec);
+
+ mpd_qshiftr_inplace(a->dec, tz);
+ a->dec->exp = 0;
+ a->dec->flags = MPD_POS;
+
+ cp = mpd_to_sci(a->dec, 1);
+ if ((obj = Py_BuildValue("(i"CONV_mpd_ssize_t"s)", sign, exp, cp)) == NULL) {
+ result = -1;
+ goto finish;
+ }
+ result = PyObject_Hash(obj);
+ }
+
+
+finish:
+ Py_DECREF(a);
+ if (obj) {Py_DECREF(obj);}
+ if (tmp) mpd_del(tmp);
+ if (cp) mpd_free(cp);
+ return result;
+}
+
+static PyObject *
+dec_reduce(PyObject *self, PyObject *dummy UNUSED)
+{
+ PyObject *newob, *mpd_str;
+
+ if ((mpd_str = dec_str((PyDecObject *)self)) == NULL) {
+ return NULL;
+ }
+
+ newob = Py_BuildValue("O(N)", Py_TYPE(self), mpd_str);
+
+ return newob;
+}
+
+static PyNumberMethods dec_number_methods =
+{
+ (binaryfunc) _Dec_mpd_qadd,
+ (binaryfunc) _Dec_mpd_qsub,
+ (binaryfunc) _Dec_mpd_qmul,
+ (binaryfunc) _Dec_mpd_qrem,
+ (binaryfunc) _Dec_mpd_qdivmod,
+ (ternaryfunc) _Dec_mpd_qpow,
+ (unaryfunc) _Dec_mpd_qminus,
+ (unaryfunc) _Dec_mpd_qplus,
+ (unaryfunc) _Dec_mpd_qabs,
+ (inquiry) _Dec_nonzero,
+ (unaryfunc) 0, /* no bit-complement */
+ (binaryfunc) 0, /* no shiftl */
+ (binaryfunc) 0, /* no shiftr */
+ (binaryfunc) 0, /* no bit-and */
+ (binaryfunc) 0, /* no bit-xor */
+ (binaryfunc) 0, /* no bit-ior */
+ (unaryfunc) PyLong_FromDec,
+ 0, /* nb_reserved */
+ (unaryfunc) PyFloat_FromDec,
+ 0, /* binaryfunc nb_inplace_add; */
+ 0, /* binaryfunc nb_inplace_subtract; */
+ 0, /* binaryfunc nb_inplace_multiply; */
+ 0, /* binaryfunc nb_inplace_remainder; */
+ 0, /* ternaryfunc nb_inplace_power; */
+ 0, /* binaryfunc nb_inplace_lshift; */
+ 0, /* binaryfunc nb_inplace_rshift; */
+ 0, /* binaryfunc nb_inplace_and; */
+ 0, /* binaryfunc nb_inplace_xor; */
+ 0, /* binaryfunc nb_inplace_or; */
+ (binaryfunc) _Dec_mpd_qdivint, /* binaryfunc nb_floor_divide; */
+ (binaryfunc) _Dec_mpd_qdiv, /* binaryfunc nb_true_divide; */
+ 0, /* binaryfunc nb_inplace_floor_divide; */
+ 0, /* binaryfunc nb_inplace_true_divide; */
+};
+
+static PyMethodDef dec_methods [] =
+{
+ /* Unary arithmetic functions */
+ { "abs", _DecOpt_mpd_qabs, METH_VARARGS, doc_abs },
+ { "exp", _DecOpt_mpd_qexp, METH_VARARGS, doc_exp },
+ { "invroot", _DecOpt_mpd_qinvroot, METH_VARARGS, doc_invroot },
+ { "ln", _DecOpt_mpd_qln, METH_VARARGS, doc_ln },
+ { "log10", _DecOpt_mpd_qlog10, METH_VARARGS, doc_log10 },
+ { "minus", _DecOpt_mpd_qminus, METH_VARARGS, doc_minus },
+ { "next_minus", _DecOpt_mpd_qnext_minus, METH_VARARGS, doc_next_minus },
+ { "next_plus", _DecOpt_mpd_qnext_plus, METH_VARARGS, doc_next_plus },
+ { "normalize", _DecOpt_mpd_qreduce, METH_VARARGS, doc_normalize }, /* alias for reduce */
+ { "plus", _DecOpt_mpd_qplus, METH_VARARGS, doc_plus },
+ { "reduce", _DecOpt_mpd_qreduce, METH_VARARGS, doc_reduce },
+ { "to_integral", (PyCFunction)PyDec_ToIntegralValue, METH_VARARGS|METH_KEYWORDS, doc_to_integral },
+ { "to_integral_exact", (PyCFunction)PyDec_ToIntegralExact, METH_VARARGS|METH_KEYWORDS, doc_to_integral_exact },
+ { "to_integral_value", (PyCFunction)PyDec_ToIntegralValue, METH_VARARGS|METH_KEYWORDS, doc_to_integral_value },
+ { "sqrt", _DecOpt_mpd_qsqrt, METH_VARARGS, doc_sqrt },
+
+ /* Binary arithmetic functions */
+ { "add", _DecOpt_mpd_qadd, METH_VARARGS, doc_add },
+ { "compare", _DecOpt_mpd_qcompare, METH_VARARGS, doc_compare },
+ { "compare_signal", _DecOpt_mpd_qcompare_signal, METH_VARARGS, doc_compare_signal },
+ { "div", _DecOpt_mpd_qdiv, METH_VARARGS, doc_div }, /* alias for divide */
+ { "divide", _DecOpt_mpd_qdiv, METH_VARARGS, doc_divide },
+ { "divide_int", _DecOpt_mpd_qdivint, METH_VARARGS, doc_divide_int },
+ { "divint", _DecOpt_mpd_qdivint, METH_VARARGS, doc_divint }, /* alias for divide_int */
+ { "divmod", _DecOpt_mpd_qdivmod, METH_VARARGS, doc_divmod },
+ { "max", _DecOpt_mpd_qmax, METH_VARARGS, doc_max },
+ { "max_mag", _DecOpt_mpd_qmax_mag, METH_VARARGS, doc_max_mag },
+ { "min", _DecOpt_mpd_qmin, METH_VARARGS, doc_min },
+ { "min_mag", _DecOpt_mpd_qmin_mag, METH_VARARGS, doc_min_mag },
+ { "mul", _DecOpt_mpd_qmul, METH_VARARGS, doc_mul }, /* alias for multiply */
+ { "multiply", _DecOpt_mpd_qmul, METH_VARARGS, doc_multiply },
+ { "next_toward", _DecOpt_mpd_qnext_toward, METH_VARARGS, doc_next_toward },
+ { "pow", _DecOpt_mpd_qpow, METH_VARARGS, doc_pow }, /* alias for power */
+ { "power", _DecOpt_mpd_qpow, METH_VARARGS, doc_power },
+ { "quantize", _DecOpt_mpd_qquantize, METH_VARARGS, doc_quantize },
+ { "rem", _DecOpt_mpd_qrem, METH_VARARGS, doc_rem }, /* alias for remainder */
+ { "remainder", _DecOpt_mpd_qrem, METH_VARARGS, doc_remainder },
+ { "remainder_near", _DecOpt_mpd_qrem_near, METH_VARARGS, doc_remainder_near },
+ { "sub", _DecOpt_mpd_qsub, METH_VARARGS, doc_sub }, /* alias for subtract */
+ { "subtract", _DecOpt_mpd_qsub, METH_VARARGS, doc_subtract },
+
+ /* Ternary arithmetic functions */
+ { "fma", _DecOpt_mpd_qfma, METH_VARARGS, doc_fma },
+ { "powmod", _DecOpt_mpd_qpowmod, METH_VARARGS, doc_powmod },
+
+ /* Boolean functions, no context arg */
+ { "is_canonical", _Dec_CFunc_mpd_iscanonical, METH_NOARGS, doc_is_canonical },
+ { "is_finite", _Dec_CFunc_mpd_isfinite, METH_NOARGS, doc_is_finite },
+ { "is_infinite", _Dec_CFunc_mpd_isinfinite, METH_NOARGS, doc_is_infinite },
+ { "is_integer", _Dec_CFunc_mpd_isinteger, METH_NOARGS, doc_is_integer },
+ { "is_nan", _Dec_CFunc_mpd_isnan, METH_NOARGS, doc_is_nan },
+ { "is_qnan", _Dec_CFunc_mpd_isqnan, METH_NOARGS, doc_is_qnan },
+ { "is_snan", _Dec_CFunc_mpd_issnan, METH_NOARGS, doc_is_snan },
+ { "is_signed", _Dec_CFunc_mpd_issigned, METH_NOARGS, doc_is_signed },
+ { "is_special", _Dec_CFunc_mpd_isspecial, METH_NOARGS, doc_is_special },
+ { "is_zero", _Dec_CFunc_mpd_iszero, METH_NOARGS, doc_is_zero },
+
+ /* Boolean functions, optional context arg */
+ { "is_normal", _DecOpt_mpd_isnormal, METH_VARARGS, doc_is_normal },
+ { "is_subnormal", _DecOpt_mpd_issubnormal, METH_VARARGS, doc_is_subnormal },
+
+ /* Unary functions, no context arg */
+ { "adjusted", _Dec_mpd_adjexp, METH_NOARGS, doc_adjusted },
+ { "canonical", _Dec_canonical, METH_NOARGS, doc_canonical },
+ { "copy_abs", _Dec_mpd_qcopy_abs, METH_NOARGS, doc_copy_abs },
+ { "copy_negate", _Dec_mpd_qcopy_negate, METH_NOARGS, doc_copy_negate },
+ { "radix", _Dec_mpd_radix, METH_NOARGS, doc_radix },
+ { "sign", _Dec_mpd_sign, METH_NOARGS, doc_sign },
+
+ /* Unary functions, optional context arg */
+ { "apply", PyDec_Apply, METH_VARARGS, doc_apply },
+ { "logb", _DecOpt_mpd_qlogb, METH_VARARGS, doc_logb },
+ { "logical_invert", _DecOpt_mpd_qinvert, METH_VARARGS, doc_logical_invert },
+ { "number_class", _DecOpt_mpd_class, METH_VARARGS, doc_number_class },
+ { "to_sci", _Dec_mpd_to_sci, METH_VARARGS, doc_to_sci }, /* alias for to_sci_string */
+ { "to_sci_string", _Dec_mpd_to_sci, METH_VARARGS, doc_to_sci_string },
+ { "to_eng", _Dec_mpd_to_eng, METH_VARARGS, doc_to_eng }, /* alias for to_eng_string */
+ { "to_eng_string", _Dec_mpd_to_eng, METH_VARARGS, doc_to_eng_string },
+
+ /* Binary functions, optional context arg */
+ { "compare_total", _DecOpt_mpd_compare_total, METH_VARARGS, doc_compare_total },
+ { "compare_total_mag", _DecOpt_mpd_compare_total_mag, METH_VARARGS, doc_compare_total_mag },
+ { "copy_sign", _Dec_mpd_qcopy_sign, METH_O, doc_copy_sign },
+ { "logical_and", _DecOpt_mpd_qand, METH_VARARGS, doc_logical_and },
+ { "logical_or", _DecOpt_mpd_qor, METH_VARARGS, doc_logical_or },
+ { "logical_xor", _DecOpt_mpd_qxor, METH_VARARGS, doc_logical_xor },
+ { "rotate", _DecOpt_mpd_qrotate, METH_VARARGS, doc_rotate },
+ { "same_quantum", _Dec_mpd_same_quantum, METH_VARARGS, doc_same_quantum },
+ { "scaleb", _DecOpt_mpd_qscaleb, METH_VARARGS, doc_scaleb },
+ { "shift", _DecOpt_mpd_qshift, METH_VARARGS, doc_shift },
+
+ /* Miscellaneous */
+ { "from_float", _PyDec_FromFloat_Max, METH_O|METH_CLASS, doc_from_float },
+ { "as_tuple", PyDec_AsTuple, METH_NOARGS, doc_as_tuple },
+
+ /* Generic stuff */
+ { "__copy__", dec_copy, METH_NOARGS, NULL },
+ { "__deepcopy__", dec_copy, METH_VARARGS, NULL },
+ { "__format__", dec_format, METH_VARARGS, NULL },
+ { "__reduce__", dec_reduce, METH_NOARGS, NULL },
+ { "__round__", PyDec_Round, METH_VARARGS, NULL },
+ { "__trunc__", PyDec_Trunc, METH_NOARGS, NULL },
+
+ { NULL, NULL, 1 }
+};
+
+static PyTypeObject PyDec_Type =
+{
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "cdecimal.Decimal", /* tp_name */
+ sizeof(PyDecObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ (destructor) dec_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ (getattrfunc) 0, /* tp_getattr */
+ (setattrfunc) 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ (reprfunc) dec_repr, /* tp_repr */
+ &dec_number_methods, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ (hashfunc) dec_hash, /* tp_hash */
+ 0, /* tp_call */
+ (reprfunc) dec_str, /* tp_str */
+ (getattrofunc) PyObject_GenericGetAttr, /* tp_getattro */
+ (setattrofunc) 0, /* tp_setattro */
+ (PyBufferProcs *) 0, /* tp_as_buffer */
+ (Py_TPFLAGS_DEFAULT|
+ Py_TPFLAGS_BASETYPE), /* tp_flags */
+ doc_decimal, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ dec_richcompare, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ dec_methods, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ dec_new, /* tp_new */
+ PyObject_Del, /* tp_free */
+};
+
+
+/******************************************************************************/
+/* Context Object, Part 2 */
+/******************************************************************************/
+
+
+/************************************************************************/
+/* Macros for converting mpdecimal functions to Context methods */
+/************************************************************************/
+
+/*
+ * Operand is PyObject that must be convertible to a PyDecObject.
+ * MPDFUNC uses a const context and does not raise.
+ */
+#define _DecCtx_BoolFunc(MPDFUNC) \
+static PyObject * \
+_DecCtx_##MPDFUNC(PyObject *self, PyObject *v) \
+{ \
+ PyObject *ret; \
+ PyDecObject *a; \
+ mpd_context_t *ctx; \
+ \
+ ctx = CtxAddr(self); \
+ CONVERT_OP(v, &a, ctx); \
+ \
+ ret = MPDFUNC(a->dec, ctx) ? Dec_INCREF_TRUE : Dec_INCREF_FALSE; \
+ Py_DECREF(a); \
+ return ret; \
+}
+
+/*
+ * Operand is PyObject that must be convertible to a PyDecObject.
+ * MPDFUNC does NOT use a context and does not raise.
+ */
+#define _DecCtx_BoolFunc_NoCtx(MPDFUNC) \
+static PyObject * \
+_DecCtx_##MPDFUNC(PyObject *self, PyObject *v) \
+{ \
+ PyObject *ret; \
+ PyDecObject *a; \
+ mpd_context_t *ctx; \
+ \
+ ctx = CtxAddr(self); \
+ CONVERT_OP(v, &a, ctx); \
+ \
+ ret = MPDFUNC(a->dec) ? Dec_INCREF_TRUE : Dec_INCREF_FALSE; \
+ Py_DECREF(a); \
+ return ret; \
+}
+
+/*
+ * Operand is PyObject that must be convertible to a PyDecObject.
+ * MPDFUNC is a quiet function.
+ */
+#define _DecCtx_UnaryFunc(MPDFUNC) \
+static PyObject * \
+_DecCtx_##MPDFUNC(PyObject *self, PyObject *v) \
+{ \
+ PyDecObject *result, *a; \
+ mpd_context_t *ctx; \
+ uint32_t status = 0; \
+ \
+ ctx = CtxAddr(self); \
+ CONVERT_OP(v, &a, ctx); \
+ \
+ if ((result = dec_alloc()) == NULL) { \
+ Py_DECREF(a); \
+ return NULL; \
+ } \
+ \
+ MPDFUNC(result->dec, a->dec, ctx, &status); \
+ Py_DECREF(a); \
+ if (dec_addstatus(ctx, status)) { \
+ Py_DECREF(result); \
+ return NULL; \
+ } \
+ \
+ return (PyObject *) result; \
+}
+
+/*
+ * Operands are PyObjects that must be convertible to PyDecObjects.
+ * MPDFUNC is a quiet function.
+ */
+#define _DecCtx_BinaryFunc(MPDFUNC) \
+static PyObject * \
+_DecCtx_##MPDFUNC(PyObject *self, PyObject *args) \
+{ \
+ PyObject *v, *w; \
+ PyDecObject *a, *b; \
+ PyDecObject *result; \
+ uint32_t status = 0; \
+ mpd_context_t *ctx; \
+ \
+ if (!PyArg_ParseTuple(args, "OO", &v, &w)) { \
+ return NULL; \
+ } \
+ \
+ ctx = CtxAddr(self); \
+ CONVERT_BINOP_SET(v, w, &a, &b, ctx); \
+ \
+ if ((result = dec_alloc()) == NULL) { \
+ Py_DECREF(a); \
+ Py_DECREF(b); \
+ return NULL; \
+ } \
+ \
+ MPDFUNC(result->dec, a->dec, b->dec, ctx, &status); \
+ Py_DECREF(a); \
+ Py_DECREF(b); \
+ if (dec_addstatus(ctx, status)) { \
+ Py_DECREF(result); \
+ return NULL; \
+ } \
+ \
+ return (PyObject *) result; \
+}
+
+/*
+ * Operands are Python Objects. Actual MPDFUNC does NOT take a context.
+ * Uses context for conversion only.
+ */
+#define _DecCtx_BinaryFunc_NoCtx(MPDFUNC) \
+static PyObject * \
+_DecCtx_##MPDFUNC(PyObject *self, PyObject *args) \
+{ \
+ PyObject *v, *w; \
+ PyDecObject *a, *b; \
+ PyDecObject *result; \
+ mpd_context_t *ctx; \
+ \
+ if (!PyArg_ParseTuple(args, "OO", &v, &w)) { \
+ return NULL; \
+ } \
+ \
+ ctx = CtxAddr(self); \
+ CONVERT_BINOP_SET(v, w, &a, &b, ctx); \
+ \
+ if ((result = dec_alloc()) == NULL) { \
+ Py_DECREF(a); \
+ Py_DECREF(b); \
+ return NULL; \
+ } \
+ \
+ MPDFUNC(result->dec, a->dec, b->dec); \
+ Py_DECREF(a); \
+ Py_DECREF(b); \
+ \
+ return (PyObject *) result; \
+}
+
+/* Operands are Python Objects. MPDFUNC is a quiet function. */
+#define _DecCtx_TernaryFunc(MPDFUNC) \
+static PyObject * \
+_DecCtx_##MPDFUNC(PyObject *self, PyObject *args) \
+{ \
+ PyObject *v, *w, *x; \
+ PyDecObject *a, *b, *c; \
+ PyDecObject *result; \
+ uint32_t status = 0; \
+ mpd_context_t *ctx; \
+ \
+ if (!PyArg_ParseTuple(args, "OOO", &v, &w, &x)) { \
+ return NULL; \
+ } \
+ \
+ ctx = CtxAddr(self); \
+ CONVERT_TERNOP_SET(v, w, x, &a, &b, &c, ctx); \
+ \
+ if ((result = dec_alloc()) == NULL) { \
+ Py_DECREF(a); \
+ Py_DECREF(b); \
+ Py_DECREF(c); \
+ return NULL; \
+ } \
+ \
+ MPDFUNC(result->dec, a->dec, b->dec, c->dec, ctx, &status); \
+ Py_DECREF(a); \
+ Py_DECREF(b); \
+ Py_DECREF(c); \
+ if (dec_addstatus(ctx, status)) { \
+ Py_DECREF(result); \
+ return NULL; \
+ } \
+ \
+ return (PyObject *) result; \
+}
+
+static PyObject *
+_DecCtx_copy_decimal(PyObject *self UNUSED, PyObject *v)
+{
+ if (!PyDec_Check(v)) {
+ PyErr_SetString(PyExc_TypeError, "argument must be a Decimal");
+ return NULL;
+ }
+
+ Py_INCREF(v);
+ return v;
+}
+
+/* Arithmetic operations */
+_DecCtx_UnaryFunc(mpd_qabs)
+_DecCtx_UnaryFunc(mpd_qexp)
+_DecCtx_UnaryFunc(mpd_qinvroot)
+_DecCtx_UnaryFunc(mpd_qln)
+_DecCtx_UnaryFunc(mpd_qlog10)
+_DecCtx_UnaryFunc(mpd_qminus)
+_DecCtx_UnaryFunc(mpd_qnext_minus)
+_DecCtx_UnaryFunc(mpd_qnext_plus)
+_DecCtx_UnaryFunc(mpd_qplus)
+_DecCtx_UnaryFunc(mpd_qreduce)
+_DecCtx_UnaryFunc(mpd_qsqrt)
+
+_DecCtx_BinaryFunc(mpd_qadd)
+_DecCtx_BinaryFunc(mpd_qcompare)
+_DecCtx_BinaryFunc(mpd_qcompare_signal)
+_DecCtx_BinaryFunc(mpd_qdiv)
+_DecCtx_BinaryFunc(mpd_qdivint)
+_DecCtx_BinaryFunc(mpd_qmax)
+_DecCtx_BinaryFunc(mpd_qmax_mag)
+_DecCtx_BinaryFunc(mpd_qmin)
+_DecCtx_BinaryFunc(mpd_qmin_mag)
+_DecCtx_BinaryFunc(mpd_qmul)
+_DecCtx_BinaryFunc(mpd_qnext_toward)
+_DecCtx_BinaryFunc(mpd_qpow)
+_DecCtx_BinaryFunc(mpd_qquantize)
+_DecCtx_BinaryFunc(mpd_qrem)
+_DecCtx_BinaryFunc(mpd_qrem_near)
+_DecCtx_BinaryFunc(mpd_qsub)
+
+_DecCtx_TernaryFunc(mpd_qfma)
+_DecCtx_TernaryFunc(mpd_qpowmod)
+
+/* Miscellaneous */
+_DecCtx_BoolFunc(mpd_isnormal)
+_DecCtx_BoolFunc(mpd_issubnormal)
+_DecCtx_BoolFunc_NoCtx(mpd_iscanonical)
+_DecCtx_BoolFunc_NoCtx(mpd_isfinite)
+_DecCtx_BoolFunc_NoCtx(mpd_isinfinite)
+_DecCtx_BoolFunc_NoCtx(mpd_isnan)
+_DecCtx_BoolFunc_NoCtx(mpd_isqnan)
+_DecCtx_BoolFunc_NoCtx(mpd_issigned)
+_DecCtx_BoolFunc_NoCtx(mpd_issnan)
+_DecCtx_BoolFunc_NoCtx(mpd_iszero)
+
+
+static PyObject *
+_DecCtx_mpd_qcopy_abs(PyObject *self, PyObject *v)
+{
+ PyDecObject *result, *a;
+ uint32_t status = 0;
+ mpd_context_t *ctx;
+
+ ctx = CtxAddr(self);
+ CONVERT_OP(v, &a, ctx);
+
+ if ((result = dec_alloc()) == NULL) {
+ Py_DECREF(a);
+ return NULL;
+ }
+
+ mpd_qcopy_abs(result->dec, a->dec, &status);
+ Py_DECREF(a);
+ if (dec_addstatus(ctx, status)) {
+ Py_DECREF(result);
+ return NULL;
+ }
+
+ return (PyObject *) result;
+}
+
+static PyObject *
+_DecCtx_mpd_qcopy_negate(PyObject *self, PyObject *v)
+{
+ PyDecObject *result, *a;
+ uint32_t status = 0;
+ mpd_context_t *ctx;
+
+ ctx = CtxAddr(self);
+ CONVERT_OP(v, &a, ctx);
+
+ if ((result = dec_alloc()) == NULL) {
+ Py_DECREF(a);
+ return NULL;
+ }
+
+ mpd_qcopy_negate(result->dec, a->dec, &status);
+ Py_DECREF(a);
+ if (dec_addstatus(ctx, status)) {
+ Py_DECREF(result);
+ return NULL;
+ }
+
+ return (PyObject *) result;
+}
+
+_DecCtx_UnaryFunc(mpd_qinvert)
+_DecCtx_UnaryFunc(mpd_qlogb)
+
+_DecCtx_BinaryFunc_NoCtx(mpd_compare_total)
+_DecCtx_BinaryFunc_NoCtx(mpd_compare_total_mag)
+
+static PyObject *
+_DecCtx_mpd_qcopy_sign(PyObject *self, PyObject *args)
+{
+ PyObject *v, *w;
+ PyDecObject *a, *b;
+ PyDecObject *result;
+ uint32_t status = 0;
+ mpd_context_t *ctx;
+
+ if (!PyArg_ParseTuple(args, "OO", &v, &w)) {
+ return NULL;
+ }
+
+ ctx = CtxAddr(self);
+ CONVERT_BINOP(v, w, &a, &b, ctx);
+
+ if ((result = dec_alloc()) == NULL) {
+ Py_DECREF(a);
+ Py_DECREF(b);
+ return NULL;
+ }
+
+ mpd_qcopy_sign(result->dec, a->dec, b->dec, &status);
+ Py_DECREF(a);
+ Py_DECREF(b);
+ if (dec_addstatus(ctx, status)) {
+ Py_DECREF(result);
+ return NULL;
+ }
+
+ return (PyObject *) result;
+}
+
+_DecCtx_BinaryFunc(mpd_qand)
+_DecCtx_BinaryFunc(mpd_qor)
+_DecCtx_BinaryFunc(mpd_qxor)
+
+_DecCtx_BinaryFunc(mpd_qrotate)
+_DecCtx_BinaryFunc(mpd_qscaleb)
+_DecCtx_BinaryFunc(mpd_qshift)
+
+static PyObject *
+_DecCtx_canonical(PyObject *self UNUSED, PyObject *v)
+{
+ if (!PyDec_Check(v)) {
+ PyErr_SetString(PyExc_ValueError, "argument must be a Decimal");
+ return NULL;
+ }
+
+ Py_INCREF(v);
+ return v;
+}
+
+static PyObject *
+_DecCtx_mpd_class(PyObject *self, PyObject *v)
+{
+ mpd_context_t *ctx;
+ const char *cp;
+
+ if (!PyDec_Check(v)) {
+ PyErr_SetString(PyExc_ValueError, "argument must be a Decimal");
+ return NULL;
+ }
+ ctx = CtxAddr(self);
+
+ cp = mpd_class(DecAddr(v), ctx);
+ return Py_BuildValue("s", cp);
+}
+
+static PyObject *
+_DecCtx_mpd_qdivmod(PyObject *self, PyObject *args)
+{
+ PyObject *v, *w;
+ PyDecObject *a, *b;
+ PyDecObject *q, *r;
+ uint32_t status = 0;
+ mpd_context_t *ctx;
+
+ if (!PyArg_ParseTuple(args, "OO", &v, &w)) {
+ return NULL;
+ }
+
+ ctx = CtxAddr(self);
+ CONVERT_BINOP_SET(v, w, &a, &b, ctx);
+
+ if ((q = dec_alloc()) == NULL) {
+ Py_DECREF(a);
+ Py_DECREF(b);
+ return NULL;
+ }
+ if ((r = dec_alloc()) == NULL) {
+ Py_DECREF(a);
+ Py_DECREF(b);
+ Py_DECREF(q);
+ return NULL;
+ }
+
+ mpd_qdivmod(q->dec, r->dec, a->dec, b->dec, ctx, &status);
+ Py_DECREF(a);
+ Py_DECREF(b);
+ if (dec_addstatus(ctx, status)) {
+ Py_DECREF(r);
+ Py_DECREF(q);
+ return NULL;
+ }
+
+ return Py_BuildValue("(NN)", q, r);
+}
+
+static PyObject *
+_DecCtx_mpd_to_sci(PyObject *self, PyObject *v)
+{
+ PyObject *result;
+ char *s;
+
+ if (!PyDec_Check(v)) {
+ PyErr_SetString(PyExc_TypeError, "argument must be a Decimal");
+ return NULL;
+ }
+
+ s = mpd_to_sci(((PyDecObject *)v)->dec,
+ ((PyDecContextObject *)self)->capitals);
+ if (s == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+
+ result = PyUnicode_FromString(s);
+ mpd_free(s);
+
+ return result;
+}
+
+static PyObject *
+_DecCtx_mpd_to_eng(PyObject *self, PyObject *v)
+{
+ PyObject *result;
+ char *s;
+
+ if (!PyDec_Check(v)) {
+ PyErr_SetString(PyExc_TypeError, "argument must be a Decimal");
+ return NULL;
+ }
+
+ s = mpd_to_eng(((PyDecObject *)v)->dec,
+ ((PyDecContextObject *)self)->capitals);
+ if (s == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+
+ result = PyUnicode_FromString(s);
+ mpd_free(s);
+
+ return result;
+}
+
+static PyObject *
+_DecCtx_mpd_radix(PyObject *self UNUSED, PyObject *dummy UNUSED)
+{
+ return Py_BuildValue("i", 10);
+}
+
+static PyObject *
+_DecCtx_mpd_same_quantum(PyObject *self, PyObject *args)
+{
+ PyObject *v, *w;
+ PyDecObject *a, *b;
+ PyObject *result;
+ mpd_context_t *ctx;
+
+ if (!PyArg_ParseTuple(args, "OO", &v, &w)) {
+ return NULL;
+ }
+
+ ctx = CtxAddr(self);
+ CONVERT_BINOP_SET(v, w, &a, &b, ctx);
+
+ result = mpd_same_quantum(a->dec, b->dec) ? Dec_INCREF_TRUE : Dec_INCREF_FALSE;
+ Py_DECREF(a);
+ Py_DECREF(b);
+
+ return result;
+}
+
+static PyObject *
+PyDecContext_ToIntegralValue(PyObject *self, PyObject *a)
+{
+ PyDecObject *result;
+ mpd_context_t *ctx;
+ uint32_t status = 0;
+
+ if (!PyDec_Check(a)) {
+ PyErr_SetString(PyExc_ValueError, "argument must be a Decimal");
+ return NULL;
+ }
+ if ((result = dec_alloc()) == NULL) {
+ return NULL;
+ }
+
+ ctx = CtxAddr(self);
+
+ mpd_qround_to_int(result->dec, DecAddr(a), ctx, &status);
+ if (dec_addstatus(ctx, status)) {
+ Py_DECREF(result);
+ return NULL;
+ }
+
+ return (PyObject *)result;
+}
+
+static PyObject *
+PyDecContext_ToIntegralExact(PyObject *self, PyObject *a)
+{
+ PyDecObject *result;
+ mpd_context_t *ctx;
+ uint32_t status = 0;
+
+ if (!PyDec_Check(a)) {
+ PyErr_SetString(PyExc_ValueError, "argument must be a Decimal");
+ return NULL;
+ }
+ if ((result = dec_alloc()) == NULL) {
+ return NULL;
+ }
+
+ ctx = CtxAddr(self);
+
+ mpd_qround_to_intx(result->dec, DecAddr(a), ctx, &status);
+ if (dec_addstatus(ctx, status)) {
+ Py_DECREF(result);
+ return NULL;
+ }
+
+ return (PyObject *)result;
+}
+
+
+static PyMethodDef context_methods [] =
+{
+ /* Unary arithmetic functions */
+ { "abs", _DecCtx_mpd_qabs, METH_O, doc_ctx_abs },
+ { "exp", _DecCtx_mpd_qexp, METH_O, doc_ctx_exp },
+ { "invroot", _DecCtx_mpd_qinvroot, METH_O, doc_ctx_invroot },
+ { "ln", _DecCtx_mpd_qln, METH_O, doc_ctx_ln },
+ { "log10", _DecCtx_mpd_qlog10, METH_O, doc_ctx_log10 },
+ { "minus", _DecCtx_mpd_qminus, METH_O, doc_ctx_minus },
+ { "next_minus", _DecCtx_mpd_qnext_minus, METH_O, doc_ctx_next_minus },
+ { "next_plus", _DecCtx_mpd_qnext_plus, METH_O, doc_ctx_next_plus },
+ { "normalize", _DecCtx_mpd_qreduce, METH_O, doc_ctx_normalize }, /* alias for reduce */
+ { "plus", _DecCtx_mpd_qplus, METH_O, doc_ctx_plus },
+ { "reduce", _DecCtx_mpd_qreduce, METH_O, doc_ctx_reduce },
+ { "to_integral", PyDecContext_ToIntegralValue, METH_O, doc_ctx_to_integral },
+ { "to_integral_exact", PyDecContext_ToIntegralExact, METH_O, doc_ctx_to_integral_exact },
+ { "to_integral_value", PyDecContext_ToIntegralValue, METH_O, doc_ctx_to_integral_value },
+ { "sqrt", _DecCtx_mpd_qsqrt, METH_O, doc_ctx_sqrt },
+
+ /* Binary arithmetic functions */
+ { "add", _DecCtx_mpd_qadd, METH_VARARGS, doc_ctx_add },
+ { "compare", _DecCtx_mpd_qcompare, METH_VARARGS, doc_ctx_compare },
+ { "compare_signal", _DecCtx_mpd_qcompare_signal, METH_VARARGS, doc_ctx_compare_signal },
+ { "div", _DecCtx_mpd_qdiv, METH_VARARGS, doc_ctx_div }, /* alias for divide */
+ { "divide", _DecCtx_mpd_qdiv, METH_VARARGS, doc_ctx_divide },
+ { "divide_int", _DecCtx_mpd_qdivint, METH_VARARGS, doc_ctx_divide_int },
+ { "divint", _DecCtx_mpd_qdivint, METH_VARARGS, doc_ctx_divint }, /* alias for divide_int */
+ { "divmod", _DecCtx_mpd_qdivmod, METH_VARARGS, doc_ctx_divmod },
+ { "max", _DecCtx_mpd_qmax, METH_VARARGS, doc_ctx_max },
+ { "max_mag", _DecCtx_mpd_qmax_mag, METH_VARARGS, doc_ctx_max_mag },
+ { "min", _DecCtx_mpd_qmin, METH_VARARGS, doc_ctx_min },
+ { "min_mag", _DecCtx_mpd_qmin_mag, METH_VARARGS, doc_ctx_min_mag },
+ { "mul", _DecCtx_mpd_qmul, METH_VARARGS, doc_ctx_mul }, /* alias for multiply */
+ { "multiply", _DecCtx_mpd_qmul, METH_VARARGS, doc_ctx_multiply },
+ { "next_toward", _DecCtx_mpd_qnext_toward, METH_VARARGS, doc_ctx_next_toward },
+ { "pow", _DecCtx_mpd_qpow, METH_VARARGS, doc_ctx_pow }, /* alias for power */
+ { "power", _DecCtx_mpd_qpow, METH_VARARGS, doc_ctx_power },
+ { "quantize", _DecCtx_mpd_qquantize, METH_VARARGS, doc_ctx_quantize },
+ { "rem", _DecCtx_mpd_qrem, METH_VARARGS, doc_ctx_rem }, /* alias for remainder */
+ { "remainder", _DecCtx_mpd_qrem, METH_VARARGS, doc_ctx_remainder },
+ { "remainder_near", _DecCtx_mpd_qrem_near, METH_VARARGS, doc_ctx_remainder_near },
+ { "sub", _DecCtx_mpd_qsub, METH_VARARGS, doc_ctx_sub }, /* alias for subtract */
+ { "subtract", _DecCtx_mpd_qsub, METH_VARARGS, doc_ctx_subtract },
+
+ /* Ternary arithmetic functions */
+ { "fma", _DecCtx_mpd_qfma, METH_VARARGS, doc_ctx_fma },
+ { "powmod", _DecCtx_mpd_qpowmod, METH_VARARGS, doc_ctx_powmod },
+
+ /* No argument */
+ { "Etiny", context_getetiny, METH_NOARGS, doc_ctx_Etiny },
+ { "Etop", context_getetop, METH_NOARGS, doc_ctx_Etop },
+ { "radix", _DecCtx_mpd_radix, METH_NOARGS, doc_ctx_radix },
+
+ /* Boolean functions */
+ { "is_canonical", _DecCtx_mpd_iscanonical, METH_O, doc_ctx_is_canonical },
+ { "is_finite", _DecCtx_mpd_isfinite, METH_O, doc_ctx_is_finite },
+ { "is_infinite", _DecCtx_mpd_isinfinite, METH_O, doc_ctx_is_infinite },
+ { "is_nan", _DecCtx_mpd_isnan, METH_O, doc_ctx_is_nan },
+ { "is_normal", _DecCtx_mpd_isnormal, METH_O, doc_ctx_is_normal },
+ { "is_qnan", _DecCtx_mpd_isqnan, METH_O, doc_ctx_is_qnan },
+ { "is_signed", _DecCtx_mpd_issigned, METH_O, doc_ctx_is_signed },
+ { "is_snan", _DecCtx_mpd_issnan, METH_O, doc_ctx_is_snan },
+ { "is_subnormal", _DecCtx_mpd_issubnormal, METH_O, doc_ctx_is_subnormal },
+ { "is_zero", _DecCtx_mpd_iszero, METH_O, doc_ctx_is_zero },
+
+ /* Functions with a single decimal argument */
+ { "_apply", PyDecContext_Apply, METH_O, NULL }, /* alias for apply */
+ { "apply", PyDecContext_Apply, METH_O, doc_ctx_apply },
+ { "canonical", _DecCtx_canonical, METH_O, doc_ctx_canonical },
+ { "copy_abs", _DecCtx_mpd_qcopy_abs, METH_O, doc_ctx_copy_abs },
+ { "copy_decimal", _DecCtx_copy_decimal, METH_O, doc_ctx_copy_decimal },
+ { "copy_negate", _DecCtx_mpd_qcopy_negate, METH_O, doc_ctx_copy_negate },
+ { "logb", _DecCtx_mpd_qlogb, METH_O, doc_ctx_logb },
+ { "logical_invert", _DecCtx_mpd_qinvert, METH_O, doc_ctx_logical_invert },
+ { "number_class", _DecCtx_mpd_class, METH_O, doc_ctx_number_class },
+ { "to_sci", _DecCtx_mpd_to_sci, METH_O, doc_ctx_to_sci }, /* alias for to_sci_string */
+ { "to_sci_string", _DecCtx_mpd_to_sci, METH_O, doc_ctx_to_sci_string },
+ { "to_eng", _DecCtx_mpd_to_eng, METH_O, doc_ctx_to_eng }, /* alias for to_eng_string */
+ { "to_eng_string", _DecCtx_mpd_to_eng, METH_O, doc_ctx_to_eng_string },
+
+ /* Functions with two decimal arguments */
+ { "compare_total", _DecCtx_mpd_compare_total, METH_VARARGS, doc_ctx_compare_total },
+ { "compare_total_mag", _DecCtx_mpd_compare_total_mag, METH_VARARGS, doc_ctx_compare_total_mag },
+ { "copy_sign", _DecCtx_mpd_qcopy_sign, METH_VARARGS, doc_ctx_copy_sign },
+ { "logical_and", _DecCtx_mpd_qand, METH_VARARGS, doc_ctx_logical_and },
+ { "logical_or", _DecCtx_mpd_qor, METH_VARARGS, doc_ctx_logical_or },
+ { "logical_xor", _DecCtx_mpd_qxor, METH_VARARGS, doc_ctx_logical_xor },
+ { "rotate", _DecCtx_mpd_qrotate, METH_VARARGS, doc_ctx_rotate },
+ { "same_quantum", _DecCtx_mpd_same_quantum, METH_VARARGS, doc_ctx_same_quantum },
+ { "scaleb", _DecCtx_mpd_qscaleb, METH_VARARGS, doc_ctx_scaleb },
+ { "shift", _DecCtx_mpd_qshift, METH_VARARGS, doc_ctx_shift },
+
+ /* Set context values */
+ { "setflags", (PyCFunction)context_setstatus_list, METH_O, doc_ctx_setflags },
+ { "settraps", (PyCFunction)context_settraps_list, METH_O, doc_ctx_settraps },
+ { "clear_flags", context_clear_flags, METH_NOARGS, doc_ctx_clear_flags },
+ { "clear_traps", context_clear_traps, METH_NOARGS, doc_ctx_clear_traps },
+
+ /* Unsafe set functions with no range checks */
+ { "unsafe_setprec", (PyCFunction)context_unsafe_setprec, METH_O, NULL },
+ { "unsafe_setemin", (PyCFunction)context_unsafe_setemin, METH_O, NULL },
+ { "unsafe_setemax", (PyCFunction)context_unsafe_setemax, METH_O, NULL },
+
+ /* Miscellaneous */
+ { "__copy__", (PyCFunction)context_copy, METH_NOARGS, NULL },
+ { "__reduce__", context_reduce, METH_NOARGS, NULL },
+ { "copy", (PyCFunction)context_copy, METH_NOARGS, doc_ctx_copy },
+ { "create_decimal", PyDecContext_CreateDecimal, METH_VARARGS, doc_ctx_create_decimal },
+ { "create_decimal_from_float", PyDecContext_FromFloat, METH_O, doc_ctx_create_decimal_from_float },
+
+ { NULL, NULL, 1 }
+};
+
+static PyTypeObject PyDecContext_Type =
+{
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "cdecimal.Context", /* tp_name */
+ sizeof(PyDecContextObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ (destructor) context_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ (getattrfunc) 0, /* tp_getattr */
+ (setattrfunc) 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ (reprfunc) context_repr, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ (hashfunc) 0, /* tp_hash */
+ 0, /* tp_call */
+ (reprfunc) context_repr, /* tp_str */
+ (getattrofunc) context_getattr, /* tp_getattro */
+ (setattrofunc) context_setattr, /* tp_setattro */
+ (PyBufferProcs *) 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ doc_context, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ context_methods, /* tp_methods */
+ 0, /* tp_members */
+ context_getsets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ context_init, /* tp_init */
+ 0, /* tp_alloc */
+ context_new, /* tp_new */
+ 0 /* tp_free */
+};
+
+
+static PyMethodDef cdecimal_methods [] =
+{
+ { "getcontext", (PyCFunction)PyDec_GetDefaultContext, METH_NOARGS, doc_getcontext},
+ { "setcontext", (PyCFunction)PyDec_SetDefaultContext, METH_O, doc_setcontext},
+ { "localcontext", (PyCFunction)ctxmanager_new, METH_VARARGS, doc_localcontext},
+ { NULL, NULL, 1, NULL }
+};
+
+static struct PyModuleDef cdecimal_module = {
+ PyModuleDef_HEAD_INIT,
+ "cdecimal",
+ doc_cdecimal,
+ -1,
+ cdecimal_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+};
+
+
+PyMODINIT_FUNC
+PyInit_cdecimal(void)
+{
+ PyObject *m = NULL;
+ PyObject *_numbers = NULL;
+ PyObject *_Number = NULL;
+ PyObject *obj, *ret, *s;
+ DecCondMap *cm;
+
+
+ PyDec_Type.tp_base = &PyBaseObject_Type;
+ PyDecContext_Type.tp_base = &PyBaseObject_Type;
+ PyDecSignalDict_Type.tp_base = &PyDict_Type;
+ PyDecContextManager_Type.tp_base = &PyBaseObject_Type;
+
+
+ if (PyType_Ready(&PyDec_Type) < 0) {
+ goto error;
+ }
+ if (PyType_Ready(&PyDecContext_Type) < 0) {
+ goto error;
+ }
+ if (PyType_Ready(&PyDecSignalDict_Type) < 0) {
+ goto error;
+ }
+ if (PyType_Ready(&PyDecContextManager_Type) < 0) {
+ goto error;
+ }
+
+
+ if ((obj = PyUnicode_FromString("cdecimal")) == NULL) {
+ goto error;
+ }
+ if (PyDict_SetItemString(PyDec_Type.tp_dict, "__module__", obj) < 0) {
+ Py_DECREF(obj);
+ goto error;
+ }
+ if (PyDict_SetItemString(PyDecContext_Type.tp_dict, "__module__", obj) < 0) {
+ Py_DECREF(obj);
+ goto error;
+ }
+ Py_DECREF(obj);
+
+
+ if ((_numbers = PyImport_ImportModule("numbers")) == NULL) {
+ goto error;
+ }
+ if ((_Number = PyObject_GetAttrString(_numbers, "Number")) == NULL) {
+ goto error;
+ }
+ if ((obj = Py_BuildValue("O", &PyDec_Type)) == NULL) {
+ goto error;
+ }
+ if ((s = Py_BuildValue("s", "register")) == NULL) {
+ goto error;
+ }
+ if ((ret = PyObject_CallMethodObjArgs(_Number, s, obj, NULL)) == NULL) {
+ Py_DECREF(s);
+ Py_DECREF(obj);
+ goto error;
+ }
+ Py_DECREF(s);
+ Py_DECREF(obj);
+ Py_DECREF(ret);
+
+
+#ifdef USE_THREAD_LOCAL_STORAGE /* not recommended */
+{
+ PyObject *_thread;
+ PyObject *_local;
+ if ((_thread = PyImport_ImportModule("_thread")) == NULL) {
+ goto error;
+ }
+ if ((_local = PyObject_GetAttrString(_thread, "_local")) == NULL) {
+ goto error;
+ }
+ if ((tls = PyObject_CallObject(_local, NULL)) == NULL) {
+ Py_DECREF(_thread);
+ Py_DECREF(_local);
+ goto error;
+ }
+ Py_DECREF(_thread);
+ Py_DECREF(_local);
+}
+#endif
+
+
+ if ((m = PyModule_Create(&cdecimal_module)) == NULL) {
+ goto error;
+ }
+
+ mpd_traphandler = dec_traphandler;
+ mpd_mallocfunc = PyMem_Malloc;
+ mpd_reallocfunc = PyMem_Realloc;
+ mpd_callocfunc = mpd_callocfunc_em;
+ mpd_free = PyMem_Free;
+
+ Py_INCREF(&PyDec_Type);
+ PyModule_AddObject(m, "Decimal", (PyObject *)&PyDec_Type);
+
+ Py_INCREF(&PyDecContext_Type);
+ PyModule_AddObject(m, "Context", (PyObject *)&PyDecContext_Type);
+
+
+ /* Top level Exception */
+ DecimalException = PyErr_NewException("cdecimal.DecimalException",
+ PyExc_ArithmeticError, NULL);
+ Py_INCREF(DecimalException);
+ PyModule_AddObject(m, "DecimalException", DecimalException);
+
+ /* Exceptions that correspond to IEEE signals */
+ for (cm = signal_map; cm->name != NULL; cm++) {
+ cm->dec_cond = PyErr_NewException((char *)cm->fqname, DecimalException, NULL);
+ Py_INCREF(cm->dec_cond);
+ PyModule_AddObject(m, cm->name, cm->dec_cond);
+ }
+
+ /*
+ * Unfortunately, InvalidOperation is a signal that comprises
+ * several conditions, including InvalidOperation! Naming the
+ * signal IEEEInvalidOperation would prevent the confusion.
+ */
+ cond_map[0].dec_cond = signal_map[0].dec_cond;
+
+ /* Remaining exceptions, inherit from the InvalidOperation */
+ for (cm = cond_map+1; cm->name != NULL; cm++) {
+ cm->dec_cond = PyErr_NewException((char *)cm->fqname, signal_map[0].dec_cond , NULL);
+ Py_INCREF(cm->dec_cond);
+ PyModule_AddObject(m, cm->name, cm->dec_cond);
+ }
+
+
+ /* Module default context and template for local and
+ * thread local contexts */
+ module_context = PyObject_CallObject((PyObject *)&PyDecContext_Type, NULL);
+ if (module_context == NULL) {
+ goto error;
+ }
+ mpd_init(CtxAddr(module_context), 28);
+ CtxAddr(module_context)->traps &= ~MPD_Underflow; /* XXX */
+ Py_INCREF(module_context);
+ PyModule_AddObject(m, "DefaultContext", (PyObject *)module_context);
+
+ /* Basic context */
+ basic_context = PyObject_CallObject((PyObject *)&PyDecContext_Type, NULL);
+ if (basic_context == NULL) {
+ goto error;
+ }
+ mpd_basiccontext(CtxAddr(basic_context));
+ Py_INCREF(basic_context);
+ PyModule_AddObject(m, "BasicContext", (PyObject *)basic_context);
+
+ /* Extended context */
+ ext_context = PyObject_CallObject((PyObject *)&PyDecContext_Type, NULL);
+ if (ext_context == NULL) {
+ goto error;
+ }
+ mpd_extcontext(CtxAddr(ext_context));
+ Py_INCREF(ext_context);
+ PyModule_AddObject(m, "ExtendedContext", (PyObject *)ext_context);
+
+
+
+ /* Useful constants */
+ PyModule_AddObject(m, "MAX_PREC", Py_BuildValue(CONV_mpd_ssize_t, MPD_MAX_PREC));
+ PyModule_AddObject(m, "MAX_EMAX", Py_BuildValue(CONV_mpd_ssize_t, MPD_MAX_EMAX));
+ PyModule_AddObject(m, "MIN_EMIN", Py_BuildValue(CONV_mpd_ssize_t, MPD_MIN_EMIN));
+ PyModule_AddObject(m, "MIN_ETINY", Py_BuildValue(CONV_mpd_ssize_t, MPD_MIN_ETINY));
+
+ PyModule_AddIntConstant(m, "ROUND_CEILING", MPD_ROUND_CEILING);
+ PyModule_AddIntConstant(m, "ROUND_FLOOR", MPD_ROUND_FLOOR);
+ PyModule_AddIntConstant(m, "ROUND_UP", MPD_ROUND_UP);
+ PyModule_AddIntConstant(m, "ROUND_DOWN", MPD_ROUND_DOWN);
+ PyModule_AddIntConstant(m, "ROUND_HALF_UP", MPD_ROUND_HALF_UP);
+ PyModule_AddIntConstant(m, "ROUND_HALF_DOWN", MPD_ROUND_HALF_DOWN);
+ PyModule_AddIntConstant(m, "ROUND_HALF_EVEN", MPD_ROUND_HALF_EVEN);
+ PyModule_AddIntConstant(m, "ROUND_05UP", MPD_ROUND_05UP);
+ PyModule_AddIntConstant(m, "ROUND_TRUNC", MPD_ROUND_TRUNC);
+
+ /* Expose the C flags */
+ PyModule_AddIntConstant(m, "DecClamped", MPD_Clamped);
+ PyModule_AddIntConstant(m, "DecConversionSyntax", MPD_Conversion_syntax);
+ PyModule_AddIntConstant(m, "DecDivisionByZero", MPD_Division_by_zero);
+ PyModule_AddIntConstant(m, "DecDivisionImpossible", MPD_Division_impossible);
+ PyModule_AddIntConstant(m, "DecDivisionUndefined", MPD_Division_undefined);
+ PyModule_AddIntConstant(m, "DecFpuError", MPD_Fpu_error);
+ PyModule_AddIntConstant(m, "DecInexact", MPD_Inexact);
+ PyModule_AddIntConstant(m, "DecInvalidContext", MPD_Invalid_context);
+ PyModule_AddIntConstant(m, "DecInvalidOperation", MPD_Invalid_operation);
+ PyModule_AddIntConstant(m, "DecIEEEInvalidOperation", MPD_IEEE_Invalid_operation);
+ PyModule_AddIntConstant(m, "DecMallocError", MPD_Malloc_error);
+ PyModule_AddIntConstant(m, "DecNotImplemented", MPD_Not_implemented);
+ PyModule_AddIntConstant(m, "DecOverflow", MPD_Overflow);
+ PyModule_AddIntConstant(m, "DecRounded", MPD_Rounded);
+ PyModule_AddIntConstant(m, "DecSubnormal", MPD_Subnormal);
+ PyModule_AddIntConstant(m, "DecUnderflow", MPD_Underflow);
+ PyModule_AddIntConstant(m, "DecErrors", MPD_Errors);
+ PyModule_AddIntConstant(m, "DecTraps", MPD_Traps);
+
+
+ return m;
+
+
+error:
+ if (tls) Py_DECREF(tls);
+ if (_numbers) Py_DECREF(_numbers);
+ if (_Number) Py_DECREF(_Number);
+ if (module_context) Py_DECREF(module_context);
+ if (basic_context) Py_DECREF(basic_context);
+ if (ext_context) Py_DECREF(ext_context);
+ if (m) Py_DECREF(m);
+
+ return NULL;
+}
+
+
Added: python/branches/py3k-cdecimal/Modules/cdecimal/constants.c
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/constants.c Thu Jan 7 13:02:51 2010
@@ -0,0 +1,110 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#include <stdio.h>
+#include "mpdecimal.h"
+#include "constants.h"
+
+
+#if defined(CONFIG_64)
+
+ /* number-theory.c */
+ const mpd_uint_t mpd_moduli[3] = {
+ 18446744069414584321ULL, 18446744056529682433ULL, 18446742974197923841ULL
+ };
+ const mpd_uint_t mpd_roots[3] = {7ULL, 10ULL, 19ULL};
+
+ /* crt.c */
+ const mpd_uint_t INV_P1_MOD_P2 = 18446744055098026669ULL;
+ const mpd_uint_t INV_P1P2_MOD_P3 = 287064143708160ULL;
+ const mpd_uint_t LH_P1P2 = 18446744052234715137ULL; /* (P1*P2) % 2^64 */
+ const mpd_uint_t UH_P1P2 = 18446744052234715141ULL; /* (P1*P2) / 2^64 */
+
+ /* transpose.c */
+ const size_t mpd_bits[64] = {
+ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384,
+ 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608,
+ 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824,
+ 2147483648ULL, 4294967296ULL, 8589934592ULL, 17179869184ULL, 34359738368ULL,
+ 68719476736ULL, 137438953472ULL, 274877906944ULL, 549755813888ULL,
+ 1099511627776ULL, 2199023255552ULL, 4398046511104, 8796093022208ULL,
+ 17592186044416ULL, 35184372088832ULL, 70368744177664ULL, 140737488355328ULL,
+ 281474976710656ULL, 562949953421312ULL, 1125899906842624ULL,
+ 2251799813685248ULL, 4503599627370496ULL, 9007199254740992ULL,
+ 18014398509481984ULL, 36028797018963968ULL, 72057594037927936ULL,
+ 144115188075855872ULL, 288230376151711744ULL, 576460752303423488ULL,
+ 1152921504606846976ULL, 2305843009213693952ULL, 4611686018427387904ULL,
+ 9223372036854775808ULL
+ };
+
+ /* mpdecimal.c */
+ const mpd_uint_t mpd_pow10[MPD_RDIGITS+1] = {
+ 1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000,
+ 10000000000ULL,100000000000ULL,1000000000000ULL,10000000000000ULL,
+ 100000000000000ULL,1000000000000000ULL,10000000000000000ULL,
+ 100000000000000000ULL,1000000000000000000ULL,10000000000000000000ULL
+ };
+
+ /* magic number for constant division by MPD_RADIX */
+ const mpd_uint_t mprime_rdx = 15581492618384294730ULL;
+
+#elif defined(CONFIG_32)
+
+ /* number-theory.c */
+ const mpd_uint_t mpd_moduli[3] = {2113929217UL, 2013265921UL, 1811939329UL};
+ const mpd_uint_t mpd_roots[3] = {5UL, 31UL, 13UL};
+
+ /* PentiumPro modular multiplication: These constants have to be loaded as
+ * 80 bit long doubles, which are not supported by certain compilers. */
+ const uint32_t mpd_invmoduli[3][3] = {
+ {4293885170U, 2181570688U, 16352U}, /* ((long double) 1 / 2113929217UL) */
+ {1698898177U, 2290649223U, 16352U}, /* ((long double) 1 / 2013265921UL) */
+ {2716021846U, 2545165803U, 16352U} /* ((long double) 1 / 1811939329UL) */
+ };
+
+ const float MPD_TWO63 = 9223372036854775808.0; /* 2^63 */
+
+ /* crt.c */
+ const mpd_uint_t INV_P1_MOD_P2 = 2013265901UL;
+ const mpd_uint_t INV_P1P2_MOD_P3 = 54UL;
+ const mpd_uint_t LH_P1P2 = 4127195137ULL; /* (P1*P2) % 2^32 */
+ const mpd_uint_t UH_P1P2 = 990904320ULL; /* (P1*P2) / 2^32 */
+
+ /* transpose.c */
+ const size_t mpd_bits[32] = {
+ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384,
+ 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608,
+ 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824,
+ 2147483648UL
+ };
+
+ /* mpdecimal.c */
+ const mpd_uint_t mpd_pow10[MPD_RDIGITS+1] = {
+ 1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000
+ };
+
+#else
+ #error "CONFIG_64 or CONFIG_32 must be defined."
+#endif
+
+const char *mpd_round_string[MPD_ROUND_GUARD] = {
+ "ROUND_UP", /* round away from 0 */
+ "ROUND_DOWN", /* round toward 0 (truncate) */
+ "ROUND_CEILING", /* round toward +infinity */
+ "ROUND_FLOOR", /* round toward -infinity */
+ "ROUND_HALF_UP", /* 0.5 is rounded up */
+ "ROUND_HALF_DOWN", /* 0.5 is rounded down */
+ "ROUND_HALF_EVEN", /* 0.5 is rounded to even */
+ "ROUND_05UP", /* round zero or five away from 0 */
+ "ROUND_TRUNC", /* truncate, but set infinity */
+};
+
+const char *mpd_clamp_string[MPD_CLAMP_GUARD] = {
+ "CLAMP_DEFAULT",
+ "CLAMP_IEEE_754"
+};
+
+
Added: python/branches/py3k-cdecimal/Modules/cdecimal/constants.h
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/constants.h Thu Jan 7 13:02:51 2010
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#ifndef CONSTANTS_H
+#define CONSTANTS_H
+
+
+#include "mpdecimal.h"
+
+
+/* choice of optimized functions */
+#if defined(CONFIG_64)
+/* x64 */
+ #define MULMOD(a, b) x64_mulmod(a, b, umod)
+ #define MULMOD2C(a0, a1, w) x64_mulmod2c(a0, a1, w, umod)
+ #define MULMOD2(a0, b0, a1, b1) x64_mulmod2(a0, b0, a1, b1, umod)
+ #define POWMOD(base, exp) x64_powmod(base, exp, umod)
+ #define SETMODULUS(modnum) std_setmodulus(modnum, &umod)
+ #define SIZE3_NTT(x0, x1, x2, w3table) std_size3_ntt(x0, x1, x2, w3table, umod)
+
+ #define BSR(a) x86_bsr(a)
+ #define BSF(a) x86_bsf(a)
+#elif defined(PPRO)
+/* PentiumPro (or later) gcc inline asm */
+ #define MULMOD(a, b) ppro_mulmod(a, b, &dmod, dinvmod)
+ #define MULMOD2C(a0, a1, w) ppro_mulmod2c(a0, a1, w, &dmod, dinvmod)
+ #define MULMOD2(a0, b0, a1, b1) ppro_mulmod2(a0, b0, a1, b1, &dmod, dinvmod)
+ #define POWMOD(base, exp) ppro_powmod(base, exp, &dmod, dinvmod)
+ #define SETMODULUS(modnum) ppro_setmodulus(modnum, &umod, &dmod, dinvmod)
+ #define SIZE3_NTT(x0, x1, x2, w3table) ppro_size3_ntt(x0, x1, x2, w3table, umod, &dmod, dinvmod)
+
+ #define BSR(a) x86_bsr(a)
+ #define BSF(a) x86_bsf(a)
+#else
+ /* ANSI C99 */
+ #define MULMOD(a, b) std_mulmod(a, b, umod)
+ #define MULMOD2C(a0, a1, w) std_mulmod2c(a0, a1, w, umod)
+ #define MULMOD2(a0, b0, a1, b1) std_mulmod2(a0, b0, a1, b1, umod)
+ #define POWMOD(base, exp) std_powmod(base, exp, umod)
+ #define SETMODULUS(modnum) std_setmodulus(modnum, &umod)
+ #define SIZE3_NTT(x0, x1, x2, w3table) std_size3_ntt(x0, x1, x2, w3table, umod)
+
+ #define BSR(a) std_bsr(a)
+ #define BSF(a) std_bsf(a)
+#endif
+
+/* PentiumPro (or later) gcc inline asm */
+extern const float MPD_TWO63;
+extern const uint32_t mpd_invmoduli[3][3];
+
+enum {P1, P2, P3};
+enum {UNORDERED, ORDERED};
+
+extern const mpd_uint_t mpd_moduli[];
+extern const mpd_uint_t mpd_roots[];
+extern const size_t mpd_bits[];
+extern const mpd_uint_t mpd_pow10[];
+
+extern const mpd_uint_t INV_P1_MOD_P2;
+extern const mpd_uint_t INV_P1P2_MOD_P3;
+extern const mpd_uint_t LH_P1P2;
+extern const mpd_uint_t UH_P1P2;
+
+
+#endif /* CONSTANTS_H */
+
+
+
Added: python/branches/py3k-cdecimal/Modules/cdecimal/context.c
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/context.c Thu Jan 7 13:02:51 2010
@@ -0,0 +1,260 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#include <stdio.h>
+#include <string.h>
+#include <signal.h>
+#include "mpdecimal.h"
+
+
+
+static void
+mpd_dflt_traphandler(mpd_context_t *ctx UNUSED)
+{
+ raise(SIGFPE);
+}
+
+void (* mpd_traphandler)(mpd_context_t *) = mpd_dflt_traphandler;
+
+
+static void
+mpd_setminalloc(mpd_ssize_t n)
+{
+ static int minalloc_is_set = 0;
+
+ if (minalloc_is_set) {
+ mpd_err_warn("mpd_setminalloc: ignoring request to set "
+ "MPD_MINALLOC a second time\n");
+ return;
+ }
+ if (n < MPD_MINALLOC_MIN || n > MPD_MINALLOC_MAX) {
+ mpd_err_fatal("illegal value for MPD_MINALLOC");
+ }
+ MPD_MINALLOC = n;
+ minalloc_is_set = 1;
+}
+
+void
+mpd_init(mpd_context_t *ctx, mpd_ssize_t prec)
+{
+ mpd_ssize_t ideal_minalloc;
+
+ mpd_defaultcontext(ctx);
+
+ if (!mpd_qsetprec(ctx, prec)) {
+ mpd_addstatus_raise(ctx, MPD_Invalid_context);
+ return;
+ }
+
+ ideal_minalloc = 2 * ((prec+MPD_RDIGITS-1) / MPD_RDIGITS);
+ if (ideal_minalloc < MPD_MINALLOC_MIN) ideal_minalloc = MPD_MINALLOC_MIN;
+ if (ideal_minalloc > MPD_MINALLOC_MAX) ideal_minalloc = MPD_MINALLOC_MAX;
+
+ mpd_setminalloc(ideal_minalloc);
+}
+
+void
+mpd_maxcontext(mpd_context_t *ctx)
+{
+ ctx->prec=MPD_MAX_PREC;
+ ctx->emax=MPD_MAX_EMAX;
+ ctx->emin=MPD_MIN_EMIN;
+ ctx->round=MPD_ROUND_HALF_EVEN;
+ ctx->traps=MPD_Traps;
+ ctx->status=0;
+ ctx->newtrap=0;
+ ctx->clamp=0;
+ ctx->allcr=1;
+}
+
+void
+mpd_defaultcontext(mpd_context_t *ctx)
+{
+ ctx->prec=2*MPD_RDIGITS;
+ ctx->emax=MPD_MAX_EMAX;
+ ctx->emin=MPD_MIN_EMIN;
+ ctx->round=MPD_ROUND_HALF_UP;
+ ctx->traps=MPD_Traps;
+ ctx->status=0;
+ ctx->newtrap=0;
+ ctx->clamp=0;
+ ctx->allcr=1;
+}
+
+void
+mpd_basiccontext(mpd_context_t *ctx)
+{
+ ctx->prec=9;
+ ctx->emax=MPD_MAX_EMAX;
+ ctx->emin=MPD_MIN_EMIN;
+ ctx->round=MPD_ROUND_HALF_UP;
+ ctx->traps=MPD_Traps|MPD_Clamped;
+ ctx->status=0;
+ ctx->newtrap=0;
+ ctx->clamp=0;
+ ctx->allcr=1;
+}
+
+void
+mpd_extcontext(mpd_context_t *ctx)
+{
+ ctx->prec=9;
+ ctx->emax=MPD_MAX_EMAX;
+ ctx->emin=MPD_MIN_EMIN;
+ ctx->round=MPD_ROUND_HALF_EVEN;
+ ctx->traps=0;
+ ctx->status=0;
+ ctx->newtrap=0;
+ ctx->clamp=0;
+ ctx->allcr=1;
+}
+
+
+mpd_ssize_t
+mpd_getprec(const mpd_context_t *ctx)
+{
+ return ctx->prec;
+}
+
+mpd_ssize_t
+mpd_getemax(const mpd_context_t *ctx)
+{
+ return ctx->emax;
+}
+
+mpd_ssize_t
+mpd_getemin(const mpd_context_t *ctx)
+{
+ return ctx->emin;
+}
+
+int
+mpd_getround(const mpd_context_t *ctx)
+{
+ return ctx->round;
+}
+
+uint32_t
+mpd_gettraps(const mpd_context_t *ctx)
+{
+ return ctx->traps;
+}
+
+uint32_t
+mpd_getstatus(const mpd_context_t *ctx)
+{
+ return ctx->status;
+}
+
+int
+mpd_getclamp(const mpd_context_t *ctx)
+{
+ return ctx->clamp;
+}
+
+int
+mpd_getcr(const mpd_context_t *ctx)
+{
+ return ctx->allcr;
+}
+
+
+int
+mpd_qsetprec(mpd_context_t *ctx, mpd_ssize_t prec)
+{
+ if (prec <= 0 || prec > MPD_MAX_PREC) {
+ return 0;
+ }
+ ctx->prec = prec;
+ return 1;
+}
+
+int
+mpd_qsetemax(mpd_context_t *ctx, mpd_ssize_t emax)
+{
+ if (emax < 0 || emax > MPD_MAX_EMAX) {
+ return 0;
+ }
+ ctx->emax = emax;
+ return 1;
+}
+
+int
+mpd_qsetemin(mpd_context_t *ctx, mpd_ssize_t emin)
+{
+ if (emin > 0 || emin < MPD_MIN_EMIN) {
+ return 0;
+ }
+ ctx->emin = emin;
+ return 1;
+}
+
+int
+mpd_qsetround(mpd_context_t *ctx, int round)
+{
+ int i;
+
+ for (i = 0; i < MPD_ROUND_GUARD; i++) {
+ if (i == round) {
+ ctx->round = round;
+ return 1;
+ }
+ }
+ return 0;
+}
+
+int
+mpd_qsettraps(mpd_context_t *ctx, uint32_t traps)
+{
+ if (traps > MPD_Max_status) {
+ return 0;
+ }
+ ctx->traps = traps;
+ return 1;
+}
+
+int
+mpd_qsetstatus(mpd_context_t *ctx, uint32_t flags)
+{
+ if (flags > MPD_Max_status) {
+ return 0;
+ }
+ ctx->status = flags;
+ return 1;
+}
+
+int
+mpd_qsetclamp(mpd_context_t *ctx, int c)
+{
+ if (c != 0 && c != 1) {
+ return 0;
+ }
+ ctx->clamp = c;
+ return 1;
+}
+
+int
+mpd_qsetcr(mpd_context_t *ctx, int c)
+{
+ if (c != 0 && c != 1) {
+ return 0;
+ }
+ ctx->allcr = c;
+ return 1;
+}
+
+
+void
+mpd_addstatus_raise(mpd_context_t *ctx, uint32_t flags)
+{
+ ctx->status |= flags;
+ if (flags&ctx->traps) {
+ ctx->newtrap = (flags&ctx->traps);
+ mpd_traphandler(ctx);
+ }
+}
+
+
Added: python/branches/py3k-cdecimal/Modules/cdecimal/convolute.c
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/convolute.c Thu Jan 7 13:02:51 2010
@@ -0,0 +1,148 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#include <stdio.h>
+#include "bits.h"
+#include "constants.h"
+#include "fnt.h"
+#include "fourstep.h"
+#include "mpdecimal.h"
+#include "numbertheory.h"
+#include "sixstep.h"
+#include "umodarith.h"
+#include "convolute.h"
+
+
+/* Convolute the data in c1 and c2. Result is in c1. */
+int
+fnt_convolute(mpd_uint_t *c1, mpd_uint_t *c2, size_t n, int modnum)
+{
+ int (*fnt)(mpd_uint_t *, size_t, int, int);
+ int (*inv_fnt)(mpd_uint_t *, size_t, int, int);
+#ifdef PPRO
+ double dmod;
+ uint32_t dinvmod[3];
+#endif
+ mpd_uint_t n_inv, umod;
+ size_t i;
+
+
+ SETMODULUS(modnum);
+ n_inv = POWMOD(n, (umod-2));
+
+ if (ispower2(n)) {
+ if (n > SIX_STEP_THRESHOLD) {
+ fnt = six_step_fnt;
+ inv_fnt = inv_six_step_fnt;
+ }
+ else {
+ fnt = std_fnt;
+ inv_fnt = std_inv_fnt;
+ }
+ }
+ else {
+ fnt = four_step_fnt;
+ inv_fnt = inv_four_step_fnt;
+ }
+
+ if (!fnt(c1, n, modnum, UNORDERED)) {
+ return 0;
+ }
+ if (!fnt(c2, n, modnum, UNORDERED)) {
+ return 0;
+ }
+ for (i = 0; i < n-1; i += 2) {
+ mpd_uint_t x0 = c1[i];
+ mpd_uint_t y0 = c2[i];
+ mpd_uint_t x1 = c1[i+1];
+ mpd_uint_t y1 = c2[i+1];
+ MULMOD2(&x0, y0, &x1, y1);
+ c1[i] = x0;
+ c1[i+1] = x1;
+ }
+
+ if (!inv_fnt(c1, n, modnum, UNORDERED)) {
+ return 0;
+ }
+ for (i = 0; i < n-3; i += 4) {
+ mpd_uint_t x0 = c1[i];
+ mpd_uint_t x1 = c1[i+1];
+ mpd_uint_t x2 = c1[i+2];
+ mpd_uint_t x3 = c1[i+3];
+ MULMOD2C(&x0, &x1, n_inv);
+ MULMOD2C(&x2, &x3, n_inv);
+ c1[i] = x0;
+ c1[i+1] = x1;
+ c1[i+2] = x2;
+ c1[i+3] = x3;
+ }
+
+ return 1;
+}
+
+/* Autoconvolute the data in c1. Result is in c1. */
+int
+fnt_autoconvolute(mpd_uint_t *c1, size_t n, int modnum)
+{
+ int (*fnt)(mpd_uint_t *, size_t, int, int);
+ int (*inv_fnt)(mpd_uint_t *, size_t, int, int);
+#ifdef PPRO
+ double dmod;
+ uint32_t dinvmod[3];
+#endif
+ mpd_uint_t n_inv, umod;
+ size_t i;
+
+
+ SETMODULUS(modnum);
+ n_inv = POWMOD(n, (umod-2));
+
+ if (ispower2(n)) {
+ if (n > SIX_STEP_THRESHOLD) {
+ fnt = six_step_fnt;
+ inv_fnt = inv_six_step_fnt;
+ }
+ else {
+ fnt = std_fnt;
+ inv_fnt = std_inv_fnt;
+ }
+ }
+ else {
+ fnt = four_step_fnt;
+ inv_fnt = inv_four_step_fnt;
+ }
+
+ if (!fnt(c1, n, modnum, UNORDERED)) {
+ return 0;
+ }
+ for (i = 0; i < n-1; i += 2) {
+ mpd_uint_t x0 = c1[i];
+ mpd_uint_t x1 = c1[i+1];
+ MULMOD2(&x0, x0, &x1, x1);
+ c1[i] = x0;
+ c1[i+1] = x1;
+ }
+
+ if (!inv_fnt(c1, n, modnum, UNORDERED)) {
+ return 0;
+ }
+ for (i = 0; i < n-3; i += 4) {
+ mpd_uint_t x0 = c1[i];
+ mpd_uint_t x1 = c1[i+1];
+ mpd_uint_t x2 = c1[i+2];
+ mpd_uint_t x3 = c1[i+3];
+ MULMOD2C(&x0, &x1, n_inv);
+ MULMOD2C(&x2, &x3, n_inv);
+ c1[i] = x0;
+ c1[i+1] = x1;
+ c1[i+2] = x2;
+ c1[i+3] = x3;
+ }
+
+ return 1;
+}
+
+
Added: python/branches/py3k-cdecimal/Modules/cdecimal/convolute.h
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/convolute.h Thu Jan 7 13:02:51 2010
@@ -0,0 +1,20 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#ifndef CONVOLUTE_H
+#define CONVOLUTE_H
+
+
+#include <stdio.h>
+#include "mpdecimal.h"
+
+#define SIX_STEP_THRESHOLD 4096
+
+int fnt_convolute(mpd_uint_t *c1, mpd_uint_t *c2, size_t n, int modnum);
+int fnt_autoconvolute(mpd_uint_t *c1, size_t n, int modnum);
+
+
+#endif
Added: python/branches/py3k-cdecimal/Modules/cdecimal/crt.c
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/crt.c Thu Jan 7 13:02:51 2010
@@ -0,0 +1,166 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#include <stdio.h>
+#include <assert.h>
+#include "mpdecimal.h"
+#include "numbertheory.h"
+#include "umodarith.h"
+#include "crt.h"
+
+
+/*
+ * Functions for arithmetic on triple-word mpd_uint_t numbers.
+ */
+
+
+/* Multiply P1P2 by v, store result in w. */
+static inline void
+_crt_mulP1P2_3(mpd_uint_t w[3], mpd_uint_t v)
+{
+ mpd_uint_t hi1, hi2, lo;
+
+ _mpd_mul_words(&hi1, &lo, LH_P1P2, v);
+ w[0] = lo;
+
+ _mpd_mul_words(&hi2, &lo, UH_P1P2, v);
+ lo = hi1 + lo;
+ if (lo < hi1) hi2++;
+
+ w[1] = lo;
+ w[2] = hi2;
+}
+
+/* Add 3 words from v to w. The result is known to fit in w. */
+static inline void
+_crt_add3(mpd_uint_t w[3], mpd_uint_t v[3])
+{
+ mpd_uint_t carry;
+
+ w[0] = w[0] + v[0];
+ carry = (w[0] < v[0]);
+
+ w[1] = w[1] + v[1];
+ if (w[1] < v[1]) w[2]++;
+
+ w[1] = w[1] + carry;
+ if (w[1] < carry) w[2]++;
+
+ w[2] += v[2];
+}
+
+/* Divide 3 words in u by v, store result in w, return remainder. */
+static inline mpd_uint_t
+_crt_div3(mpd_uint_t *w, const mpd_uint_t *u, mpd_uint_t v)
+{
+ mpd_uint_t r1 = u[2];
+ mpd_uint_t r2;
+
+ if (r1 < v) {
+ w[2] = 0;
+ }
+ else {
+ _mpd_div_word(&w[2], &r1, u[2], v);
+ }
+
+ _mpd_div_words(&w[1], &r2, r1, u[1], v);
+ _mpd_div_words(&w[0], &r1, r2, u[0], v);
+
+ return r1;
+}
+
+
+/*
+ * Chinese Remainder Theorem:
+ * Algorithm from Joerg Arndt, "Matters Computational",
+ * Chapter 37.4.1 [http://www.jjj.de/fxt/]
+ */
+
+/*
+ * CRT with carry: x1, x2, x3 contain numbers modulo p1, p2, p3. For each
+ * triple of members of the arrays, find the unique z modulo p1*p2*p3.
+ *
+ * Overflow analysis for 32 bit:
+ *
+ * carry[3] can hold cmax = 2**96-1. Let c_i denote the carry at the
+ * beginning of the ith iteration. Let zmax be the maximum z.
+ *
+ * cmax = 2**96-1 = 79228162514264337593543950335
+ * zmax = (p1*p2*p3)-1 = 7711435583600944683209981953
+ *
+ * c_0 = 0
+ * c_1 = (c_0 + zmax) / 10**9 = 7711435583600944683
+ * c_2 = (c_1 + zmax) / 10**9 = 7711435591312380266
+ * c_3 = (c_2 + zmax) / 10**9 = 7711435591312380274
+ * c_4 = (c_3 + zmax) / 10**9 = 7711435591312380274
+ * (...)
+ *
+ * The carries do not increase, (c_i + zmax) cannot overflow.
+ *
+ *
+ * Overflow analysis for 64 bit:
+ *
+ * cmax = 2**192-1 = 6277101735386680763835789423207666416102355444464034512895
+ * zmax = (p1*p2*p3)-1 = 6277101353934753858413533876806988331203900781075588186113
+ *
+ * c_0 = 0
+ * c_1 = (c_0 + zmax) / 10**19 = 627710135393475385841353387680698833120
+ * c_2 = (c_1 + zmax) / 10**19 = 627710135393475385904124401220046371704
+ * c_3 = (c_2 + zmax) / 10**19 = 627710135393475385904124401220046371710
+ * c_4 = (c_3 + zmax) / 10**19 = 627710135393475385904124401220046371710
+ * (...)
+ *
+ * The carries do not increase. (c_i + zmax) cannot overflow.
+ */
+void
+crt3(mpd_uint_t *x1, mpd_uint_t *x2, mpd_uint_t *x3, size_t rsize)
+{
+ mpd_uint_t p1 = mpd_moduli[P1];
+ mpd_uint_t umod;
+#ifdef PPRO
+ double dmod;
+ uint32_t dinvmod[3];
+#endif
+ mpd_uint_t a1, a2, a3;
+ mpd_uint_t s;
+ mpd_uint_t z[3], t[3];
+ mpd_uint_t carry[3] = {0,0,0};
+ mpd_uint_t hi, lo;
+ size_t i;
+
+ for (i = 0; i < rsize; i++) {
+
+ a1 = x1[i];
+ a2 = x2[i];
+ a3 = x3[i];
+
+ SETMODULUS(P2);
+ s = ext_submod(a2, a1, umod);
+ s = MULMOD(s, INV_P1_MOD_P2);
+
+ _mpd_mul_words(&hi, &lo, s, p1);
+ lo = lo + a1;
+ if (lo < a1) hi++;
+
+ SETMODULUS(P3);
+ s = dw_submod(a3, hi, lo, umod);
+ s = MULMOD(s, INV_P1P2_MOD_P3);
+
+ z[0] = lo;
+ z[1] = hi;
+ z[2] = 0;
+
+ _crt_mulP1P2_3(t, s);
+ _crt_add3(z, t);
+ _crt_add3(carry, z);
+
+ x1[i] = _crt_div3(carry, carry, MPD_RADIX);
+ }
+
+ assert(carry[0] == 0 && carry[1] == 0 && carry[2] == 0);
+}
+
+
Added: python/branches/py3k-cdecimal/Modules/cdecimal/crt.h
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/crt.h Thu Jan 7 13:02:51 2010
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#ifndef CRT_H
+#define CRT_H
+
+
+#include <stdio.h>
+#include "mpdecimal.h"
+
+void crt3(mpd_uint_t *x1, mpd_uint_t *x2, mpd_uint_t *x3, size_t nmemb);
+
+
+#endif
Added: python/branches/py3k-cdecimal/Modules/cdecimal/difradix2.c
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/difradix2.c Thu Jan 7 13:02:51 2010
@@ -0,0 +1,141 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#include <stdio.h>
+#include <assert.h>
+#include "bits.h"
+#include "mpdecimal.h"
+#include "numbertheory.h"
+#include "umodarith.h"
+#include "difradix2.h"
+
+
+/*
+ * Generate bit reversed words and carry out the permutation.
+ * Algorithm due to Brent Lehmann, see Joerg Arndt, "Matters Computational",
+ * Chapter 1.13.4. [http://www.jjj.de/fxt/]
+ */
+static inline void
+bitreverse_permute(mpd_uint_t a[], size_t n)
+{
+ size_t x = 0;
+ size_t r = 0;
+ size_t t;
+
+ do {
+ if (r > x) {
+ t = a[x];
+ a[x] = a[r];
+ a[r] = t;
+ }
+ x += 1;
+ r ^= (n - (n >> (BSF(x)+1)));
+ } while (x < n);
+}
+
+
+/* Fast Number Theoretic Transform, decimation in frequency. */
+void
+fnt_dif2(mpd_uint_t a[], size_t n, struct fnt_params *tparams)
+{
+ mpd_uint_t *wtable = tparams->wtable;
+ mpd_uint_t umod;
+#ifdef PPRO
+ double dmod;
+ uint32_t dinvmod[3];
+#endif
+ mpd_uint_t m ,mhalf;
+ mpd_uint_t u0, u1, v0, v1;
+ mpd_uint_t j, r;
+ mpd_uint_t w, w0, w1, wstep;
+
+
+ assert(ispower2(n));
+ assert(n >= 4);
+
+ SETMODULUS(tparams->modnum);
+
+ mhalf = n / 2;
+ for (j = 0; j < mhalf; j += 2) {
+
+ w0 = wtable[j];
+ w1 = wtable[j+1];
+
+ u0 = a[j];
+ v0 = a[j+mhalf];
+
+ u1 = a[j+1];
+ v1 = a[j+1+mhalf];
+
+ a[j] = addmod(u0, v0, umod);
+ v0 = submod(u0, v0, umod);
+
+ a[j+1] = addmod(u1, v1, umod);
+ v1 = submod(u1, v1, umod);
+
+ MULMOD2(&v0, w0, &v1, w1);
+
+ a[j+mhalf] = v0;
+ a[j+1+mhalf] = v1;
+
+ }
+
+ wstep = 2;
+ for (m = n/2; m >= 2; m>>=1, wstep<<=1) {
+
+ mhalf = m / 2;
+
+ /* j = 0 */
+ for (r = 0; r < n; r += 2*m) {
+
+ u0 = a[r];
+ v0 = a[r+mhalf];
+
+ u1 = a[m+r];
+ v1 = a[m+r+mhalf];
+
+ a[r] = addmod(u0, v0, umod);
+ v0 = submod(u0, v0, umod);
+
+ a[m+r] = addmod(u1, v1, umod);
+ v1 = submod(u1, v1, umod);
+
+ a[r+mhalf] = v0;
+ a[m+r+mhalf] = v1;
+ }
+
+ for (j = 1; j < mhalf; j++) {
+
+ w = wtable[j*wstep];
+
+ for (r = 0; r < n; r += 2*m) {
+
+ u0 = a[r+j];
+ v0 = a[r+j+mhalf];
+
+ u1 = a[m+r+j];
+ v1 = a[m+r+j+mhalf];
+
+ a[r+j] = addmod(u0, v0, umod);
+ v0 = submod(u0, v0, umod);
+
+ a[m+r+j] = addmod(u1, v1, umod);
+ v1 = submod(u1, v1, umod);
+
+ MULMOD2C(&v0, &v1, w);
+
+ a[r+j+mhalf] = v0;
+ a[m+r+j+mhalf] = v1;
+ }
+
+ }
+
+ }
+
+ bitreverse_permute(a, n);
+}
+
+
Added: python/branches/py3k-cdecimal/Modules/cdecimal/difradix2.h
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/difradix2.h Thu Jan 7 13:02:51 2010
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#ifndef DIF_RADIX2_H
+#define DIF_RADIX2_H
+
+
+#include "stdio.h"
+#include "mpdecimal.h"
+#include "numbertheory.h"
+
+
+void fnt_dif2(mpd_uint_t a[], size_t n, struct fnt_params *tparams);
+
+
+#endif
Added: python/branches/py3k-cdecimal/Modules/cdecimal/docstrings.h
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/docstrings.h Thu Jan 7 13:02:51 2010
@@ -0,0 +1,922 @@
+/*
+ * Copyright (c) 2001-2010 Python Software Foundation. All Rights Reserved.
+ * Modified and extended by Stefan Krah.
+ */
+
+
+#ifndef DOCSTRINGS_H
+#define DOCSTRINGS_H
+
+
+/******************************************************************************/
+/* Module */
+/******************************************************************************/
+
+static const char doc_cdecimal[] = "C decimal arithmetic module";
+
+static const char doc_getcontext[] = "\n\
+getcontext() - Get the current default context.\n\
+\n";
+
+static const char doc_setcontext[] = "\n\
+setcontext(c) - Set a new default context.\n\
+\n";
+
+static const char doc_localcontext[] = "\n\
+localcontext(c) - Return a context manager that will set the default context\n\
+to a copy of c on entry to the with-statement and restore the previous default\n\
+context when exiting the with-statement. If no context is specified, a copy of\n\
+the current default context is used.\n\
+\n";
+
+
+/******************************************************************************/
+/* Decimal Object and Methods */
+/******************************************************************************/
+
+static const char doc_decimal[] = "\n\
+Decimal([value[, context]]): Construct a new Decimal object from value.\n\
+\n\
+value can be an integer, string, tuple, or another Decimal object.\n\
+If no value is given, return Decimal('0'). The context does not affect\n\
+the conversion and is only passed to determine if the InvalidOperation\n\
+trap is active.\n\
+\n";
+
+static const char doc_abs[] = "\n\
+abs() - Return the absolute value of the number.\n\
+\n";
+
+static const char doc_adjusted[] = "\n\
+adjusted() - Return the adjusted exponent of the number.\n\
+\n\
+Defined as exp + digits - 1.\n\
+\n";
+
+static const char doc_as_tuple[] = "\n\
+as_tuple() - Return a tuple representation of the number.\n\
+\n";
+
+static const char doc_canonical[] = "\n\
+canonical() - Return the canonical encoding of the argument. Currently,\n\
+the encoding of a Decimal instance is always canonical, so this operation\n\
+returns its argument unchanged.\n\
+\n";
+
+static const char doc_compare[] = "\n\
+compare(other[, context]) - Compare self to other. Return a decimal value:\n\
+\n\
+ a or b is a NaN ==> Decimal('NaN')\n\
+ a < b ==> Decimal('-1')\n\
+ a == b ==> Decimal('0')\n\
+ a > b ==> Decimal('1')\n\
+\n";
+
+static const char doc_compare_signal[] = "\n\
+compare_signal(other[, context]) - Identical to compare, except that\n\
+all NaNs signal.\n\
+\n";
+
+static const char doc_compare_total[] = "\n\
+compare_total(other) - Compare two operands using their abstract representation\n\
+rather than their numerical value. Similar to the compare() method, but the\n\
+result gives a total ordering on Decimal instances. Two Decimal instances with\n\
+the same numeric value but different representations compare unequal in this\n\
+ordering:\n\
+\n\
+ >>> Decimal('12.0').compare_total(Decimal('12'))\n\
+ Decimal('-1')\n\
+\n\
+Quiet and signaling NaNs are also included in the total ordering. The result\n\
+of this function is Decimal('0') if both operands have the same representation,\n\
+Decimal('-1') if the first operand is lower in the total order than the second,\n\
+and Decimal('1') if the first operand is higher in the total order than the\n\
+second operand. See the specification for details of the total order.\n\
+\n";
+
+static const char doc_compare_total_mag[] = "\n\
+compare_total_mag(other) - Compare two operands using their abstract\n\
+representation rather than their value as in compare_total(), but\n\
+ignoring the sign of each operand. x.compare_total_mag(y) is\n\
+equivalent to x.copy_abs().compare_total(y.copy_abs()).\n\
+\n";
+
+static const char doc_copy_abs[] = "\n\
+copy_abs() - Return the absolute value of the argument. This operation\n\
+is unaffected by the context and is quiet: no flags are changed and no\n\
+rounding is performed.\n\
+\n";
+
+static const char doc_copy_negate[] = "\n\
+copy_negate() - Return the negation of the argument. This operation is\n\
+unaffected by the context and is quiet: no flags are changed and no\n\
+rounding is performed.\n\
+\n";
+
+static const char doc_copy_sign[] = "\n\
+copy_sign(other) - Return a copy of the first operand with the sign set\n\
+to be the same as the sign of the second operand. For example:\n\
+\n\
+ >>> Decimal('2.3').copy_sign(Decimal('-1.5'))\n\
+ Decimal('-2.3')\n\
+\n\
+This operation is unaffected by the context and is quiet: no flags are\n\
+changed and no rounding is performed.\n\
+\n";
+
+static const char doc_exp[] = "\n\
+exp([context]) - Return the value of the (natural) exponential function e**x\n\
+at the given number. The ROUND_HALF_EVEN rounding mode is used. If the _allcr\n\
+field of the context is set to 1 (default), the result is correctly rounded.\n\
+\n";
+
+static const char doc_from_float[] = "\n\
+from_float(f) - Class method that converts a float to a decimal number, exactly.\n\
+Since 0.1 is not exactly representable in binary floating point,\n\
+Decimal.from_float(0.1) is not the same as Decimal('0.1').\n\
+\n\
+ >>> Decimal.from_float(0.1)\n\
+ Decimal('0.1000000000000000055511151231257827021181583404541015625')\n\
+ >>> Decimal.from_float(float('nan'))\n\
+ Decimal('NaN')\n\
+ >>> Decimal.from_float(float('inf'))\n\
+ Decimal('Infinity')\n\
+ >>> Decimal.from_float(float('-inf'))\n\
+ Decimal('-Infinity')\n\
+\n\
+\n";
+
+static const char doc_fma[] = "\n\
+fma(other, third[, context]) - Fused multiply-add. Return self*other+third\n\
+with no rounding of the intermediate product self*other.\n\
+\n\
+ >>> Decimal(2).fma(3, 5)\n\
+ Decimal('11')\n\
+\n\
+\n";
+
+static const char doc_is_canonical[] = "\n\
+is_canonical() - Return True if the argument is canonical and False otherwise.\n\
+Currently, a Decimal instance is always canonical, so this operation always\n\
+returns True.\n\
+\n";
+
+static const char doc_is_finite[] = "\n\
+is_finite() - Return True if the argument is a finite number, and False if the\n\
+argument is infinite or a NaN.\n\
+\n";
+
+static const char doc_is_infinite[] = "\n\
+is_infinite() - Return True if the argument is either positive or negative\n\
+infinity and False otherwise.\n\
+\n";
+
+static const char doc_is_nan[] = "\n\
+is_nan() - Return True if the argument is a (quiet or signaling) NaN and\n\
+False otherwise.\n\
+\n";
+
+static const char doc_is_normal[] = "\n\
+is_normal([context]) - Return True if the argument is a normal finite non-zero\n\
+number with an adjusted exponent greater than or equal to Emin. Return False\n\
+if the argument is zero, subnormal, infinite or a NaN.\n\
+\n";
+
+static const char doc_is_qnan[] = "\n\
+is_qnan() - Return True if the argument is a quiet NaN, and False otherwise.\n\
+\n";
+
+static const char doc_is_signed[] = "\n\
+is_signed() - Return True if the argument has a negative sign and\n\
+False otherwise. Note that both zeros and NaNs can carry signs.\n\
+\n";
+
+static const char doc_is_snan[] = "\n\
+is_snan() - Return True if the argument is a signaling NaN and False otherwise.\n\
+\n";
+
+static const char doc_is_special[] = "\n\
+is_special() - Return True if the argument is either NaN, sNaN or Infinity\n\
+and False otherwise.\n\
+\n";
+
+static const char doc_is_subnormal[] = "\n\
+is_subnormal([context]) - Return True if the argument is subnormal, and False\n\
+otherwise. A number is subnormal if it is non-zero, finite, and has an\n\
+adjusted exponent less than Emin.\n\
+\n";
+
+static const char doc_is_zero[] = "\n\
+is_zero() - Return True if the argument is a (positive or negative) zero and\n\
+False otherwise.\n\
+\n";
+
+static const char doc_ln[] = "\n\
+ln([context]) - Return the natural (base e) logarithm of the operand.\n\
+The ROUND_HALF_EVEN rounding mode is used. If the _allcr field of the\n\
+context is set to 1, the result is correctly rounded.\n\
+\n";
+
+static const char doc_log10[] = "\n\
+log10([context]) - Return the base ten logarithm of the operand.\n\
+The ROUND_HALF_EVEN rounding mode is used. If the _allcr field of the\n\
+context is set to 1, the result is correctly rounded.\n\
+\n";
+
+static const char doc_logb[] = "\n\
+logb([context]) - For a non-zero number, return the adjusted exponent\n\
+of the operand as a Decimal instance. If the operand is a zero, then\n\
+Decimal('-Infinity') is returned and the DivisionByZero condition is\n\
+raised. If the operand is an infinity then Decimal('Infinity') is returned.\n\
+\n";
+
+static const char doc_logical_and[] = "\n\
+logical_and(other[, context]) - Return the digit-wise and of the two\n\
+(logical) operands.\n\
+\n";
+
+static const char doc_logical_invert[] = "\n\
+logical_invert([context]) - Return the digit-wise inversion of the\n\
+(logical) operand.\n\
+\n";
+
+static const char doc_logical_or[] = "\n\
+logical_or(other[, context]) - Return the digit-wise or of the two\n\
+(logical) operands.\n\
+\n";
+
+static const char doc_logical_xor[] = "\n\
+logical_xor(other[, context]) - Return the digit-wise exclusive or of the\n\
+two (logical) operands.\n\
+\n";
+
+static const char doc_max[] = "\n\
+max(other[, context]) - Maximum of self and other. If one operand is a quiet\n\
+NaN and the other is numeric, the numeric operand is returned.\n\
+\n";
+
+static const char doc_max_mag[] = "\n\
+max_mag(other[, context]) - Similar to the max() method, but the comparison is\n\
+done using the absolute values of the operands.\n\
+\n";
+
+static const char doc_min[] = "\n\
+min(other[, context]) - Minimum of self and other. If one operand is a quiet\n\
+NaN and the other is numeric, the numeric operand is returned.\n\
+\n";
+
+static const char doc_min_mag[] = "\n\
+min_mag(other[, context]) - Similar to the min() method, but the comparison is\n\
+done using the absolute values of the operands.\n\
+\n";
+
+static const char doc_next_minus[] = "\n\
+next_minus([context]) - Return the largest number representable in the given\n\
+context (or in the current default context if no context is given) that is\n\
+smaller than the given operand.\n\
+\n";
+
+static const char doc_next_plus[] = "\n\
+next_plus([context]) - Return the smallest number representable in the given\n\
+context (or in the current default context if no context is given) that is\n\
+larger than the given operand.\n\
+\n";
+
+static const char doc_next_toward[] = "\n\
+next_toward(other[, context]) - If the two operands are unequal, return the\n\
+number closest to the first operand in the direction of the second operand.\n\
+If both operands are numerically equal, return a copy of the first operand\n\
+with the sign set to be the same as the sign of the second operand.\n\
+\n";
+
+static const char doc_normalize[] = "\n\
+normalize([context]) - Normalize the number by stripping the rightmost trailing\n\
+zeros and converting any result equal to Decimal('0') to Decimal('0e0'). Used\n\
+for producing canonical values for members of an equivalence class. For example,\n\
+Decimal('32.100') and Decimal('0.321000e+2') both normalize to the equivalent\n\
+value Decimal('32.1').\n\
+\n\
+Normalize is an alias for reduce([context]).\n\
+\n";
+
+static const char doc_number_class[] = "\n\
+number_class([context]) - Return a string describing the class of the operand.\n\
+The returned value is one of the following ten strings:\n\
+\n\
+ * '-Infinity', indicating that the operand is negative infinity.\n\
+ * '-Normal', indicating that the operand is a negative normal number.\n\
+ * '-Subnormal', indicating that the operand is negative and subnormal.\n\
+ * '-Zero', indicating that the operand is a negative zero.\n\
+ * '+Zero', indicating that the operand is a positive zero.\n\
+ * '+Subnormal', indicating that the operand is positive and subnormal.\n\
+ * '+Normal', indicating that the operand is a positive normal number.\n\
+ * '+Infinity', indicating that the operand is positive infinity.\n\
+ * 'NaN', indicating that the operand is a quiet NaN (Not a Number).\n\
+ * 'sNaN', indicating that the operand is a signaling NaN.\n\
+\n\
+\n";
+
+static const char doc_quantize[] = "\n\
+quantize(exp[, context]) - Return a value equal to the first operand after\n\
+rounding and having the exponent of the second operand.\n\
+\n\
+ >>> Decimal('1.41421356').quantize(Decimal('1.000'))\n\
+ Decimal('1.414')\n\
+\n\
+Unlike other operations, if the length of the coefficient after the quantize\n\
+operation would be greater than precision, then an InvalidOperation is signaled.\n\
+This guarantees that, unless there is an error condition, the quantized exponent\n\
+is always equal to that of the right-hand operand.\n\
+\n\
+Also unlike other operations, quantize never signals Underflow, even if the\n\
+result is subnormal and inexact.\n\
+\n\
+If the exponent of the second operand is larger than that of the first, then\n\
+rounding may be necessary. In this case, the rounding mode is determined by the\n\
+given context argument; if no argument is given, the rounding mode of the\n\
+current default context is used.\n\
+\n";
+
+static const char doc_radix[] = "\n\
+radix() - Return Decimal(10), the radix (base) in which the Decimal class does\n\
+all its arithmetic. Included for compatibility with the specification.\n\
+\n";
+
+static const char doc_reduce[] = "\n\
+reduce([context]) - Normalize the number by stripping the rightmost trailing\n\
+zeros and converting any result equal to Decimal('0') to Decimal('0e0'). Used\n\
+for producing canonical values for members of an equivalence class. For example,\n\
+Decimal('32.100') and Decimal('0.321000e+2') both normalize to the equivalent\n\
+value Decimal('32.1').\n\
+\n";
+
+static const char doc_remainder_near[] = "\n\
+remainder_near(other[, context]) - Compute the modulo as either a positive\n\
+or negative value depending on which is closest to zero. For instance,\n\
+Decimal(10).remainder_near(6) returns Decimal('-2'), which is closer to zero\n\
+than Decimal('4').\n\
+\n\
+If both are equally close, the one chosen will have the same sign as self.\n\
+\n";
+
+static const char doc_rotate[] = "\n\
+rotate(other[, context]) - Return the result of rotating the digits of the\n\
+first operand by an amount specified by the second operand. The second operand\n\
+must be an integer in the range -precision through precision. The absolute\n\
+value of the second operand gives the number of places to rotate. If the second\n\
+operand is positive then rotation is to the left; otherwise rotation is to the\n\
+right. The coefficient of the first operand is padded on the left with zeros to\n\
+length precision if necessary. The sign and exponent of the first operand are\n\
+unchanged.\n\
+\n";
+
+static const char doc_same_quantum[] = "\n\
+same_quantum(other[, context]) - Test whether self and other have the\n\
+same exponent or whether both are NaN.\n\
+\n";
+
+static const char doc_scaleb[] = "\n\
+scaleb(other[, context]) - Return the first operand with the exponent adjusted\n\
+the second. Equivalently, return the first operand multiplied by 10**other.\n\
+The second operand must be an integer.\n\
+\n";
+
+static const char doc_shift[] = "\n\
+shift(other[, context]) - Return the result of shifting the digits of the\n\
+first operand by an amount specified by the second operand. The second operand\n\
+must be an integer in the range -precision through precision. The absolute value\n\
+of the second operand gives the number of places to shift. If the second operand\n\
+is positive, then the shift is to the left; otherwise the shift is to the right.\n\
+Digits shifted into the coefficient are zeros. The sign and exponent of the\n\
+first operand are unchanged.\n\
+\n";
+
+static const char doc_sqrt[] = "\n\
+sqrt([context]) - Return the square root of the argument to full precision.\n\
+The result is correctly rounded using the ROUND_HALF_EVEN rounding mode.\n\
+\n";
+
+static const char doc_to_eng[] = "\n\
+to_eng([context]) - Convert a number to a string using engineering\n\
+notation. Alias for to_eng_string().\n\
+\n";
+
+static const char doc_to_eng_string[] = "\n\
+to_eng_string([context]) - Convert to an engineering-type string.\n\
+Engineering notation has an exponent which is a multiple of 3, so\n\
+there are up to 3 digits left of the decimal place. For example,\n\
+Decimal('123E+1') is converted to Decimal('1.23E+3')\n\
+\n";
+
+static const char doc_to_integral[] = "\n\
+to_integral([rounding[, context]]) - Identical to the to_integral_value()\n\
+method. The to_integral name has been kept for compatibility with older\n\
+versions.\n\
+\n";
+
+static const char doc_to_integral_exact[] = "\n\
+to_integral_exact([rounding[, context]]) - Round to the nearest integer,\n\
+signaling Inexact or Rounded as appropriate if rounding occurs. The rounding\n\
+mode is determined by the rounding parameter if given, else by the given\n\
+context. If neither parameter is given, then the rounding mode of the current\n\
+default context is used.\n\
+\n";
+
+static const char doc_to_integral_value[] = "\n\
+to_integral_value([rounding[, context]]) - Round to the nearest integer without\n\
+signaling Inexact or Rounded. The rounding mode is determined by the rounding\n\
+parameter if given, else by the given context. If neither parameter is given,\n\
+then the rounding mode of the current default context is used.\n\
+\n";
+
+
+/******************************************************************************/
+/* Decimal Object, Additional Methods */
+/******************************************************************************/
+
+static const char doc_add[] = "\n\
+add(other[, context]) - Return the sum of self and other.\n\
+\n";
+
+static const char doc_apply[] = "\n\
+apply() - Apply the default context to the number.\n\
+\n";
+
+static const char doc_div[] = "\n\
+div(other[, context]) - Divide self by other.\n\
+Alias for divide(other[, context]).\n\
+\n";
+
+static const char doc_divide[] = "\n\
+divide(other[, context]) - Divide self by other.\n\
+\n";
+
+static const char doc_divide_int[] = "\n\
+divide_int(other[, context]) - Truncating division.\n\
+\n";
+
+static const char doc_divint[] = "\n\
+divint(other[, context]) - Truncating division.\n\
+Alias for divide_int(other[, context]).\n\
+\n";
+
+static const char doc_divmod[] = "\n\
+divmod(other[, context]) - Return quotient and remainder of the\n\
+division self / other.\n\
+\n";
+
+static const char doc_invroot[] = "\n\
+invroot([context]) - Return the reciprocal of the square root.\n\
+\n";
+
+static const char doc_is_integer[] = "\n\
+is_integer() - Return True if the argument is an integer and False otherwise.\n\
+\n";
+
+static const char doc_minus[] = "\n\
+minus() - Minus corresponds to the unary prefix minus operator in Python,\n\
+but applies the context precision and rounding.\n\
+\n";
+
+static const char doc_mul[] = "\n\
+mul(other[, context]) - Multiply self by other.\n\
+Alias for multiply(other[, context]).\n\
+\n";
+
+static const char doc_multiply[] = "\n\
+multiply(other[, context]) - Multiply self by other.\n\
+\n";
+
+static const char doc_plus[] = "\n\
+plus() - Plus corresponds to the unary prefix plus operator in Python,\n\
+but applies the context precision and rounding.\n\
+\n";
+
+static const char doc_pow[] = "\n\
+pow(other[, context]) - Raise self to the power of other.\n\
+Alias for power(other[, context]).\n\
+\n";
+
+static const char doc_power[] = "\n\
+power(other[, context]) - Raise self to the power of other.\n\
+\n";
+
+static const char doc_powmod[] = "\n\
+powmod(other, third[, context]) - Return (self ** other) % third.\n\
+\n";
+
+static const char doc_rem[] = "\n\
+rem(other[, context]) - Remainder of the division self / other.\n\
+Alias for remainder(other[, context]).\n\
+\n";
+
+static const char doc_remainder[] = "\n\
+remainder(other[, context]) - Remainder of the division self / other.\n\
+\n";
+
+static const char doc_sub[] = "\n\
+sub(other[, context]) - Subtract other from self.\n\
+Alias for subtract(other[, context]).\n\
+\n";
+
+static const char doc_subtract[] = "\n\
+subtract(other[, context]) - Subtract other from self.\n\
+\n";
+
+static const char doc_sign[] = "\n\
+sign() - Return -1 or 1, depending on the sign of self.\n\
+\n";
+
+static const char doc_to_sci[] = "\n\
+to_sci([context]) - Convert a number to a string using scientific notation.\n\
+Alias for to_sci_string().\n\
+\n";
+
+static const char doc_to_sci_string[] = "\n\
+to_sci_string([context]) - Convert a number to a string using\n\
+scientific notation.\n\
+\n";
+
+
+/******************************************************************************/
+/* Context Object and Methods */
+/******************************************************************************/
+
+static const char doc_context[] = "\n\
+The context affects almost all operations and controls rounding,\n\
+Over/Underflow, raising of exceptions and much more. A new context\n\
+can be constructed as follows:\n\
+\n\
+ >>> c = Context(prec=28, Emin=-425000000, Emax=425000000, \n\
+ rounding=ROUND_HALF_EVEN, capitals=1,\n\
+ traps=[InvalidOperation, DivisionByZero, Overflow],\n\
+ flags=[], _clamp=0, _allcr=1)\n\
+\n\
+\n";
+
+static const char doc_ctx_apply[] = "\n\
+apply(x) - Apply self to Decimal x.\n\
+\n";
+
+static const char doc_ctx_clear_flags[] = "\n\
+clear_flags() - Reset all flags to False.\n\
+\n";
+
+static const char doc_ctx_clear_traps[] = "\n\
+clear_traps() - Set all traps to False.\n\
+\n";
+
+static const char doc_ctx_copy[] = "\n\
+copy() - Return a duplicate of the context with all flags cleared.\n\
+\n";
+
+static const char doc_ctx_copy_decimal[] = "\n\
+copy_decimal(x) - Return a copy of Decimal x.\n\
+\n";
+
+static const char doc_ctx_create_decimal[] = "\n\
+create_decimal(x) - Create a new Decimal instance from x, using self as the\n\
+context. Unlike the Decimal constructor, this function observes the context\n\
+limits.\n\
+\n";
+
+static const char doc_ctx_create_decimal_from_float[] = "\n\
+create_decimal_from_float(f) - Create a new Decimal instance from float f.\n\
+Unlike the Decimal.from_float() class method, this function observes the\n\
+context limits.\n\
+\n";
+
+static const char doc_ctx_Etiny[] = "\n\
+Etiny() - Return a value equal to Emin - prec + 1, which is the minimum\n\
+exponent value for subnormal results. When underflow occurs, the exponent\n\
+is set to Etiny.\n\
+\n";
+
+static const char doc_ctx_Etop[] = "\n\
+Etop() - Return a value equal to Emax - prec + 1. This is the maximum exponent\n\
+if the _clamp field of the context is set to 1 (IEEE clamp mode). Etop() must\n\
+not be negative.\n\
+\n";
+
+static const char doc_ctx_abs[] = "\n\
+abs(x) - Return the absolute value of x.\n\
+\n";
+
+static const char doc_ctx_add[] = "\n\
+add(x, y) - Return the sum of x and y.\n\
+\n";
+
+static const char doc_ctx_canonical[] = "\n\
+canonical(x) - Return a new instance of x.\n\
+\n";
+
+static const char doc_ctx_compare[] = "\n\
+compare(x, y) - Compare x and y numerically.\n\
+\n";
+
+static const char doc_ctx_compare_signal[] = "\n\
+compare_signal(x, y) - Compare x and y numerically. All NaNs signal.\n\
+\n";
+
+static const char doc_ctx_compare_total[] = "\n\
+compare_total(x, y) - Compare x and y using their abstract representation.\n\
+\n";
+
+static const char doc_ctx_compare_total_mag[] = "\n\
+compare_total_mag(x, y) - Compare x and y using their abstract representation,\n\
+ignoring sign.\n\
+\n";
+
+static const char doc_ctx_copy_abs[] = "\n\
+copy_abs(x) - Return a copy of x with the sign set to 0.\n\
+\n";
+
+static const char doc_ctx_copy_negate[] = "\n\
+copy_negate(x) - Return a copy of x with the sign inverted.\n\
+\n";
+
+static const char doc_ctx_copy_sign[] = "\n\
+copy_sign(x, y) - Copy the sign from y to x.\n\
+\n";
+
+static const char doc_ctx_div[] = "\n\
+div(x, y) - Return x divided by y. Alias for divide(x, y).\n\
+\n";
+
+static const char doc_ctx_divide[] = "\n\
+divide(x, y) - Return x divided by y.\n\
+\n";
+
+static const char doc_ctx_divide_int[] = "\n\
+divide_int(x, y) - Return x divided by y, truncated to an integer.\n\
+\n";
+
+static const char doc_ctx_divint[] = "\n\
+divint(x, y) - Return x divided by y, truncated to an integer.\n\
+Alias for divide_int(x, y).\n\
+\n";
+
+static const char doc_ctx_divmod[] = "\n\
+divmod(x, y) - Return quotient and remainder of the division x / y.\n\
+\n";
+
+static const char doc_ctx_exp[] = "\n\
+exp(x) - Return e ** x.\n\
+\n";
+
+static const char doc_ctx_fma[] = "\n\
+fma(x, y, z) - Return x multiplied by y, plus z.\n\
+\n";
+
+static const char doc_ctx_is_canonical[] = "\n\
+is_canonical(x) - Return True if x is canonical, False otherwise.\n\
+\n";
+
+static const char doc_ctx_is_finite[] = "\n\
+is_finite(x) - Return True if x is finite, False otherwise.\n\
+\n";
+
+static const char doc_ctx_is_infinite[] = "\n\
+is_infinite(x) - Return True if x is infinite, False otherwise.\n\
+\n";
+
+static const char doc_ctx_is_nan[] = "\n\
+is_nan(x) - Return True if x is a qNaN or sNaN, False otherwise.\n\
+\n";
+
+static const char doc_ctx_is_normal[] = "\n\
+is_normal(x) - Return True if x is a normal number, False otherwise.\n\
+\n";
+
+static const char doc_ctx_is_qnan[] = "\n\
+is_qnan(x) - Return True if x is a quiet NaN, False otherwise.\n\
+\n";
+
+static const char doc_ctx_is_signed[] = "\n\
+is_signed(x) - Return True if x is negative, False otherwise.\n\
+\n";
+
+static const char doc_ctx_is_snan[] = "\n\
+is_snan() - Return True if x is a signaling NaN, False otherwise.\n\
+\n";
+
+static const char doc_ctx_is_subnormal[] = "\n\
+is_subnormal(x) - Return True if x is subnormal, False otherwise.\n\
+\n";
+
+static const char doc_ctx_is_zero[] = "\n\
+is_zero(x) - Return True if x is a zero, False otherwise.\n\
+\n";
+
+static const char doc_ctx_ln[] = "\n\
+ln(x) - Return the natural (base e) logarithm of x.\n\
+\n";
+
+static const char doc_ctx_log10[] = "\n\
+log10(x) - Return the base 10 logarithm of x.\n\
+\n";
+
+static const char doc_ctx_logb[] = "\n\
+logb(x) - Return the exponent of the magnitude of the operand's MSD.\n\
+\n";
+
+static const char doc_ctx_logical_and[] = "\n\
+logical_and(x, y) - Digit-wise and of x and y.\n\
+\n";
+
+static const char doc_ctx_logical_invert[] = "\n\
+logical_invert(x) - Invert all digits of x.\n\
+\n";
+
+static const char doc_ctx_logical_or[] = "\n\
+logical_or(x, y) - Digit-wise or of x and y.\n\
+\n";
+
+static const char doc_ctx_logical_xor[] = "\n\
+logical_xor(x, y) - Digit-wise xor of x and y.\n\
+\n";
+
+static const char doc_ctx_max[] = "\n\
+max(x, y) - Compare the values numerically and return the maximum.\n\
+\n";
+
+static const char doc_ctx_max_mag[] = "\n\
+max_mag(x, y) - Compare the values numerically with their sign ignored.\n\
+\n";
+
+static const char doc_ctx_min[] = "\n\
+min(x, y) - Compare the values numerically and return the minimum.\n\
+\n";
+
+static const char doc_ctx_min_mag[] = "\n\
+min_mag(x, y) - Compare the values numerically with their sign ignored.\n\
+\n";
+
+static const char doc_ctx_minus[] = "\n\
+minus(x) - Minus corresponds to the unary prefix minus operator in Python,\n\
+but applies the context to the result.\n\
+\n";
+
+static const char doc_ctx_mul[] = "\n\
+mul(x, y) - Return the product of x and y. Alias for multiply(x, y).\n\
+\n";
+
+static const char doc_ctx_multiply[] = "\n\
+multiply(x, y) - Return the product of x and y.\n\
+\n";
+
+static const char doc_ctx_next_minus[] = "\n\
+next_minus(x) - Return the largest representable number smaller than x.\n\
+\n";
+
+static const char doc_ctx_next_plus[] = "\n\
+next_plus(x) - Return the smallest representable number larger than x.\n\
+\n";
+
+static const char doc_ctx_next_toward[] = "\n\
+next_toward(x) - Return the number closest to x, in the direction towards y.\n\
+\n";
+
+static const char doc_ctx_normalize[] = "\n\
+normalize(x) - Reduce x to its simplest form. Alias for reduce(x).\n\
+\n";
+
+static const char doc_ctx_number_class[] = "\n\
+number_class(x) - Return an indication of the class of x.\n\
+\n";
+
+static const char doc_ctx_plus[] = "\n\
+plus(x) - Plus corresponds to the unary prefix plus operator in Python,\n\
+but applies the context to the result.\n\
+\n";
+
+static const char doc_ctx_pow[] = "\n\
+pow(x, y) - Compute x**y. Alias for power(x, y).\n\
+\n";
+
+static const char doc_ctx_power[] = "\n\
+power(x, y) - Compute x**y. If x is negative, then y must be integral.\n\
+The result will be inexact unless y is integral and the result is finite\n\
+and can be expressed exactly in 'precision' digits.\n\
+\n";
+
+static const char doc_ctx_powmod[] = "\n\
+powmod(x, y, m) - Compute (x**y) % m. The following restrictions hold:\n\
+\n\
+ * all three arguments must be integral\n\
+ * y must be nonnegative\n\
+ * at least one of x or y must be nonzero\n\
+ * m must be nonzero\n\
+\n\
+\n";
+
+static const char doc_ctx_quantize[] = "\n\
+quantize(x, y) - Return a value equal to x (rounded), having the exponent of y.\n\
+\n";
+
+static const char doc_ctx_radix[] = "\n\
+radix() - Return 10.\n\
+\n";
+
+static const char doc_ctx_reduce[] = "\n\
+reduce(x) - Reduce x to its simplest form.\n\
+\n";
+
+static const char doc_ctx_rem[] = "\n\
+rem(x, y) - Return the remainder from integer division. The sign of\n\
+the result, if non-zero, is the same as that of the original dividend.\n\
+\n\
+Alias for remainder(x, y).\n\
+\n";
+
+static const char doc_ctx_remainder[] = "\n\
+remainder(x, y) - Return the remainder from integer division. The sign of\n\
+the result, if non-zero, is the same as that of the original dividend.\n\
+\n";
+
+static const char doc_ctx_remainder_near[] = "\n\
+remainder_near(x, y) - Return x - y * n, where n is the integer nearest the\n\
+exact value of x / y (if the result is 0 then its sign will be the sign of x).\n\
+\n";
+
+static const char doc_ctx_rotate[] = "\n\
+rotate(x, y) - Return a copy of x, rotated by y places.\n\
+\n";
+
+static const char doc_ctx_same_quantum[] = "\n\
+same_quantum(x, y) - Return True if the two operands have the same exponent.\n\
+\n";
+
+static const char doc_ctx_scaleb[] = "\n\
+scaleb(x, y) - Return the first operand after adding the second value\n\
+to its exp.\n\
+\n";
+
+static const char doc_ctx_shift[] = "\n\
+shift(x, y) - Return a copy of x, shifted by y places.\n\
+\n";
+
+static const char doc_ctx_sqrt[] = "\n\
+sqrt(x) - Square root of a non-negative number to context precision.\n\
+\n";
+
+static const char doc_ctx_sub[] = "\n\
+sub(x, y) - Return the difference between x and y. Alias for subtract(x, y).\n\
+\n";
+
+static const char doc_ctx_subtract[] = "\n\
+subtract(x, y) - Return the difference between x and y.\n\
+\n";
+
+static const char doc_ctx_to_eng[] = "\n\
+to_eng(x) - Convert a number to a string, using engineering notation.\n\
+Alias for to_eng_string(x).\n\
+\n";
+
+static const char doc_ctx_to_eng_string[] = "\n\
+to_eng_string(x) - Convert a number to a string, using engineering notation.\n\
+\n";
+
+static const char doc_ctx_to_integral[] = "\n\
+to_integral(x) - Identical to to_integral_value(x).\n\
+\n";
+
+static const char doc_ctx_to_integral_exact[] = "\n\
+to_integral_exact(x) - Round to an integer. Signal if the result is\n\
+rounded or inexact.\n\
+\n";
+
+static const char doc_ctx_to_integral_value[] = "\n\
+to_integral_value(x) - Round to an integer.\n\
+\n";
+
+static const char doc_ctx_to_sci[] = "\n\
+to_sci(x) - Convert a number to a string using scientific notation.\n\
+Alias for to_sci_string(x).\n\
+\n";
+
+static const char doc_ctx_to_sci_string[] = "\n\
+to_sci_string(x) - Convert a number to a string using scientific notation.\n\
+\n";
+
+/******************************************************************************/
+/* Context Object, Additional Methods */
+/******************************************************************************/
+
+static const char doc_ctx_invroot[] = "\n\
+invroot(x) - Return the reciprocal of the square root of x.\n\
+\n";
+
+static const char doc_ctx_setflags[] = "\n\
+setflags(list) - Set the context flags from a list containing signals.\n\
+\n";
+
+static const char doc_ctx_settraps[] = "\n\
+settraps(list) - Set the context traps from a list containing signals.\n\
+\n";
+
+
+#endif
+
+
+
Added: python/branches/py3k-cdecimal/Modules/cdecimal/error.c
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/error.c Thu Jan 7 13:02:51 2010
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#include <stdio.h>
+#include <stdarg.h>
+
+
+#include "mpdecimal.h"
+
+
+void mpd_err_doit(int action, const char *fmt, ...)
+{
+ va_list ap;
+
+ va_start(ap, fmt);
+ vfprintf(stderr, fmt, ap);
+ fputc('\n', stderr);
+ va_end(ap);
+
+ if (action == MPD_ERR_EXIT) {
+ exit(EXIT_FAILURE);
+ }
+}
+
Added: python/branches/py3k-cdecimal/Modules/cdecimal/fnt.c
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/fnt.c Thu Jan 7 13:02:51 2010
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <assert.h>
+#include "bits.h"
+#include "difradix2.h"
+#include "mpdecimal.h"
+#include "numbertheory.h"
+#include "fnt.h"
+
+
+/* forward transform, sign = -1 */
+int
+std_fnt(mpd_uint_t *a, size_t n, int modnum, int ordered UNUSED)
+{
+ struct fnt_params *tparams;
+
+ assert(ispower2(n));
+ assert(n >= 4);
+ assert(n <= 3*MPD_MAXTRANSFORM_2N);
+
+ if ((tparams = _mpd_init_fnt_params(n, -1, modnum)) == NULL) {
+ return 0;
+ }
+ fnt_dif2(a, n, tparams);
+
+ mpd_free(tparams);
+ return 1;
+}
+
+/* reverse transform, sign = 1 */
+int
+std_inv_fnt(mpd_uint_t *a, size_t n, int modnum, int ordered UNUSED)
+{
+ struct fnt_params *tparams;
+
+ assert(ispower2(n));
+ assert(n >= 4);
+ assert(n <= 3*MPD_MAXTRANSFORM_2N);
+
+ if ((tparams = _mpd_init_fnt_params(n, 1, modnum)) == NULL) {
+ return 0;
+ }
+ fnt_dif2(a, n, tparams);
+
+ mpd_free(tparams);
+ return 1;
+}
+
+
+
Added: python/branches/py3k-cdecimal/Modules/cdecimal/fnt.h
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/fnt.h Thu Jan 7 13:02:51 2010
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#ifndef FNT_H
+#define FNT_H
+
+
+#include <stdio.h>
+#include "mpdecimal.h"
+
+int std_fnt(mpd_uint_t a[], size_t n, int modnum, int ordered UNUSED);
+int std_inv_fnt(mpd_uint_t a[], size_t n, int modnum, int ordered UNUSED);
+
+
+#endif
+
Added: python/branches/py3k-cdecimal/Modules/cdecimal/fourstep.c
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/fourstep.c Thu Jan 7 13:02:51 2010
@@ -0,0 +1,238 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#include <assert.h>
+#include "mpdecimal.h"
+#include "numbertheory.h"
+#include "sixstep.h"
+#include "transpose.h"
+#include "umodarith.h"
+#include "fourstep.h"
+
+
+/*
+ * A variant of the four-step algorithm from:
+ *
+ * David H. Bailey: FFTs in External or Hierarchical Memory, Journal of
+ * Supercomputing, vol. 4, no. 1 (March 1990), p. 23-35.
+ *
+ * URL: http://crd.lbl.gov/~dhbailey/dhbpapers/
+ */
+
+
+#ifndef PPRO
+static inline void
+std_size3_ntt(mpd_uint_t *x1, mpd_uint_t *x2, mpd_uint_t *x3,
+ mpd_uint_t w3table[3], mpd_uint_t umod)
+{
+ mpd_uint_t r1, r2;
+ mpd_uint_t w;
+ mpd_uint_t s, tmp;
+
+
+ /* k = 0 -> w = 1 */
+ s = *x1;
+ s = addmod(s, *x2, umod);
+ s = addmod(s, *x3, umod);
+
+ r1 = s;
+
+ /* k = 1 */
+ s = *x1;
+
+ w = w3table[1];
+ tmp = MULMOD(*x2, w);
+ s = addmod(s, tmp, umod);
+
+ w = w3table[2];
+ tmp = MULMOD(*x3, w);
+ s = addmod(s, tmp, umod);
+
+ r2 = s;
+
+ /* k = 2 */
+ s = *x1;
+
+ w = w3table[2];
+ tmp = MULMOD(*x2, w);
+ s = addmod(s, tmp, umod);
+
+ w = w3table[1];
+ tmp = MULMOD(*x3, w);
+ s = addmod(s, tmp, umod);
+
+ *x3 = s;
+ *x2 = r2;
+ *x1 = r1;
+}
+#else /* PPRO */
+static inline void
+ppro_size3_ntt(mpd_uint_t *x1, mpd_uint_t *x2, mpd_uint_t *x3, mpd_uint_t w3table[3],
+ mpd_uint_t umod, double *dmod, uint32_t dinvmod[3])
+{
+ mpd_uint_t r1, r2;
+ mpd_uint_t w;
+ mpd_uint_t s, tmp;
+
+
+ /* k = 0 -> w = 1 */
+ s = *x1;
+ s = addmod(s, *x2, umod);
+ s = addmod(s, *x3, umod);
+
+ r1 = s;
+
+ /* k = 1 */
+ s = *x1;
+
+ w = w3table[1];
+ tmp = ppro_mulmod(*x2, w, dmod, dinvmod);
+ s = addmod(s, tmp, umod);
+
+ w = w3table[2];
+ tmp = ppro_mulmod(*x3, w, dmod, dinvmod);
+ s = addmod(s, tmp, umod);
+
+ r2 = s;
+
+ /* k = 2 */
+ s = *x1;
+
+ w = w3table[2];
+ tmp = ppro_mulmod(*x2, w, dmod, dinvmod);
+ s = addmod(s, tmp, umod);
+
+ w = w3table[1];
+ tmp = ppro_mulmod(*x3, w, dmod, dinvmod);
+ s = addmod(s, tmp, umod);
+
+ *x3 = s;
+ *x2 = r2;
+ *x1 = r1;
+}
+#endif
+
+
+/* forward transform, sign = -1; transform length = 3 * 2^n */
+int
+four_step_fnt(mpd_uint_t *a, size_t n, int modnum, int ordered)
+{
+ size_t R = 3; /* number of rows */
+ size_t C = n / 3; /* number of columns */
+ mpd_uint_t w3table[3];
+ mpd_uint_t kernel, w0, w1, wstep;
+ mpd_uint_t *s, *p0, *p1, *p2;
+ mpd_uint_t umod;
+#ifdef PPRO
+ double dmod;
+ uint32_t dinvmod[3];
+#endif
+ size_t i, k;
+
+
+ assert(n >= 48);
+ assert(n <= 3*MPD_MAXTRANSFORM_2N);
+
+
+ SETMODULUS(modnum);
+ _mpd_init_w3table(w3table, -1, modnum);
+ /* size three ntt on the columns */
+ for (p0=a, p1=p0+C, p2=p0+2*C; p0<a+C; p0++,p1++,p2++) {
+
+ SIZE3_NTT(p0, p1, p2, w3table);
+ }
+
+
+ kernel = _mpd_getkernel(n, -1, modnum);
+ for (i = 1; i < R; i++) {
+ w0 = 1;
+ w1 = POWMOD(kernel, i);
+ wstep = MULMOD(w1, w1);
+ for (k = 0; k < C-1; k += 2) {
+ mpd_uint_t x0 = a[i*C+k];
+ mpd_uint_t x1 = a[i*C+k+1];
+ MULMOD2(&x0, w0, &x1, w1);
+ MULMOD2C(&w0, &w1, wstep);
+ a[i*C+k] = x0;
+ a[i*C+k+1] = x1;
+ }
+ }
+
+ /* transform rows */
+ for (s = a; s < a+n; s += C) {
+ if (!six_step_fnt(s, C, modnum, ordered)) {
+ return 0;
+ }
+ }
+
+ if (ordered) {
+ transpose_3xpow2(a, R, C);
+ }
+
+ return 1;
+}
+
+/* backward transform, sign = 1; transform length = 3 * 2^n */
+int
+inv_four_step_fnt(mpd_uint_t *a, size_t n, int modnum, int ordered)
+{
+ size_t R = 3; /* number of rows */
+ size_t C = n / 3; /* number of columns */
+ mpd_uint_t w3table[3];
+ mpd_uint_t kernel, w0, w1, wstep;
+ mpd_uint_t *s, *p0, *p1, *p2;
+ mpd_uint_t umod;
+#ifdef PPRO
+ double dmod;
+ uint32_t dinvmod[3];
+#endif
+ size_t i, k;
+
+
+ assert(n >= 48);
+ assert(n <= 3*MPD_MAXTRANSFORM_2N);
+
+
+ if (ordered) {
+ transpose_3xpow2(a, C, R);
+ }
+
+ /* transform rows */
+ for (s = a; s < a+n; s += C) {
+ if (!inv_six_step_fnt(s, C, modnum, ordered)) {
+ return 0;
+ }
+ }
+
+
+ SETMODULUS(modnum);
+ kernel = _mpd_getkernel(n, 1, modnum);
+ for (i = 1; i < R; i++) {
+ w0 = 1;
+ w1 = POWMOD(kernel, i);
+ wstep = MULMOD(w1, w1);
+ for (k = 0; k < C; k += 2) {
+ mpd_uint_t x0 = a[i*C+k];
+ mpd_uint_t x1 = a[i*C+k+1];
+ MULMOD2(&x0, w0, &x1, w1);
+ MULMOD2C(&w0, &w1, wstep);
+ a[i*C+k] = x0;
+ a[i*C+k+1] = x1;
+ }
+ }
+
+
+ _mpd_init_w3table(w3table, 1, modnum);
+ /* size three ntt on the columns */
+ for (p0=a, p1=p0+C, p2=p0+2*C; p0<a+C; p0++,p1++,p2++) {
+
+ SIZE3_NTT(p0, p1, p2, w3table);
+ }
+
+ return 1;
+}
+
+
Added: python/branches/py3k-cdecimal/Modules/cdecimal/fourstep.h
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/fourstep.h Thu Jan 7 13:02:51 2010
@@ -0,0 +1,18 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#ifndef FOUR_STEP_H
+#define FOUR_STEP_H
+
+
+#include <stdio.h>
+#include "mpdecimal.h"
+
+int four_step_fnt(mpd_uint_t *a, size_t n, int modnum, int ordered);
+int inv_four_step_fnt(mpd_uint_t *a, size_t n, int modnum, int ordered);
+
+
+#endif
Added: python/branches/py3k-cdecimal/Modules/cdecimal/io.c
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/io.c Thu Jan 7 13:02:51 2010
@@ -0,0 +1,1349 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+#include <limits.h>
+#include <assert.h>
+#include <errno.h>
+#include <locale.h>
+#include "bits.h"
+#include "constants.h"
+#include "memory.h"
+#include "mpdecimal.h"
+#include "typearith.h"
+
+
+/*
+ * Work around the behavior of tolower() and strcasecmp() in certain
+ * locales. For example, in tr_TR.utf8:
+ *
+ * tolower((unsigned char)'I') == 'I'
+ *
+ * u is the exact uppercase version of l; n is strlen(l) or strlen(l)+1
+ */
+static inline int
+_mpd_strneq(const char *s, const char *l, const char *u, size_t n)
+{
+ while (--n != SIZE_MAX) {
+ if (*s != *l && *s != *u) {
+ return 0;
+ }
+ s++; u++; l++;
+ }
+
+ return 1;
+}
+
+static mpd_ssize_t
+strtoexp(const char *s)
+{
+ char *end;
+ mpd_ssize_t retval;
+
+ errno = 0;
+ retval = mpd_strtossize(s, &end, 10);
+ if (errno == 0 && !(*s != '\0' && *end == '\0'))
+ errno = EINVAL;
+
+ return retval;
+}
+
+
+/*
+ * Scan 'len' words. The most significant word contains 'r' digits,
+ * the remaining words are full words. Skip dpoint. The string 's' must
+ * consist of digits and an optional single decimal point at 'dpoint'.
+ */
+static void
+string_to_coeff(mpd_uint_t *data, const char *s, const char *dpoint, int r,
+ size_t len)
+{
+ int j;
+
+ if (r > 0) {
+ data[--len] = 0;
+ for (j = 0; j < r; j++, s++) {
+ if (s == dpoint) s++;
+ data[len] = 10 * data[len] + (*s - '0');
+ }
+ }
+
+ while (--len != SIZE_MAX) {
+ data[len] = 0;
+ for (j = 0; j < MPD_RDIGITS; j++, s++) {
+ if (s == dpoint) s++;
+ data[len] = 10 * data[len] + (*s - '0');
+ }
+ }
+}
+
+/*
+ * Scan for at most one decimal point and at most one indicator.
+ * Remove unneeded zeros before and after the decimal point.
+ * The first relevant digit will be the start of the coefficient.
+ * A decimal point may occur before an indicator.
+ * Plus or minus may occur directly after the indicator.
+ * The rest of the characters must be decimal digits.
+ *
+ * Return start of the coefficient or NULL or error. The end of
+ * the string is stored in 'end'.
+ */
+static const char *
+scan_dpoint_exp(const char *s, const char **dpoint, const char **exp,
+ const char **end)
+{
+ const char *coeff = NULL;
+
+ *dpoint = NULL;
+ *exp = NULL;
+ for (; *s != '\0'; s++) {
+ switch (*s) {
+ case '.':
+ if (*dpoint != NULL || *exp != NULL)
+ return NULL;
+ *dpoint = s;
+ break;
+ case 'E': case 'e':
+ if (*exp != NULL)
+ return NULL;
+ *exp = s;
+ if (*(s+1) == '+' || *(s+1) == '-')
+ s++;
+ break;
+ default:
+ if (!isdigit((uchar)*s))
+ return NULL;
+ if (coeff == NULL && *exp == NULL) {
+ if (*s == '0') {
+ if (!isdigit((uchar)*(s+1)))
+ if (!(*(s+1) == '.' &&
+ isdigit((uchar)*(s+2))))
+ coeff = s;
+ }
+ else {
+ coeff = s;
+ }
+ }
+ break;
+
+ }
+ }
+
+ *end = s;
+ return coeff;
+}
+
+/* scan the payload of a NaN */
+static const char *
+scan_payload(const char *s, const char **end)
+{
+ const char *coeff;
+
+ while (*s == '0')
+ s++;
+ coeff = s;
+
+ while (isdigit((uchar)*s))
+ s++;
+ *end = s;
+
+ return (*s == '\0') ? coeff : NULL;
+}
+
+/* convert a character string to a decimal */
+void
+mpd_qset_string(mpd_t *dec, const char *s, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ mpd_ssize_t q, r, declen;
+ const char *coeff, *end;
+ const char *dpoint = NULL, *exp = NULL;
+ size_t len;
+ uint8_t sign = MPD_POS;
+
+ dec->flags = 0;
+ dec->len = 0;
+ dec->exp = 0;
+
+ /* [flags] */
+ if (*s == '+') {
+ s++;
+ }
+ else if (*s == '-') {
+ mpd_set_negative(dec);
+ sign = MPD_NEG;
+ s++;
+ }
+
+ if (_mpd_strneq(s, "nan", "NAN", 3)) { /* NaN */
+ s += 3;
+ mpd_setspecial(dec, sign, MPD_NAN);
+ if (*s == '\0')
+ return;
+ /* only digits for the diagnostic code */
+ if ((coeff = scan_payload(s, &end)) == NULL)
+ goto conversion_error;
+ /* payload consists entirely of zeros */
+ if (*coeff == '\0')
+ return;
+ len = end - coeff;
+ /* prec >= 1, clamp is 0 or 1 */
+ if (len > (size_t)(ctx->prec-ctx->clamp))
+ goto conversion_error;
+ } /* sNaN */
+ else if (_mpd_strneq(s, "snan", "SNAN", 4)) {
+ s += 4;
+ mpd_setspecial(dec, sign, MPD_SNAN);
+ if (*s == '\0')
+ return;
+ /* only digits for the diagnostic code */
+ if ((coeff = scan_payload(s, &end)) == NULL)
+ goto conversion_error;
+ /* payload consists entirely of zeros */
+ if (*coeff == '\0')
+ return;
+ len = end - coeff;
+ if (len > (size_t)(ctx->prec-ctx->clamp))
+ goto conversion_error;
+ }
+ else if (_mpd_strneq(s, "inf", "INF", 3)) {
+ s += 3;
+ if (*s == '\0' || _mpd_strneq(s, "inity", "INITY", 6)) {
+ /* numeric-value: infinity */
+ mpd_setspecial(dec, sign, MPD_INF);
+ return;
+ }
+ goto conversion_error;
+ }
+ else {
+ /* scan for start of coefficient, decimal point, indicator, end */
+ if ((coeff = scan_dpoint_exp(s, &dpoint, &exp, &end)) == NULL)
+ goto conversion_error;
+
+ /* numeric-value: [exponent-part] */
+ if (exp) {
+ /* exponent-part */
+ end = exp; exp++;
+ dec->exp = strtoexp(exp);
+ if (errno == EINVAL)
+ goto conversion_error;
+ if ((errno == ERANGE && dec->exp == MPD_SSIZE_MAX)
+ || dec->exp > MPD_EXP_INF)
+ dec->exp = MPD_EXP_INF;
+ else if ((errno == ERANGE && dec->exp == MPD_SSIZE_MIN)
+ || dec->exp < MPD_EXP_CLAMP)
+ dec->exp = MPD_EXP_CLAMP;
+ }
+
+ len = end - coeff;
+ if (dpoint) {
+ dec->exp -= (end-dpoint-1);
+ if (dpoint > coeff) len--;
+ }
+ if (len > MPD_MAX_PREC) {
+ goto conversion_error;
+ }
+ }
+
+ _mpd_idiv_word(&q, &r, (mpd_ssize_t)len, MPD_RDIGITS);
+
+ declen = (r == 0) ? q : q+1;
+ if (declen == 0) {
+ goto conversion_error;
+ }
+ if (!mpd_qresize(dec, declen, status)) {
+ mpd_seterror(dec, MPD_Malloc_error, status);
+ return;
+ }
+ dec->len = declen;
+
+ string_to_coeff(dec->data, coeff, dpoint, (int)r, declen);
+
+ mpd_setdigits(dec);
+ mpd_qfinalize(dec, ctx, status);
+ return;
+
+conversion_error:
+ /* standard wants a positive NaN */
+ mpd_seterror(dec, MPD_Conversion_syntax, status);
+}
+
+/* print the exponent to a string */
+static inline char *
+exp_to_string(char *s, mpd_ssize_t x, int print_sign)
+{
+ mpd_ssize_t q, d;
+ char sign = '+';
+ int j;
+
+ if (x < 0) {
+ sign = '-';
+ x = -x;
+ }
+
+ if (print_sign)
+ *s++ = sign;
+
+ j = mpd_exp_digits(x) - 1;
+
+ for (; j != 0; --j) {
+ d = mpd_pow10[j];
+ q = x / d;
+ x -= d * q;
+ *s++ = '0' + q;
+ }
+ *s++ = '0' + x;
+
+ return s;
+}
+
+/* print coefficient to string, len(dec) > 0 */
+static inline char *
+coeff_to_string(char *s, const mpd_t *dec)
+{
+ mpd_uint_t x, q, d;
+ mpd_ssize_t i;
+ int j;
+
+ /* most significant word */
+ x = mpd_msword(dec);
+ j = mpd_word_digits(x) - 1;
+
+ for (; j != 0; --j) {
+ d = mpd_pow10[j];
+ q = x / d;
+ x -= d * q;
+ *s++ = '0' + q;
+ }
+ *s++ = '0' + x;
+
+ /* remaining full words */
+ for (i=dec->len-2; i >= 0; --i) {
+ x = dec->data[i];
+ for (j=MPD_RDIGITS-1; j != 0; --j) {
+ d = mpd_pow10[j];
+ q = x / d;
+ x -= d * q;
+ *s++ = '0' + q;
+ }
+ *s++ = '0' + x;
+ }
+
+ return s;
+}
+
+/* print coefficient to string, len(dec) > 0 */
+static inline char *
+coeff_to_string_dot(char *s, char *dot, const mpd_t *dec)
+{
+ mpd_uint_t x, q, d;
+ mpd_ssize_t i;
+ int j;
+
+ /* most significant word */
+ x = mpd_msword(dec);
+ j = mpd_word_digits(x) - 1;
+
+ for (; j >= 0; --j) {
+ if (s == dot)
+ *s++ = '.';
+ d = mpd_pow10[j];
+ q = x / d;
+ x -= d * q;
+ *s++ = '0' + q;
+ }
+
+ /* remaining full words */
+ for (i=dec->len-2; i >= 0; --i) {
+ x = dec->data[i];
+ for (j=MPD_RDIGITS-1; j >= 0; --j) {
+ if (s == dot)
+ *s++ = '.';
+ d = mpd_pow10[j];
+ q = x / d;
+ x -= d * q;
+ *s++ = '0' + q;
+ }
+ }
+
+ return s;
+}
+
+/* Format type */
+#define MPD_FMT_LOWER 0x00000000
+#define MPD_FMT_UPPER 0x00000001
+#define MPD_FMT_TOSCI 0x00000002
+#define MPD_FMT_TOENG 0x00000004
+#define MPD_FMT_EXP 0x00000008
+#define MPD_FMT_FIXED 0x00000010
+#define MPD_FMT_PERCENT 0x00000020
+#define MPD_FMT_SIGN_SPACE 0x00000040
+#define MPD_FMT_SIGN_PLUS 0x00000080
+
+/*
+ * Return the string representation of a decimal. Formatting is done according
+ * to 'flags'. A return value of NULL indicates MPD_Malloc_error.
+ *
+ * To allow formatting like [0e15, '.6e' -> 0.000000e-9], 'zeroexp' is used
+ * in combination with MPD_FMT_FIXED (see mpd_qformat for details).
+ */
+static char *
+_mpd_to_string(const mpd_t *dec, int flags, mpd_ssize_t zeroexp)
+{
+ char *decstring = NULL, *cp = NULL;
+ mpd_ssize_t ldigits, dplace;
+ mpd_ssize_t mem = 0, k;
+
+ if (mpd_isspecial(dec)) {
+
+ mem = sizeof "-Infinity";
+ if (mpd_isnan(dec) && dec->len > 0) {
+ /* diagnostic code */
+ mem += dec->digits;
+ }
+ cp = decstring = mpd_alloc(mem, sizeof *decstring);
+ if (cp == NULL) {
+ return NULL;
+ }
+
+ if (mpd_isnegative(dec)) {
+ *cp++ = '-';
+ }
+ else if (flags&MPD_FMT_SIGN_SPACE) {
+ *cp++ = ' ';
+ }
+ else if (flags&MPD_FMT_SIGN_PLUS) {
+ *cp++ = '+';
+ }
+
+ if (mpd_isnan(dec)) {
+ if (mpd_isqnan(dec)) {
+ strcpy(cp, "NaN");
+ cp += 3;
+ }
+ else {
+ strcpy(cp, "sNaN");
+ cp += 4;
+ }
+ if (dec->len > 0) { /* diagnostic code */
+ cp = coeff_to_string(cp, dec);
+ }
+ }
+ else if (mpd_isinfinite(dec)) {
+ strcpy(cp, "Infinity");
+ cp += 8;
+ }
+ else { /* debug */
+ abort();
+ }
+ }
+ else {
+ assert(dec->len > 0);
+
+ /*
+ * ldigits: Digits to the left of the decimal point, as if the
+ * number was written without exponent notation.
+ *
+ * dplace: Position of the decimal point relative to the first
+ * member of the coefficient.
+ *
+ * 0.00000_.____._____000000.
+ * ^ ^ ^ ^
+ * | | | |
+ * | | | `- dplace in the last position
+ * | | `- dplace in the middle of the coefficient
+ * | ` dplace = 1 (after the first coefficient digit)
+ * `- dplace is negative
+ */
+
+ ldigits = dec->digits + dec->exp;
+ dplace = 1; /* default for MPD_FMT_TOSCI, MPD_FMT_EXP */
+
+ if (flags&MPD_FMT_EXP) {
+ ;
+ }
+ else if (flags&MPD_FMT_FIXED || (dec->exp <= 0 && ldigits > -6)) {
+ /* MPD_FMT_FIXED: always use fixed point notation.
+ * MPD_FMT_TOSCI, MPD_FMT_TOENG: for a certain range,
+ * override exponent notation. */
+ dplace = ldigits;
+ }
+ else if (flags&MPD_FMT_TOENG) {
+ if (mpd_iszero(dec)) {
+ /* If the exponent is divisible by three,
+ * dplace = 1. Otherwise, move dplace one
+ * or two places to the left. */
+ dplace = -1 + mod_mpd_ssize_t(dec->exp+2, 3);
+ }
+ else { /* ldigits-1 is the adjusted exponent, which
+ * should be divisible by three. If not, move
+ * dplace one or two places to the right. */
+ dplace += mod_mpd_ssize_t(ldigits-1, 3);
+ }
+ }
+
+ /*
+ * Basic space requirements:
+ *
+ * [-][.][coeffdigits][E][-][expdigits+1][%]['\0']
+ *
+ * If the decimal point lies outside of the coefficient digits,
+ * space is adjusted accordingly.
+ */
+ if (dplace <= 0) {
+ mem = -dplace + dec->digits + 2;
+ }
+ else if (dplace >= dec->digits) {
+ mem = dplace;
+ }
+ else {
+ mem = dec->digits;
+ }
+ mem += (MPD_EXPDIGITS+1+6);
+
+ cp = decstring = mpd_alloc(mem, sizeof *decstring);
+ if (cp == NULL) {
+ return NULL;
+ }
+
+
+ if (mpd_isnegative(dec)) {
+ *cp++ = '-';
+ }
+ else if (flags&MPD_FMT_SIGN_SPACE) {
+ *cp++ = ' ';
+ }
+ else if (flags&MPD_FMT_SIGN_PLUS) {
+ *cp++ = '+';
+ }
+
+ if (dplace <= 0) {
+ /* space: -dplace+dec->digits+2 */
+ *cp++ = '0';
+ *cp++ = '.';
+ for (k = 0; k < -dplace; k++) {
+ *cp++ = '0';
+ }
+ cp = coeff_to_string(cp, dec);
+ }
+ else if (dplace >= dec->digits) {
+ /* space: dplace */
+ cp = coeff_to_string(cp, dec);
+ for (k = 0; k < dplace-dec->digits; k++) {
+ *cp++ = '0';
+ }
+ }
+ else {
+ /* space: dec->digits+1 */
+ cp = coeff_to_string_dot(cp, cp+dplace, dec);
+ }
+
+ /*
+ * Conditions for printing an exponent:
+ *
+ * MPD_FMT_TOSCI, MPD_FMT_TOENG: only if ldigits != dplace
+ * MPD_FMT_FIXED: never (ldigits == dplace)
+ * MPD_FMT_EXP: always
+ * MPD_FMT_FIXED with zeroexp: always
+ */
+ if (ldigits != dplace || flags&MPD_FMT_EXP || zeroexp != MPD_SSIZE_MAX) {
+ /* space: expdigits+2 */
+ mpd_ssize_t x = (zeroexp != MPD_SSIZE_MAX) ? zeroexp : ldigits-dplace;
+ *cp++ = (flags&MPD_FMT_UPPER) ? 'E' : 'e';
+ cp = exp_to_string(cp, x, 1);
+ }
+
+ if (flags&MPD_FMT_PERCENT) {
+ *cp++ = '%';
+ }
+ }
+
+ assert(cp < decstring+mem);
+ *cp = '\0';
+ return decstring;
+}
+
+char *
+mpd_to_sci(const mpd_t *dec, int fmt)
+{
+ int flags = MPD_FMT_TOSCI;
+
+ flags |= fmt ? MPD_FMT_UPPER : MPD_FMT_LOWER;
+ return _mpd_to_string(dec, flags, MPD_SSIZE_MAX);
+}
+
+char *
+mpd_to_eng(const mpd_t *dec, int fmt)
+{
+ int flags = MPD_FMT_TOENG;
+
+ flags |= fmt ? MPD_FMT_UPPER : MPD_FMT_LOWER;
+ return _mpd_to_string(dec, flags, MPD_SSIZE_MAX);
+}
+
+/* Copy a single UTF-8 char to dest. */
+static int
+_mpd_copy_utf8(char dest[5], const char *s)
+{
+ const uchar *cp = (const uchar *)s;
+ uchar lb, ub;
+ int count, i;
+
+
+ if (*cp == 0) {
+ /* empty string */
+ dest[0] = '\0';
+ return 0;
+ }
+ else if (*cp <= 0x7f) {
+ /* ascii */
+ dest[0] = *cp;
+ dest[1] = '\0';
+ return 1;
+ }
+ else if (0xc2 <= *cp && *cp <= 0xdf) {
+ lb = 0x80; ub = 0xbf;
+ count = 2;
+ }
+ else if (*cp == 0xe0) {
+ lb = 0xa0; ub = 0xbf;
+ count = 3;
+ }
+ else if (*cp <= 0xec) {
+ lb = 0x80; ub = 0xbf;
+ count = 3;
+ }
+ else if (*cp == 0xed) {
+ lb = 0x80; ub = 0x9f;
+ count = 3;
+ }
+ else if (*cp <= 0xef) {
+ lb = 0x80; ub = 0xbf;
+ count = 3;
+ }
+ else if (*cp == 0xf0) {
+ lb = 0x90; ub = 0xbf;
+ count = 4;
+ }
+ else if (*cp <= 0xf3) {
+ lb = 0x80; ub = 0xbf;
+ count = 4;
+ }
+ else if (*cp == 0xf4) {
+ lb = 0x80; ub = 0x8f;
+ count = 4;
+ }
+ else {
+ /* invalid */
+ goto error;
+ }
+
+ dest[0] = *cp++;
+ if (*cp < lb || ub < *cp) {
+ goto error;
+ }
+ dest[1] = *cp++;
+ for (i = 2; i < count; i++) {
+ if (*cp < 0x80 || 0xbf < *cp) {
+ goto error;
+ }
+ dest[i] = *cp++;
+ }
+ dest[i] = '\0';
+
+ return count;
+
+error:
+ dest[0] = '\0';
+ return -1;
+}
+
+int
+mpd_parse_fmt_str(mpd_spec_t *spec, const char *fmt)
+{
+ char *cp = (char *)fmt;
+ int have_align = 0, n;
+
+ /* defaults */
+ spec->min_width = 0;
+ spec->prec = -1;
+ spec->type = 'G';
+ spec->align = '>';
+ spec->sign = '-';
+ spec->dot = "";
+ spec->sep = "";
+ spec->grouping = "";
+
+
+ /* presume that the first character is a UTF-8 fill character */
+ if ((n = _mpd_copy_utf8(spec->fill, cp)) < 0) {
+ return 0;
+ }
+
+ /* alignment directive, prefixed by a fill character */
+ if (*cp && (*(cp+n) == '<' || *(cp+n) == '>' ||
+ *(cp+n) == '=' || *(cp+n) == '^')) {
+ cp += n;
+ spec->align = *cp++;
+ have_align = 1;
+ } /* alignment directive */
+ else {
+ /* default fill character */
+ spec->fill[0] = ' ';
+ spec->fill[1] = '\0';
+ if (*cp == '<' || *cp == '>' ||
+ *cp == '=' || *cp == '^') {
+ spec->align = *cp++;
+ have_align = 1;
+ }
+ }
+
+ /* sign formatting */
+ if (*cp == '+' || *cp == '-' || *cp == ' ') {
+ spec->sign = *cp++;
+ }
+
+ /* zero padding */
+ if (*cp == '0') {
+ /* zero padding implies alignment, which should not be
+ * specified twice. */
+ if (have_align) {
+ return 0;
+ }
+ spec->align = 'z';
+ spec->fill[0] = *cp++;
+ spec->fill[1] = '\0';
+ }
+
+ /* minimum width */
+ if (isdigit((uchar)*cp)) {
+ if (*cp == '0') {
+ return 0;
+ }
+ errno = 0;
+ spec->min_width = mpd_strtossize(cp, &cp, 10);
+ if (errno == ERANGE || errno == EINVAL) {
+ return 0;
+ }
+ }
+
+ /* thousands separator */
+ if (*cp == ',') {
+ spec->dot = ".";
+ spec->sep = ",";
+ spec->grouping = "\003\003";
+ cp++;
+ }
+
+ /* fraction digits or significant digits */
+ if (*cp == '.') {
+ cp++;
+ if (!isdigit((uchar)*cp)) {
+ return 0;
+ }
+ errno = 0;
+ spec->prec = mpd_strtossize(cp, &cp, 10);
+ if (errno == ERANGE || errno == EINVAL) {
+ return 0;
+ }
+ }
+
+ /* type */
+ if (*cp == 'E' || *cp == 'e' || *cp == 'F' || *cp == 'f' ||
+ *cp == 'G' || *cp == 'g' || *cp == '%') {
+ spec->type = *cp++;
+ }
+ else if (*cp == 'N' || *cp == 'n') {
+ /* locale specific conversion */
+ struct lconv *lc;
+ spec->type = *cp++;
+ /* separator has already been specified */
+ if (*spec->sep) return 0;
+ spec->type = (spec->type == 'N') ? 'G' : 'g';
+ lc = localeconv();
+ spec->dot = lc->decimal_point;
+ spec->sep = lc->thousands_sep;
+ spec->grouping = lc->grouping;
+ }
+
+ /* check correctness */
+ if (*cp != '\0') {
+ return 0;
+ }
+
+ return 1;
+}
+
+/* Multibyte string */
+typedef struct {
+ mpd_ssize_t nbytes; /* length in bytes */
+ mpd_ssize_t nchars; /* length in chars */
+ mpd_ssize_t cur; /* current write index */
+ char *data;
+} mpd_mbstr_t;
+
+static inline void
+_mpd_bcopy(char *dest, const char *src, mpd_ssize_t n)
+{
+ while (--n >= 0) {
+ dest[n] = src[n];
+ }
+}
+
+static inline void
+_mbstr_copy_char(mpd_mbstr_t *dest, const char *src, mpd_ssize_t n)
+{
+ dest->nbytes += n;
+ dest->nchars += 1;
+ dest->cur -= n;
+
+ if (dest->data != NULL) {
+ _mpd_bcopy(dest->data+dest->cur, src, n);
+ }
+}
+
+static inline void
+_mbstr_copy_ascii(mpd_mbstr_t *dest, const char *src, mpd_ssize_t n)
+{
+ dest->nbytes += n;
+ dest->nchars += n;
+ dest->cur -= n;
+
+ if (dest->data != NULL) {
+ _mpd_bcopy(dest->data+dest->cur, src, n);
+ }
+}
+
+static inline void
+_mbstr_copy_pad(mpd_mbstr_t *dest, mpd_ssize_t n)
+{
+ dest->nbytes += n;
+ dest->nchars += n;
+ dest->cur -= n;
+
+ if (dest->data != NULL) {
+ char*cp = dest->data + dest->cur;
+ while (--n >= 0) {
+ cp[n] = '0';
+ }
+ }
+}
+
+/*
+ * Copy the decimal to dest, adding separators according to
+ * spec->grouping. If leading zero padding is enabled and the
+ * result is smaller than spec->min_width, continue adding zeros
+ * and separators until min_width is reached.
+ */
+static void
+_mpd_add_sep_dot(mpd_mbstr_t *dest,
+ const char *src, mpd_ssize_t n_src, /* integer part and length */
+ const char *sign, const char *dot, const char *rest,
+ mpd_spec_t *spec)
+{
+ mpd_ssize_t n_sep, n_sign, consume;
+ const char *g;
+ int pad = 0;
+
+ n_sign = sign ? 1 : 0;
+ n_sep = strlen(spec->sep);
+ g = spec->grouping;
+ dest->cur = dest->nbytes;
+ dest->nbytes = dest->nchars = 0;
+
+ _mbstr_copy_ascii(dest, rest, strlen(rest));
+
+ if (dot) {
+ _mbstr_copy_char(dest, dot, strlen(dot));
+ }
+
+ consume = *g;
+ while (1) {
+ if (*g == 0 || *g == CHAR_MAX || consume > n_src) {
+ consume = n_src;
+ }
+ n_src -= consume;
+ if (pad) {
+ _mbstr_copy_pad(dest, consume);
+ }
+ else {
+ _mbstr_copy_ascii(dest, src+n_src, consume);
+ }
+
+ if (n_src == 0) {
+ if (spec->align == 'z' &&
+ dest->nchars + n_sign < spec->min_width) {
+ n_src = spec->min_width - (dest->nchars + n_sign);
+ consume = *g - consume;
+ pad = 1;
+ continue;
+ }
+ break;
+ }
+
+ if (n_sep > 0) {
+ if (pad && n_src > 1) n_src -= 1;
+ _mbstr_copy_char(dest, spec->sep, n_sep);
+ }
+
+ if (*g && *(g+1)) g++;
+ consume = *g;
+ }
+
+ if (sign) {
+ _mbstr_copy_ascii(dest, sign, 1);
+ }
+
+ if (dest->data) {
+ dest->data[dest->nbytes] = '\0';
+ }
+}
+
+/* Change decstring to locale-specific appearance. */
+static void
+_mpd_apply_lconv(mpd_mbstr_t *result, char *decstring, mpd_spec_t *spec,
+ uint32_t *status)
+{
+ const char *sign = NULL, *intpart = NULL;
+ const char *dot = NULL, *rest = NULL;
+ const char *dp;
+ size_t n_int;
+
+ assert(result->data == NULL);
+
+ dp = decstring;
+ n_int = 0;
+
+ if (!isdigit((uchar)*dp)) {
+ sign = dp++;
+ }
+ if (isdigit((uchar)*dp)) {
+ intpart = dp++;
+ while (isdigit((uchar)*dp)) {
+ dp++;
+ }
+ n_int = dp-intpart;
+ }
+ if (*dp == '.') {
+ if (*spec->dot == '\0') {
+ /* decimal point must be present */
+ *status |= MPD_Invalid_operation;
+ mpd_free(decstring);
+ return;
+ }
+ dp++; dot = spec->dot;
+ }
+ rest = dp;
+
+
+ if (!dot && !(intpart && *spec->sep && *spec->grouping)) {
+ result->data = decstring;
+ result->nbytes = result->nchars = strlen(decstring);
+ return;
+ }
+
+ /* Get the size of the new decimal string after inserting dot and
+ * separators. */
+ _mpd_add_sep_dot(result, intpart, n_int, sign, dot, rest, spec);
+
+ if ((result->data = mpd_alloc(result->nbytes+1, 1)) == NULL) {
+ *status |= MPD_Malloc_error;
+ mpd_free(decstring);
+ return;
+ }
+
+ /* Perform actual writes. */
+ _mpd_add_sep_dot(result, intpart, n_int, sign, dot, rest, spec);
+
+ mpd_free(decstring);
+}
+
+/* Add padding to the formatted string if necessary. */
+static void
+_mpd_add_pad(mpd_mbstr_t *result, mpd_spec_t *spec, uint32_t *status)
+{
+ if (result->nchars < spec->min_width) {
+ size_t lpad = 0, rpad = 0;
+ size_t add_chars, add_bytes, n_fill;
+ size_t len, i, j;
+ uint8_t err = 0;
+ char *cp;
+
+ n_fill = strlen(spec->fill);
+ add_chars = (spec->min_width - result->nchars);
+ add_bytes = mul_size_t(add_chars, n_fill);
+
+ cp = result->data = mpd_realloc(result->data,
+ result->nbytes+add_bytes+1,
+ sizeof *result->data, &err);
+ if (err) {
+ *status |= MPD_Malloc_error;
+ mpd_free(result->data);
+ return;
+ }
+
+ if (spec->align == 'z') {
+ spec->align = '=';
+ }
+
+ if (spec->align == '<') {
+ rpad = add_chars;
+ }
+ else if (spec->align == '>' || spec->align == '=') {
+ lpad = add_chars;
+ }
+ else { /* align == '^' */
+ lpad = add_chars/2;
+ rpad = add_chars-lpad;
+ }
+
+ len = result->nbytes;
+ if (spec->align == '=' && (*cp == '-' || *cp == '+' ||
+ *cp == ' ')) {
+ /* leave sign in the leading position */
+ cp++; len--;
+ }
+
+ memmove(cp+n_fill*lpad, cp, len);
+ for (i = 0; i < lpad; i++) {
+ for (j = 0; j < n_fill; j++) {
+ cp[i*n_fill+j] = spec->fill[j];
+ }
+ }
+ cp += (n_fill*lpad + len);
+ for (i = 0; i < rpad; i++) {
+ for (j = 0; j < n_fill; j++) {
+ cp[i*n_fill+j] = spec->fill[j];
+ }
+ }
+
+ result->nbytes += add_bytes;
+ result->nchars += add_chars;
+ result->data[result->nbytes] = '\0';
+ }
+}
+
+/*
+ * Return the string representation of an mpd_t, formatted according to 'spec'.
+ * 'spec' is modified. The format specification is assumed to be valid. Memory
+ * errors are indicated as usual. This function is quiet.
+ */
+char *
+mpd_qformat_spec(const mpd_t *dec, mpd_spec_t *spec, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ mpd_context_t workctx;
+ mpd_uint_t dt[MPD_MINALLOC_MAX];
+ mpd_t tmp = {MPD_STATIC|MPD_STATIC_DATA,0,0,0,MPD_MINALLOC_MAX,dt};
+ mpd_ssize_t prec, fracdigits, exp;
+ mpd_ssize_t zeroexp = MPD_SSIZE_MAX;
+ mpd_mbstr_t result;
+ char *decstring;
+ int flags = 0;
+
+
+ if (!mpd_qcopy(&tmp, dec, status)) {
+ return NULL;
+ }
+
+ if (spec->type == '%') {
+ tmp.exp += 2;
+ spec->type = 'f';
+ flags |= MPD_FMT_PERCENT;
+ }
+
+ if (isupper((uchar)spec->type)) {
+ spec->type = tolower((uchar)spec->type);
+ flags |= MPD_FMT_UPPER;
+ }
+ if (spec->sign == ' ') {
+ flags |= MPD_FMT_SIGN_SPACE;
+ }
+ else if (spec->sign == '+') {
+ flags |= MPD_FMT_SIGN_PLUS;
+ }
+
+ workctx = *ctx;
+ workctx.traps = workctx.status = 0;
+ if (mpd_isspecial(&tmp)) {
+ /* no percent formatting */
+ flags |= MPD_FMT_TOSCI;
+ if (spec->align == 'z') {
+ spec->fill[0] = ' ';
+ spec->fill[1] = '\0';
+ spec->align = '>';
+ }
+ }
+ else if (spec->type == 'g') {
+ /* spec->prec: significant digits */
+ prec = (spec->prec < 0) ? dec->digits : spec->prec;
+ workctx.prec = (prec == 0) ? 1 : prec;
+ flags |= MPD_FMT_TOSCI;
+ mpd_qfinalize(&tmp, &workctx, &workctx.status);
+ }
+ else {
+ /* spec->prec: fraction digits */
+ if (spec->type == 'e') {
+ fracdigits = (spec->prec < 0) ? tmp.digits-1 : spec->prec;
+ if (mpd_iszero(&tmp)) {
+ zeroexp = tmp.exp+fracdigits;
+ exp = -fracdigits;
+ flags |= MPD_FMT_FIXED;
+ }
+ else {
+ exp = tmp.exp + tmp.digits-(fracdigits+1);
+ flags |= MPD_FMT_EXP;
+ }
+ }
+ else { /* 'f' */
+ fracdigits = spec->prec;
+ if (fracdigits < 0) {
+ fracdigits = (tmp.exp < 0) ? -tmp.exp : 0;
+ }
+ exp = -fracdigits;
+ fracdigits += (tmp.exp+tmp.digits);
+ fracdigits = (fracdigits < 0) ? 0 : fracdigits;
+ flags |= MPD_FMT_FIXED;
+ }
+ workctx.prec = fracdigits+1;
+ mpd_qrescale(&tmp, &tmp, exp, &workctx, &workctx.status);
+ if (tmp.digits > workctx.prec) {
+ mpd_qfinalize(&tmp, &workctx, &workctx.status);
+ }
+ }
+
+ if ((decstring = _mpd_to_string(&tmp, flags, zeroexp)) == NULL) {
+ *status |= MPD_Malloc_error;
+ mpd_del(&tmp);
+ return NULL;
+ }
+
+ result.data = decstring;
+ result.nbytes = result.nchars = 0;
+ if (!mpd_isspecial(&tmp) && *spec->dot != '\0') {
+ result.data = NULL;
+ _mpd_apply_lconv(&result, decstring, spec, status);
+ if (result.data == NULL) {
+ goto finish;
+ }
+ }
+
+ if (spec->min_width) {
+ if (result.nbytes == 0) {
+ result.nbytes = result.nchars = strlen(result.data);
+ }
+ _mpd_add_pad(&result, spec, status);
+ }
+
+
+finish:
+ mpd_del(&tmp);
+ return result.data;
+}
+
+char *
+mpd_qformat(const mpd_t *dec, const char *fmt, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ mpd_spec_t spec;
+
+ if (!mpd_parse_fmt_str(&spec, fmt)) {
+ *status |= MPD_Invalid_operation;
+ return NULL;
+ }
+
+ return mpd_qformat_spec(dec, &spec, ctx, status);
+}
+
+/*
+ * The specification has a *condition* called Invalid_operation and an
+ * IEEE *signal* called Invalid_operation. The former corresponds to
+ * MPD_Invalid_operation, the latter to MPD_IEEE_Invalid_operation.
+ * MPD_IEEE_Invalid_operation comprises the following conditions:
+ *
+ * [MPD_Conversion_syntax, MPD_Division_impossible, MPD_Division_undefined,
+ * MPD_Fpu_error, MPD_Invalid_context, MPD_Invalid_operation,
+ * MPD_Malloc_error]
+ *
+ * In the following functions, 'flag' denotes the condition, 'signal'
+ * denotes the IEEE signal.
+ */
+
+static const char *mpd_flag_string[MPD_NUM_FLAGS] = {
+ "Clamped",
+ "Conversion_syntax",
+ "Division_by_zero",
+ "Division_impossible",
+ "Division_undefined",
+ "Fpu_error",
+ "Inexact",
+ "Invalid_context",
+ "Invalid_operation",
+ "Malloc_error",
+ "Not_implemented",
+ "Overflow",
+ "Rounded",
+ "Subnormal",
+ "Underflow",
+};
+
+static const char *mpd_signal_string[MPD_NUM_FLAGS] = {
+ "Clamped",
+ "IEEE_Invalid_operation",
+ "Division_by_zero",
+ "IEEE_Invalid_operation",
+ "IEEE_Invalid_operation",
+ "IEEE_Invalid_operation",
+ "Inexact",
+ "IEEE_Invalid_operation",
+ "IEEE_Invalid_operation",
+ "IEEE_Invalid_operation",
+ "Not_implemented",
+ "Overflow",
+ "Rounded",
+ "Subnormal",
+ "Underflow",
+};
+
+/* print conditions to buffer, separated by spaces */
+int
+mpd_snprint_flags(char *dest, int nmemb, uint32_t flags)
+{
+ char *cp;
+ int n, j;
+
+ assert(nmemb >= MPD_MAX_FLAG_STRING);
+
+ *dest = '\0'; cp = dest;
+ for (j = 0; j < MPD_NUM_FLAGS; j++) {
+ if (flags & (1U<<j)) {
+ n = snprintf(cp, nmemb, "%s ", mpd_flag_string[j]);
+ if (n < 0 || n >= nmemb) return -1;
+ cp += n; nmemb -= n;
+ }
+ }
+
+ if (cp != dest) {
+ *(--cp) = '\0';
+ }
+
+ return (int)(cp-dest);
+}
+
+/* print conditions to buffer, in list form */
+int
+mpd_lsnprint_flags(char *dest, int nmemb, uint32_t flags, const char *flag_string[])
+{
+ char *cp;
+ int n, j;
+
+ assert(nmemb >= MPD_MAX_FLAG_LIST);
+ if (flag_string == NULL) {
+ flag_string = mpd_flag_string;
+ }
+
+ *dest = '[';
+ *(dest+1) = '\0';
+ cp = dest+1;
+ --nmemb;
+
+ for (j = 0; j < MPD_NUM_FLAGS; j++) {
+ if (flags & (1U<<j)) {
+ n = snprintf(cp, nmemb, "%s, ", flag_string[j]);
+ if (n < 0 || n >= nmemb) return -1;
+ cp += n; nmemb -= n;
+ }
+ }
+
+ /* erase the last ", " */
+ if (cp != dest+1) {
+ cp -= 2;
+ }
+
+ *cp++ = ']';
+ *cp = '\0';
+
+ return (int)(cp-dest); /* strlen, without NUL terminator */
+}
+
+/* print signals to buffer, in list form */
+int
+mpd_lsnprint_signals(char *dest, int nmemb, uint32_t flags, const char *signal_string[])
+{
+ char *cp;
+ int n, j;
+ int ieee_invalid_done = 0;
+
+ assert(nmemb >= MPD_MAX_SIGNAL_LIST);
+ if (signal_string == NULL) {
+ signal_string = mpd_signal_string;
+ }
+
+ *dest = '[';
+ *(dest+1) = '\0';
+ cp = dest+1;
+ --nmemb;
+
+ for (j = 0; j < MPD_NUM_FLAGS; j++) {
+ uint32_t f = flags & (1U<<j);
+ if (f) {
+ if (f&MPD_IEEE_Invalid_operation) {
+ if (ieee_invalid_done) {
+ continue;
+ }
+ ieee_invalid_done = 1;
+ }
+ n = snprintf(cp, nmemb, "%s, ", signal_string[j]);
+ if (n < 0 || n >= nmemb) return -1;
+ cp += n; nmemb -= n;
+ }
+ }
+
+ /* erase the last ", " */
+ if (cp != dest+1) {
+ cp -= 2;
+ }
+
+ *cp++ = ']';
+ *cp = '\0';
+
+ return (int)(cp-dest); /* strlen, without NUL terminator */
+}
+
+void
+mpd_fprint(FILE *file, const mpd_t *dec)
+{
+ char *decstring;
+
+ decstring = mpd_to_sci(dec, 1);
+ if (decstring != NULL) {
+ fprintf(file, "%s\n", decstring);
+ mpd_free(decstring);
+ }
+ else {
+ fputs("mpd_fprint: output error\n", file);
+ }
+}
+
+void
+mpd_print(const mpd_t *dec)
+{
+ char *decstring;
+
+ decstring = mpd_to_sci(dec, 1);
+ if (decstring != NULL) {
+ printf("%s\n", decstring);
+ mpd_free(decstring);
+ }
+ else {
+ fputs("mpd_fprint: output error", stderr);
+ }
+}
+
+
Added: python/branches/py3k-cdecimal/Modules/cdecimal/memory.c
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/memory.c Thu Jan 7 13:02:51 2010
@@ -0,0 +1,241 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#include <stdio.h>
+#include <stdlib.h>
+#include "mpdecimal.h"
+#include "typearith.h"
+#include "memory.h"
+
+
+mpd_ssize_t MPD_MINALLOC = MPD_MINALLOC_MIN;
+
+void *(* mpd_mallocfunc)(size_t size) = malloc;
+void *(* mpd_reallocfunc)(void *ptr, size_t size) = realloc;
+void *(* mpd_callocfunc)(size_t nmemb, size_t size) = calloc;
+void (* mpd_free)(void *ptr) = free;
+
+
+/* emulate calloc if it is not available */
+void *
+mpd_callocfunc_em(size_t nmemb, size_t size)
+{
+ void *ptr;
+ size_t req;
+
+ req = mul_size_t(nmemb, size);
+ if ((ptr = mpd_mallocfunc(req)) == NULL) {
+ return NULL;
+ }
+ /* used on uint32_t or uint64_t */
+ memset(ptr, 0, req);
+
+ return ptr;
+}
+
+
+/* malloc with overflow checking */
+void *
+mpd_alloc(size_t nmemb, size_t size)
+{
+ void *ptr;
+ size_t req;
+
+ req = mul_size_t(nmemb, size);
+ if ((ptr = mpd_mallocfunc(req)) == NULL) {
+ return NULL;
+ }
+
+ return ptr;
+}
+
+/* calloc with overflow checking */
+void *
+mpd_calloc(size_t nmemb, size_t size)
+{
+ void *ptr;
+
+ if ((ptr = mpd_callocfunc(nmemb, size)) == NULL) {
+ return NULL;
+ }
+
+ return ptr;
+}
+
+/* realloc with overflow checking */
+void *
+mpd_realloc(void *ptr, size_t nmemb, size_t size, uint8_t *err)
+{
+ void *new;
+ size_t req;
+
+ req = mul_size_t(nmemb, size);
+ if ((new = mpd_reallocfunc(ptr, req)) == NULL) {
+ *err = 1;
+ return ptr;
+ }
+
+ return new;
+}
+
+/* struct hack malloc with overflow checking */
+void *
+mpd_sh_alloc(size_t struct_size, size_t nmemb, size_t size)
+{
+ void *ptr;
+ size_t req;
+
+ req = mul_size_t(nmemb, size);
+ req = add_size_t(req, struct_size);
+ if ((ptr = mpd_mallocfunc(req)) == NULL) {
+ return NULL;
+ }
+
+ return ptr;
+}
+
+/* mpd_callocfunc must have overflow checking */
+void *
+mpd_sh_calloc(size_t struct_size, size_t nmemb, size_t size)
+{
+ void *ptr;
+ size_t req;
+
+ req = mul_size_t(nmemb, size);
+ req = add_size_t(req, struct_size);
+ if ((ptr = mpd_callocfunc(req, 1)) == NULL) {
+ return NULL;
+ }
+
+ return ptr;
+}
+
+/* struct hack realloc with overflow checking */
+void *
+mpd_sh_realloc(void *ptr, size_t struct_size, size_t nmemb, size_t size, uint8_t *err)
+{
+ void *new;
+ size_t req;
+
+ req = mul_size_t(nmemb, size);
+ req = add_size_t(req, struct_size);
+ if ((new = mpd_reallocfunc(ptr, req)) == NULL) {
+ *err = 1;
+ return ptr;
+ }
+
+ return new;
+}
+
+
+/* Allocate a new decimal with data-size 'size'.
+ * In case of an error the return value is NULL.
+ */
+mpd_t *
+mpd_qnew_size(mpd_ssize_t size)
+{
+ mpd_t *result;
+
+ size = (size < MPD_MINALLOC) ? MPD_MINALLOC : size;
+
+ if ((result = mpd_alloc(1, sizeof *result)) == NULL) {
+ return NULL;
+ }
+ if ((result->data = mpd_alloc(size, sizeof *result->data)) == NULL) {
+ mpd_free(result);
+ return NULL;
+ }
+
+ result->flags = result->exp = result->digits = result->len = 0;
+ result->alloc = size;
+
+ return result;
+}
+
+/* Allocate a new decimal with data-size MPD_MINALLOC.
+ * In case of an error the return value is NULL.
+ */
+mpd_t *
+mpd_qnew(void)
+{
+ return mpd_qnew_size(MPD_MINALLOC);
+}
+
+/* Allocate new decimal. Caller can check for NULL or MPD_Malloc_error.
+ * Raises on error.
+ */
+mpd_t *
+mpd_new(mpd_context_t *ctx)
+{
+ mpd_t *result;
+
+ if ((result = mpd_qnew()) == NULL) {
+ mpd_addstatus_raise(ctx, MPD_Malloc_error);
+ }
+ return result;
+}
+
+int
+mpd_switch_to_dyn(mpd_t *result, mpd_ssize_t size, uint32_t *status)
+{
+ mpd_uint_t *p = result->data;
+
+ if ((result->data = mpd_alloc(size, sizeof *result->data)) == NULL) {
+ result->data = p;
+ mpd_set_qnan(result);
+ mpd_set_positive(result);
+ result->exp = result->digits = result->len = 0;
+ *status |= MPD_Malloc_error;
+ return 0;
+ }
+
+ memcpy(result->data, p, result->len * (sizeof *result->data));
+ result->alloc = size;
+ mpd_set_dynamic_data(result);
+ return 1;
+}
+
+int
+mpd_switch_to_dyn_zero(mpd_t *result, mpd_ssize_t size, uint32_t *status)
+{
+ mpd_uint_t *p = result->data;
+
+ if ((result->data = mpd_calloc(size, sizeof *result->data)) == NULL) {
+ result->data = p;
+ mpd_set_qnan(result);
+ mpd_set_positive(result);
+ result->exp = result->digits = result->len = 0;
+ *status |= MPD_Malloc_error;
+ return 0;
+ }
+
+ result->alloc = size;
+ mpd_set_dynamic_data(result);
+
+ return 1;
+}
+
+int
+mpd_realloc_dyn(mpd_t *result, mpd_ssize_t size, uint32_t *status)
+{
+ uint8_t err = 0;
+
+ result->data = mpd_realloc(result->data, size, sizeof *result->data, &err);
+ if (!err) {
+ result->alloc = size;
+ }
+ else if (size > result->alloc) {
+ mpd_set_qnan(result);
+ mpd_set_positive(result);
+ result->exp = result->digits = result->len = 0;
+ *status |= MPD_Malloc_error;
+ return 0;
+ }
+
+ return 1;
+}
+
+
Added: python/branches/py3k-cdecimal/Modules/cdecimal/memory.h
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/memory.h Thu Jan 7 13:02:51 2010
@@ -0,0 +1,22 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#ifndef MEMORY_H
+#define MEMORY_H
+
+
+#include "mpdecimal.h"
+
+
+int mpd_switch_to_dyn(mpd_t *result, mpd_ssize_t size, uint32_t *status);
+int mpd_switch_to_dyn_zero(mpd_t *result, mpd_ssize_t size, uint32_t *status);
+int mpd_realloc_dyn(mpd_t *result, mpd_ssize_t size, uint32_t *status);
+
+
+#endif
+
+
+
Added: python/branches/py3k-cdecimal/Modules/cdecimal/mpdecimal.c
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/mpdecimal.c Thu Jan 7 13:02:51 2010
@@ -0,0 +1,7020 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <limits.h>
+#include <math.h>
+#include "basearith.h"
+#include "bits.h"
+#include "convolute.h"
+#include "crt.h"
+#include "errno.h"
+#include "memory.h"
+#include "typearith.h"
+#include "umodarith.h"
+#include "mptypes.h"
+#include "mpdecimal.h"
+
+#ifdef PPRO
+ #if defined(_MSC_VER)
+ #include <float.h>
+ #pragma fenv_access(on)
+ #elif !defined(__OpenBSD__)
+ /* C99 */
+ #include <fenv.h>
+ #pragma STDC FENV_ACCESS ON
+ #endif
+#endif
+
+#if defined(__GLIBC__) && !defined(__INTEL_COMPILER)
+ #define HAVE_80BIT_LONG_DOUBLE
+#endif
+
+#if defined(_MSC_VER)
+ #define ALWAYS_INLINE __forceinline
+#else
+ #define ALWAYS_INLINE inline __attribute__ ((always_inline))
+#endif
+
+#define MPD_NEWTONDIV_CUTOFF (8*MPD_RDIGITS)
+
+#define MPD_NEW_STATIC(name, flags, exp, digits, len) \
+ mpd_uint_t name##_data[MPD_MINALLOC_MAX]; \
+ mpd_t name = {flags|MPD_STATIC|MPD_STATIC_DATA, exp, digits, \
+ len, MPD_MINALLOC_MAX, name##_data}
+
+#define MPD_NEW_CONST(name, flags, exp, digits, len, alloc, initval) \
+ mpd_uint_t name##_data[alloc] = {initval}; \
+ mpd_t name = {flags|MPD_STATIC|MPD_CONST_DATA, exp, digits, \
+ len, alloc, name##_data}
+
+#define MPD_NEW_SHARED(name, a) \
+ mpd_t name = {(a->flags&~MPD_DATAFLAGS)|MPD_STATIC|MPD_SHARED_DATA, \
+ a->exp, a->digits, a->len, a->alloc, a->data}
+
+
+static mpd_uint_t data_one[1] = {1};
+static mpd_uint_t data_zero[1] = {0};
+static const mpd_t one = {MPD_STATIC|MPD_CONST_DATA, 0, 1, 1, 1, data_one};
+static const mpd_t minus_one = {MPD_NEG|MPD_STATIC|MPD_CONST_DATA, 0, 1, 1, 1,
+ data_one};
+static const mpd_t zero = {MPD_STATIC|MPD_CONST_DATA, 0, 1, 1, 1, data_zero};
+
+static inline void _mpd_check_exp(mpd_t *dec, const mpd_context_t *ctx, uint32_t *status);
+static void _settriple(mpd_t *result, uint8_t sign, mpd_uint_t a, mpd_ssize_t exp);
+static inline mpd_ssize_t _mpd_real_size(mpd_uint_t *data, mpd_ssize_t size);
+
+static void _mpd_qadd(mpd_t *result, const mpd_t *a, const mpd_t *b,
+ const mpd_context_t *ctx, uint32_t *status);
+static inline void _mpd_qmul(mpd_t *result, const mpd_t *a, const mpd_t *b,
+ const mpd_context_t *ctx, uint32_t *status);
+static void _mpd_qbarrett_divmod(mpd_t *q, mpd_t *r, const mpd_t *a,
+ const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+static inline void _mpd_qpow_uint(mpd_t *result, mpd_t *base, mpd_uint_t exp,
+ uint8_t resultsign, const mpd_context_t *ctx, uint32_t *status);
+
+static mpd_uint_t mpd_qsshiftr(mpd_t *result, const mpd_t *a, mpd_ssize_t n);
+
+
+/******************************************************************************/
+/* Performance critical inline functions */
+/******************************************************************************/
+
+#ifdef CONFIG_64
+/* Digits in a word, primarily useful for the most significant word. */
+ALWAYS_INLINE int
+mpd_word_digits(mpd_uint_t word)
+{
+ if (word < mpd_pow10[9]) {
+ if (word < mpd_pow10[4]) {
+ if (word < mpd_pow10[2]) {
+ return (word < mpd_pow10[1]) ? 1 : 2;
+ }
+ return (word < mpd_pow10[3]) ? 3 : 4;
+ }
+ if (word < mpd_pow10[6]) {
+ return (word < mpd_pow10[5]) ? 5 : 6;
+ }
+ if (word < mpd_pow10[8]) {
+ return (word < mpd_pow10[7]) ? 7 : 8;
+ }
+ return 9;
+ }
+ if (word < mpd_pow10[14]) {
+ if (word < mpd_pow10[11]) {
+ return (word < mpd_pow10[10]) ? 10 : 11;
+ }
+ if (word < mpd_pow10[13]) {
+ return (word < mpd_pow10[12]) ? 12 : 13;
+ }
+ return 14;
+ }
+ if (word < mpd_pow10[17]) {
+ if (word < mpd_pow10[16]) {
+ return (word < mpd_pow10[15]) ? 15 : 16;
+ }
+ return 17;
+ }
+
+ return (word < mpd_pow10[18]) ? 18 : 19;
+}
+#else
+ALWAYS_INLINE int
+mpd_word_digits(mpd_uint_t word)
+{
+ if (word < mpd_pow10[4]) {
+ if (word < mpd_pow10[2]) {
+ return (word < mpd_pow10[1]) ? 1 : 2;
+ }
+ return (word < mpd_pow10[3]) ? 3 : 4;
+ }
+ if (word < mpd_pow10[6]) {
+ return (word < mpd_pow10[5]) ? 5 : 6;
+ }
+ if (word < mpd_pow10[8]) {
+ return (word < mpd_pow10[7]) ? 7 : 8;
+ }
+
+ return (word < mpd_pow10[9]) ? 9 : 10;
+}
+#endif
+
+
+/* Adjusted exponent */
+ALWAYS_INLINE mpd_ssize_t
+mpd_adjexp(const mpd_t *dec)
+{
+ return dec->exp + dec->digits - 1;
+}
+
+/* Etiny */
+ALWAYS_INLINE mpd_ssize_t
+mpd_etiny(const mpd_context_t *ctx)
+{
+ return ctx->emin - (ctx->prec - 1);
+}
+
+/* Etop: used for folding down in IEEE clamping */
+ALWAYS_INLINE mpd_ssize_t
+mpd_etop(const mpd_context_t *ctx)
+{
+ return ctx->emax - (ctx->prec - 1);
+}
+
+/* Most significant word */
+ALWAYS_INLINE mpd_uint_t
+mpd_msword(const mpd_t *dec)
+{
+ assert(dec->len > 0);
+ return dec->data[dec->len-1];
+}
+
+/* Most significant digit of a word */
+inline mpd_uint_t
+mpd_msd(mpd_uint_t word)
+{
+ int n;
+
+ n = mpd_word_digits(word);
+ return word / mpd_pow10[n-1];
+}
+
+/* Least significant digit of a word */
+ALWAYS_INLINE mpd_uint_t
+mpd_lsd(mpd_uint_t word)
+{
+ return word % 10;
+}
+
+/* Coefficient size needed to store 'digits' */
+ALWAYS_INLINE mpd_ssize_t
+mpd_digits_to_size(mpd_ssize_t digits)
+{
+ mpd_ssize_t q, r;
+
+ _mpd_idiv_word(&q, &r, digits, MPD_RDIGITS);
+ return (r == 0) ? q : q+1;
+}
+
+/* Number of digits in the exponent. Not defined for MPD_SSIZE_MIN. */
+inline int
+mpd_exp_digits(mpd_ssize_t exp)
+{
+ exp = (exp < 0) ? -exp : exp;
+ return mpd_word_digits(exp);
+}
+
+/* Canonical */
+ALWAYS_INLINE int
+mpd_iscanonical(const mpd_t *dec UNUSED)
+{
+ return 1;
+}
+
+/* Finite */
+ALWAYS_INLINE int
+mpd_isfinite(const mpd_t *dec)
+{
+ return !(dec->flags & MPD_SPECIAL);
+}
+
+/* Infinite */
+ALWAYS_INLINE int
+mpd_isinfinite(const mpd_t *dec)
+{
+ return dec->flags & MPD_INF;
+}
+
+/* NaN */
+ALWAYS_INLINE int
+mpd_isnan(const mpd_t *dec)
+{
+ return dec->flags & (MPD_NAN|MPD_SNAN);
+}
+
+/* Negative */
+ALWAYS_INLINE int
+mpd_isnegative(const mpd_t *dec)
+{
+ return dec->flags & MPD_NEG;
+}
+
+/* Positive */
+ALWAYS_INLINE int
+mpd_ispositive(const mpd_t *dec)
+{
+ return !(dec->flags & MPD_NEG);
+}
+
+/* qNaN */
+ALWAYS_INLINE int
+mpd_isqnan(const mpd_t *dec)
+{
+ return dec->flags & MPD_NAN;
+}
+
+/* Signed */
+ALWAYS_INLINE int
+mpd_issigned(const mpd_t *dec)
+{
+ return dec->flags & MPD_NEG;
+}
+
+/* sNaN */
+ALWAYS_INLINE int
+mpd_issnan(const mpd_t *dec)
+{
+ return dec->flags & MPD_SNAN;
+}
+
+/* Special */
+ALWAYS_INLINE int
+mpd_isspecial(const mpd_t *dec)
+{
+ return dec->flags & MPD_SPECIAL;
+}
+
+/* Zero */
+ALWAYS_INLINE int
+mpd_iszero(const mpd_t *dec)
+{
+ return !mpd_isspecial(dec) && mpd_msword(dec) == 0;
+}
+
+/* Test for zero when specials have been ruled out already */
+ALWAYS_INLINE int
+mpd_iszerocoeff(const mpd_t *dec)
+{
+ return mpd_msword(dec) == 0;
+}
+
+/* Normal */
+inline int
+mpd_isnormal(const mpd_t *dec, const mpd_context_t *ctx)
+{
+ if (mpd_isspecial(dec)) return 0;
+ if (mpd_iszerocoeff(dec)) return 0;
+
+ return mpd_adjexp(dec) >= ctx->emin;
+}
+
+/* Subnormal */
+inline int
+mpd_issubnormal(const mpd_t *dec, const mpd_context_t *ctx)
+{
+ if (mpd_isspecial(dec)) return 0;
+ if (mpd_iszerocoeff(dec)) return 0;
+
+ return mpd_adjexp(dec) < ctx->emin;
+}
+
+/* Odd word */
+ALWAYS_INLINE int
+mpd_isoddword(mpd_uint_t word)
+{
+ return word & 1;
+}
+
+/* Odd coefficient */
+ALWAYS_INLINE int
+mpd_isoddcoeff(const mpd_t *dec)
+{
+ return mpd_isoddword(dec->data[0]);
+}
+
+/* 0 if dec is positive, 1 if dec is negative */
+ALWAYS_INLINE uint8_t
+mpd_sign(const mpd_t *dec)
+{
+ return dec->flags & MPD_NEG;
+}
+
+/* 1 if dec is positive, -1 if dec is negative */
+ALWAYS_INLINE int
+mpd_arith_sign(const mpd_t *dec)
+{
+ return 1 - 2 * mpd_isnegative(dec);
+}
+
+/* Radix */
+ALWAYS_INLINE long
+mpd_radix(void)
+{
+ return 10;
+}
+
+/* Dynamic decimal */
+ALWAYS_INLINE int
+mpd_isdynamic(mpd_t *dec)
+{
+ return !(dec->flags & MPD_STATIC);
+}
+
+/* Static decimal */
+ALWAYS_INLINE int
+mpd_isstatic(mpd_t *dec)
+{
+ return dec->flags & MPD_STATIC;
+}
+
+/* Data of decimal is dynamic */
+ALWAYS_INLINE int
+mpd_isdynamic_data(mpd_t *dec)
+{
+ return !(dec->flags & MPD_DATAFLAGS);
+}
+
+/* Data of decimal is static */
+ALWAYS_INLINE int
+mpd_isstatic_data(mpd_t *dec)
+{
+ return dec->flags & MPD_STATIC_DATA;
+}
+
+/* Data of decimal is shared */
+ALWAYS_INLINE int
+mpd_isshared_data(mpd_t *dec)
+{
+ return dec->flags & MPD_SHARED_DATA;
+}
+
+/* Data of decimal is const */
+ALWAYS_INLINE int
+mpd_isconst_data(mpd_t *dec)
+{
+ return dec->flags & MPD_CONST_DATA;
+}
+
+
+/******************************************************************************/
+/* Inline memory handling */
+/******************************************************************************/
+
+/* Fill destination with zeros */
+ALWAYS_INLINE void
+mpd_uint_zero(mpd_uint_t *dest, size_t len)
+{
+ size_t i;
+
+ for (i = 0; i < len; i++) {
+ dest[i] = 0;
+ }
+}
+
+/* Free a decimal */
+ALWAYS_INLINE void
+mpd_del(mpd_t *dec)
+{
+ if (mpd_isdynamic_data(dec)) {
+ mpd_free(dec->data);
+ }
+ if (mpd_isdynamic(dec)) {
+ mpd_free(dec);
+ }
+}
+
+/*
+ * Update the memory size for the coefficient. Existing data up to size is
+ * left untouched.
+ *
+ * Error handling: When relloc fails, result->data will still be a valid pointer
+ * to the old memory area of size result->len. If the requested size is less than
+ * result->len, we can continue normally, so we treat the failure as a soft error.
+ * If the requested size is greater than the old area, MPD_Malloc_error is
+ * set and the result will be a NaN.
+ */
+ALWAYS_INLINE int
+mpd_qresize(mpd_t *result, mpd_ssize_t size, uint32_t *status)
+{
+ assert(!mpd_isconst_data(result)); /* illegal operation for a const */
+ assert(!mpd_isshared_data(result)); /* illegal operation for a shared */
+
+ if (mpd_isstatic_data(result)) {
+ if (size > result->alloc) {
+ return mpd_switch_to_dyn(result, size, status);
+ }
+ }
+ else if (size != result->alloc && size >= MPD_MINALLOC) {
+ return mpd_realloc_dyn(result, size, status);
+ }
+
+ return 1;
+}
+
+/* Same as mpd_qresize, but the complete coefficient (including the old
+ * memory area!) is initialized to zero. */
+ALWAYS_INLINE int
+mpd_qresize_zero(mpd_t *result, mpd_ssize_t size, uint32_t *status)
+{
+ assert(!mpd_isconst_data(result)); /* illegal operation for a const */
+ assert(!mpd_isshared_data(result)); /* illegal operation for a shared */
+
+ if (mpd_isstatic_data(result)) {
+ if (size > result->alloc) {
+ return mpd_switch_to_dyn_zero(result, size, status);
+ }
+ }
+ else if (size != result->alloc && size >= MPD_MINALLOC) {
+ if (!mpd_realloc_dyn(result, size, status)) {
+ return 0;
+ }
+ }
+
+ mpd_uint_zero(result->data, size);
+
+ return 1;
+}
+
+/*
+ * Reduce memory size for the coefficient to MPD_MINALLOC. In theory, realloc
+ * may fail even when reducing the memory size. But in that case the old memory
+ * area is always big enough, so checking for MPD_Malloc_error is not imperative.
+ */
+ALWAYS_INLINE void
+mpd_minalloc(mpd_t *result)
+{
+ assert(!mpd_isconst_data(result)); /* illegal operation for a const */
+ assert(!mpd_isshared_data(result)); /* illegal operation for a shared */
+
+ if (!mpd_isstatic_data(result) && result->alloc > MPD_MINALLOC) {
+ uint8_t err = 0;
+ result->data = mpd_realloc(result->data, MPD_MINALLOC,
+ sizeof *result->data, &err);
+ if (!err) {
+ result->alloc = MPD_MINALLOC;
+ }
+ }
+}
+
+int
+mpd_resize(mpd_t *result, mpd_ssize_t size, mpd_context_t *ctx)
+{
+ uint32_t status = 0;
+ if (!mpd_qresize(result, size, &status)) {
+ mpd_addstatus_raise(ctx, status);
+ return 0;
+ }
+ return 1;
+}
+
+int
+mpd_resize_zero(mpd_t *result, mpd_ssize_t size, mpd_context_t *ctx)
+{
+ uint32_t status = 0;
+ if (!mpd_qresize_zero(result, size, &status)) {
+ mpd_addstatus_raise(ctx, status);
+ return 0;
+ }
+ return 1;
+}
+
+
+/******************************************************************************/
+/* Set attributes of a decimal */
+/******************************************************************************/
+
+/* Set digits. result->len is assumed to be correct. */
+inline void
+mpd_setdigits(mpd_t *result)
+{
+ mpd_ssize_t wdigits = mpd_word_digits(mpd_msword(result));
+ result->digits = wdigits + (result->len-1) * MPD_RDIGITS;
+}
+
+/* Set sign */
+ALWAYS_INLINE void
+mpd_set_sign(mpd_t *result, uint8_t sign)
+{
+ result->flags &= ~MPD_NEG;
+ result->flags |= sign;
+}
+
+/* Copy sign from another decimal */
+ALWAYS_INLINE void
+mpd_signcpy(mpd_t *result, mpd_t *a)
+{
+ uint8_t sign = a->flags&MPD_NEG;
+
+ result->flags &= ~MPD_NEG;
+ result->flags |= sign;
+}
+
+/* Set infinity */
+ALWAYS_INLINE void
+mpd_set_infinity(mpd_t *result)
+{
+ result->flags &= ~MPD_SPECIAL;
+ result->flags |= MPD_INF;
+}
+
+/* Set qNaN */
+ALWAYS_INLINE void
+mpd_set_qnan(mpd_t *result)
+{
+ result->flags &= ~MPD_SPECIAL;
+ result->flags |= MPD_NAN;
+}
+
+/* Set sNaN */
+ALWAYS_INLINE void
+mpd_set_snan(mpd_t *result)
+{
+ result->flags &= ~MPD_SPECIAL;
+ result->flags |= MPD_SNAN;
+}
+
+/* Set to negative */
+ALWAYS_INLINE void
+mpd_set_negative(mpd_t *result)
+{
+ result->flags |= MPD_NEG;
+}
+
+/* Set to positive */
+ALWAYS_INLINE void
+mpd_set_positive(mpd_t *result)
+{
+ result->flags &= ~MPD_NEG;
+}
+
+/* Set to dynamic */
+ALWAYS_INLINE void
+mpd_set_dynamic(mpd_t *result)
+{
+ result->flags &= ~MPD_STATIC;
+}
+
+/* Set to static */
+ALWAYS_INLINE void
+mpd_set_static(mpd_t *result)
+{
+ result->flags |= MPD_STATIC;
+}
+
+/* Set data to dynamic */
+ALWAYS_INLINE void
+mpd_set_dynamic_data(mpd_t *result)
+{
+ result->flags &= ~MPD_DATAFLAGS;
+}
+
+/* Set data to static */
+ALWAYS_INLINE void
+mpd_set_static_data(mpd_t *result)
+{
+ result->flags &= ~MPD_DATAFLAGS;
+ result->flags |= MPD_STATIC_DATA;
+}
+
+/* Set data to shared */
+ALWAYS_INLINE void
+mpd_set_shared_data(mpd_t *result)
+{
+ result->flags &= ~MPD_DATAFLAGS;
+ result->flags |= MPD_SHARED_DATA;
+}
+
+/* Set data to const */
+ALWAYS_INLINE void
+mpd_set_const_data(mpd_t *result)
+{
+ result->flags &= ~MPD_DATAFLAGS;
+ result->flags |= MPD_CONST_DATA;
+}
+
+/* Clear flags, preserving memory attributes. */
+ALWAYS_INLINE void
+mpd_clear_flags(mpd_t *result)
+{
+ result->flags &= (MPD_STATIC|MPD_DATAFLAGS);
+}
+
+/* Set flags, preserving memory attributes. */
+ALWAYS_INLINE void
+mpd_set_flags(mpd_t *result, uint8_t flags)
+{
+ result->flags &= (MPD_STATIC|MPD_DATAFLAGS);
+ result->flags |= flags;
+}
+
+/* Copy flags, preserving memory attributes of result. */
+ALWAYS_INLINE void
+mpd_copy_flags(mpd_t *result, const mpd_t *a)
+{
+ uint8_t aflags = a->flags;
+ result->flags &= (MPD_STATIC|MPD_DATAFLAGS);
+ result->flags |= (aflags & ~(MPD_STATIC|MPD_DATAFLAGS));
+}
+
+/* Make a work context */
+static inline void
+mpd_workcontext(mpd_context_t *workctx, const mpd_context_t *ctx)
+{
+ workctx->prec = ctx->prec;
+ workctx->emax = ctx->emax;
+ workctx->emin = ctx->emin;
+ workctx->round = ctx->round;
+ workctx->traps = 0;
+ workctx->status= 0;
+ workctx->newtrap= 0;
+ workctx->clamp = ctx->clamp;
+ workctx->allcr = ctx->allcr;
+}
+
+
+/******************************************************************************/
+/* Getting and setting parts of decimals */
+/******************************************************************************/
+
+/* Flip the sign of a decimal */
+static inline void
+_mpd_negate(mpd_t *dec)
+{
+ dec->flags ^= MPD_NEG;
+}
+
+/* Set coefficient to zero */
+void
+mpd_zerocoeff(mpd_t *result)
+{
+ mpd_minalloc(result);
+ result->digits = 1;
+ result->len = 1;
+ result->data[0] = 0;
+}
+
+/* Set the coefficient to all nines. Does not raise. */
+void
+mpd_qmaxcoeff(mpd_t *result, const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_ssize_t len, r;
+
+ _mpd_idiv_word(&len, &r, ctx->prec, MPD_RDIGITS);
+ len = (r == 0) ? len : len+1;
+
+ if (!mpd_qresize(result, len, status)) {
+ return;
+ }
+
+ result->len = len;
+ result->digits = ctx->prec;
+
+ --len;
+ if (r > 0) {
+ result->data[len--] = mpd_pow10[r]-1;
+ }
+ for (; len >= 0; --len) {
+ result->data[len] = MPD_RADIX-1;
+ }
+}
+
+/*
+ * Cut off the most significant digits so that the rest fits in ctx->prec.
+ * Cannot fail.
+ */
+static void
+_mpd_cap(mpd_t *result, const mpd_context_t *ctx)
+{
+ uint32_t dummy;
+ mpd_ssize_t len, r;
+
+ if (result->len > 0 && result->digits > ctx->prec) {
+ _mpd_idiv_word(&len, &r, ctx->prec, MPD_RDIGITS);
+ len = (r == 0) ? len : len+1;
+
+ /* resize to fewer words cannot fail */
+ mpd_qresize(result, len, &dummy);
+
+ if (r != 0) {
+ result->data[len-1] %= mpd_pow10[r];
+ }
+
+ len = _mpd_real_size(result->data, len);
+ result->len = len;
+ mpd_setdigits(result);
+ }
+ if (mpd_iszero(result)) {
+ _settriple(result, mpd_sign(result), 0, result->exp);
+ }
+}
+
+/*
+ * Cut off the most significant digits of a NaN payload so that the rest
+ * fits in ctx->prec. Cannot fail.
+ */
+static void
+_mpd_fix_nan(mpd_t *result, const mpd_context_t *ctx)
+{
+ uint32_t dummy;
+ mpd_ssize_t len, r;
+
+ if (result->len > 0 && result->digits > ctx->prec-ctx->clamp) {
+ _mpd_idiv_word(&len, &r, ctx->prec, MPD_RDIGITS);
+ len = (r == 0) ? len : len+1;
+
+ /* resize to fewer words cannot fail */
+ mpd_qresize(result, len, &dummy);
+
+ if (r != 0) {
+ result->data[len-1] %= mpd_pow10[r];
+ }
+
+ len = _mpd_real_size(result->data, len);
+ result->len = len;
+ mpd_setdigits(result);
+ if (mpd_iszerocoeff(result)) {
+ /* NaN0 is not a valid representation */
+ result->len = result->digits = 0;
+ }
+ }
+}
+
+/*
+ * Get n most significant digits from a decimal, where 0 < n <= MPD_UINT_DIGITS.
+ * Assumes MPD_UINT_DIGITS == MPD_RDIGITS+1, which is true for 32 and 64 bit machines.
+ *
+ * The result of the operation will be in lo. If the operation is impossible,
+ * hi will be nonzero. This is used to indicate an error.
+ */
+static inline void
+_mpd_get_msdigits(mpd_uint_t *hi, mpd_uint_t *lo, const mpd_t *dec, unsigned int n)
+{
+ mpd_uint_t r, tmp;
+
+ assert(0 < n && n <= MPD_RDIGITS+1);
+
+ _mpd_div_word(&tmp, &r, dec->digits, MPD_RDIGITS);
+ r = (r == 0) ? MPD_RDIGITS : r; /* digits in the most significant word */
+
+ *hi = 0;
+ *lo = dec->data[dec->len-1];
+ if (n <= r) {
+ *lo /= mpd_pow10[r-n];
+ }
+ else if (dec->len > 1) {
+ /* at this point 1 <= r < n <= MPD_RDIGITS+1 */
+ _mpd_mul_words(hi, lo, *lo, mpd_pow10[n-r]);
+ tmp = dec->data[dec->len-2] / mpd_pow10[MPD_RDIGITS-(n-r)];
+ *lo = *lo + tmp;
+ if (*lo < tmp) (*hi)++;
+ }
+}
+
+
+/******************************************************************************/
+/* Gathering information about a decimal */
+/******************************************************************************/
+
+/* The real size of the coefficient without leading zero words. */
+static inline mpd_ssize_t
+_mpd_real_size(mpd_uint_t *data, mpd_ssize_t size)
+{
+ while (size > 1 && data[size-1] == 0) {
+ size--;
+ }
+
+ return size;
+}
+
+/* Return number of trailing zeros. No errors are possible. */
+mpd_ssize_t
+mpd_trail_zeros(const mpd_t *dec)
+{
+ mpd_uint_t word;
+ mpd_ssize_t i, tz = 0;
+
+ for (i=0; i < dec->len; ++i) {
+ if (dec->data[i] != 0) {
+ word = dec->data[i];
+ tz = i * MPD_RDIGITS;
+ while (word % 10 == 0) {
+ word /= 10;
+ tz++;
+ }
+ break;
+ }
+ }
+
+ return tz;
+}
+
+/* Integer: Undefined for specials */
+static int
+_mpd_isint(const mpd_t *dec)
+{
+ mpd_ssize_t tz;
+
+ if (mpd_iszerocoeff(dec)) {
+ return 1;
+ }
+
+ tz = mpd_trail_zeros(dec);
+ return (dec->exp + tz >= 0);
+}
+
+/* Integer */
+int
+mpd_isinteger(const mpd_t *dec)
+{
+ if (mpd_isspecial(dec)) {
+ return 0;
+ }
+ return _mpd_isint(dec);
+}
+
+/* Word is a power of 10 */
+static int
+mpd_word_ispow10(mpd_uint_t word)
+{
+ int n;
+
+ n = mpd_word_digits(word);
+ if (word == mpd_pow10[n-1]) {
+ return 1;
+ }
+
+ return 0;
+}
+
+/* Coefficient is a power of 10 */
+static int
+mpd_coeff_ispow10(const mpd_t *dec)
+{
+ if (mpd_word_ispow10(mpd_msword(dec))) {
+ if (_mpd_isallzero(dec->data, dec->len-1)) {
+ return 1;
+ }
+ }
+
+ return 0;
+}
+
+/* All digits of a word are nines */
+static int
+mpd_word_isallnine(mpd_uint_t word)
+{
+ int n;
+
+ n = mpd_word_digits(word);
+ if (word == mpd_pow10[n]-1) {
+ return 1;
+ }
+
+ return 0;
+}
+
+/* All digits of the coefficient are nines */
+static int
+mpd_coeff_isallnine(const mpd_t *dec)
+{
+ if (mpd_word_isallnine(mpd_msword(dec))) {
+ if (_mpd_isallnine(dec->data, dec->len-1)) {
+ return 1;
+ }
+ }
+
+ return 0;
+}
+
+/* Odd decimal: Undefined for non-integers! */
+int
+mpd_isodd(const mpd_t *dec)
+{
+ mpd_uint_t q, r;
+ assert(mpd_isinteger(dec));
+ if (mpd_iszerocoeff(dec)) return 0;
+ if (dec->exp < 0) {
+ _mpd_div_word(&q, &r, -dec->exp, MPD_RDIGITS);
+ q = dec->data[q] / mpd_pow10[r];
+ return mpd_isoddword(q);
+ }
+ return dec->exp == 0 && mpd_isoddword(dec->data[0]);
+}
+
+/* Even: Undefined for non-integers! */
+int
+mpd_iseven(const mpd_t *dec)
+{
+ return !mpd_isodd(dec);
+}
+
+/******************************************************************************/
+/* Getting and setting decimals */
+/******************************************************************************/
+
+/* Internal function: Set a static decimal from a triple, no error checking. */
+static void
+_ssettriple(mpd_t *result, uint8_t sign, mpd_uint_t a, mpd_ssize_t exp)
+{
+ mpd_set_flags(result, sign);
+ result->exp = exp;
+ _mpd_div_word(&result->data[1], &result->data[0], a, MPD_RADIX);
+ result->len = (result->data[1] == 0) ? 1 : 2;
+ mpd_setdigits(result);
+}
+
+/* Internal function: Set a decimal from a triple, no error checking. */
+static void
+_settriple(mpd_t *result, uint8_t sign, mpd_uint_t a, mpd_ssize_t exp)
+{
+ mpd_minalloc(result);
+ mpd_set_flags(result, sign);
+ result->exp = exp;
+ _mpd_div_word(&result->data[1], &result->data[0], a, MPD_RADIX);
+ result->len = (result->data[1] == 0) ? 1 : 2;
+ mpd_setdigits(result);
+}
+
+/* Set a special number from a triple */
+void
+mpd_setspecial(mpd_t *result, uint8_t sign, uint8_t type)
+{
+ mpd_minalloc(result);
+ result->flags &= ~(MPD_NEG|MPD_SPECIAL);
+ result->flags |= (sign|type);
+ result->exp = result->digits = result->len = 0;
+}
+
+/* Set result of NaN with an error status */
+void
+mpd_seterror(mpd_t *result, uint32_t flags, uint32_t *status)
+{
+ mpd_minalloc(result);
+ mpd_set_qnan(result);
+ mpd_set_positive(result);
+ result->exp = result->digits = result->len = 0;
+ *status |= flags;
+}
+
+/* quietly set a static decimal from an mpd_ssize_t */
+void
+mpd_qsset_ssize(mpd_t *result, mpd_ssize_t a, const mpd_context_t *ctx, uint32_t *status)
+{
+ int adj = 0;
+
+ mpd_clear_flags(result);
+ if (a < 0) {
+ if (a == MPD_SSIZE_MIN) {
+ adj = 1;
+ a += 1;
+ }
+ result->flags |= MPD_NEG;
+ a = -a;
+ }
+ result->exp = 0;
+ _mpd_div_word(&result->data[1], &result->data[0], a, MPD_RADIX);
+ result->data[0] += adj;
+ result->len = (result->data[1] == 0) ? 1 : 2;
+ mpd_setdigits(result);
+
+ mpd_qfinalize(result, ctx, status);
+}
+
+/* quietly set a static decimal from an mpd_uint_t */
+void
+mpd_qsset_uint(mpd_t *result, mpd_uint_t a, const mpd_context_t *ctx, uint32_t *status)
+{
+ _ssettriple(result, MPD_POS, a, 0);
+ mpd_qfinalize(result, ctx, status);
+}
+
+/* quietly set a static decimal from an int32_t */
+void
+mpd_qsset_i32(mpd_t *result, int32_t a, const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_qsset_ssize(result, a, ctx, status);
+}
+
+/* quietly set a static decimal from a uint32_t */
+void
+mpd_qsset_u32(mpd_t *result, uint32_t a, const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_qsset_uint(result, a, ctx, status);
+}
+
+#ifdef CONFIG_64
+/* quietly set a static decimal from an int64_t */
+void
+mpd_qsset_i64(mpd_t *result, int64_t a, const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_qsset_ssize(result, a, ctx, status);
+}
+
+/* quietly set a static decimal from a uint64_t */
+void
+mpd_qsset_u64(mpd_t *result, uint64_t a, const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_qsset_uint(result, a, ctx, status);
+}
+#endif
+
+/* quietly set a decimal from an mpd_ssize_t */
+void
+mpd_qset_ssize(mpd_t *result, mpd_ssize_t a, const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_minalloc(result);
+ mpd_qsset_ssize(result, a, ctx, status);
+}
+
+/* quietly set a decimal from an mpd_uint_t */
+void
+mpd_qset_uint(mpd_t *result, mpd_uint_t a, const mpd_context_t *ctx, uint32_t *status)
+{
+ _settriple(result, MPD_POS, a, 0);
+ mpd_qfinalize(result, ctx, status);
+}
+
+/* quietly set a decimal from an int32_t */
+void
+mpd_qset_i32(mpd_t *result, int32_t a, const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_qset_ssize(result, a, ctx, status);
+}
+
+/* quietly set a decimal from a uint32_t */
+void
+mpd_qset_u32(mpd_t *result, uint32_t a, const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_qset_uint(result, a, ctx, status);
+}
+
+#ifdef CONFIG_64
+/* quietly set a decimal from an int64_t */
+void
+mpd_qset_i64(mpd_t *result, int64_t a, const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_qset_ssize(result, a, ctx, status);
+}
+
+/* quietly set a decimal from a uint64_t */
+void
+mpd_qset_u64(mpd_t *result, uint64_t a, const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_qset_uint(result, a, ctx, status);
+}
+#endif
+
+
+/*
+ * Quietly get an mpd_uint_t from a decimal. Assumes MPD_UINT_DIGITS == MPD_RDIGITS+1,
+ * which is true for 32 and 64 bit machines.
+ *
+ * If the operation is impossible, MPD_Invalid_operation is set.
+ */
+mpd_uint_t
+mpd_qget_uint(const mpd_t *a, uint32_t *status)
+{
+ mpd_t tmp;
+ mpd_uint_t tmp_data[2];
+ mpd_uint_t lo, hi;
+
+ if (mpd_isspecial(a)) {
+ *status |= MPD_Invalid_operation;
+ return MPD_UINT_MAX;
+ }
+
+ assert(a->len > 0);
+
+ if (mpd_iszero(a)) {
+ return 0;
+ }
+ if (a->digits+a->exp > MPD_RDIGITS+1) {
+ *status |= MPD_Invalid_operation;
+ return MPD_UINT_MAX;
+ }
+
+ if (a->exp < 0) {
+ if (!_mpd_isint(a)) {
+ *status |= MPD_Invalid_operation;
+ return MPD_UINT_MAX;
+ }
+ /* at this point a->digits+a->exp <= MPD_RDIGITS+1, so the shift fits */
+ tmp.data = tmp_data;
+ tmp.flags = MPD_STATIC|MPD_CONST_DATA;
+ mpd_qsshiftr(&tmp, a, -a->exp);
+ tmp.exp = 0;
+ a = &tmp;
+ }
+
+ _mpd_get_msdigits(&hi, &lo, a, MPD_RDIGITS+1);
+ if (hi) {
+ *status |= MPD_Invalid_operation;
+ return MPD_UINT_MAX;
+ }
+
+ if (a->exp > 0) {
+ _mpd_mul_words(&hi, &lo, lo, mpd_pow10[a->exp]);
+ if (hi) {
+ *status |= MPD_Invalid_operation;
+ return MPD_UINT_MAX;
+ }
+ }
+
+ return lo;
+}
+
+/* quietly get an mpd_ssize_t from a decimal */
+mpd_ssize_t
+mpd_qget_ssize(const mpd_t *a, uint32_t *status)
+{
+ mpd_uint_t u;
+ int isneg;
+
+ u = mpd_qget_uint(a, status);
+ if (*status&MPD_Invalid_operation) {
+ return MPD_SSIZE_MAX;
+ }
+
+ isneg = mpd_isnegative(a);
+ if (u <= MPD_SSIZE_MAX) {
+ return isneg ? -((mpd_ssize_t)u) : (mpd_ssize_t)u;
+ }
+ else if (isneg && u-1 == MPD_SSIZE_MAX) {
+ return MPD_SSIZE_MIN;
+ }
+
+ *status |= MPD_Invalid_operation;
+ return MPD_SSIZE_MAX;
+}
+
+#ifdef CONFIG_64
+/* quietly get a uint64_t from a decimal */
+uint64_t
+mpd_qget_u64(const mpd_t *a, uint32_t *status)
+{
+ return mpd_qget_uint(a, status);
+}
+
+/* quietly get an int64_t from a decimal */
+int64_t
+mpd_qget_i64(const mpd_t *a, uint32_t *status)
+{
+ return mpd_qget_ssize(a, status);
+}
+#else
+/* quietly get a uint32_t from a decimal */
+uint32_t
+mpd_qget_u32(const mpd_t *a, uint32_t *status)
+{
+ return mpd_qget_uint(a, status);
+}
+
+/* quietly get an int32_t from a decimal */
+int32_t
+mpd_qget_i32(const mpd_t *a, uint32_t *status)
+{
+ return mpd_qget_ssize(a, status);
+}
+#endif
+
+
+/******************************************************************************/
+/* Filtering input of functions, finalizing output of functions */
+/******************************************************************************/
+
+/*
+ * Check if the operand is NaN, copy to result and return 1 if this is
+ * the case. Copying can fail since NaNs are allowed to have a payload that
+ * does not fit in MPD_MINALLOC.
+ */
+int
+mpd_qcheck_nan(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status)
+{
+ if (mpd_isnan(a)) {
+ *status |= mpd_issnan(a) ? MPD_Invalid_operation : 0;
+ mpd_qcopy(result, a, status);
+ mpd_set_qnan(result);
+ _mpd_fix_nan(result, ctx);
+ return 1;
+ }
+ return 0;
+}
+
+/*
+ * Check if either operand is NaN, copy to result and return 1 if this
+ * is the case. Copying can fail since NaNs are allowed to have a payload
+ * that does not fit in MPD_MINALLOC.
+ */
+int
+mpd_qcheck_nans(mpd_t *result, const mpd_t *a, const mpd_t *b,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ if ((a->flags|b->flags)&(MPD_NAN|MPD_SNAN)) {
+ const mpd_t *choice = b;
+ if (mpd_issnan(a)) {
+ choice = a;
+ *status |= MPD_Invalid_operation;
+ }
+ else if (mpd_issnan(b)) {
+ *status |= MPD_Invalid_operation;
+ }
+ else if (mpd_isqnan(a)) {
+ choice = a;
+ }
+ mpd_qcopy(result, choice, status);
+ mpd_set_qnan(result);
+ _mpd_fix_nan(result, ctx);
+ return 1;
+ }
+ return 0;
+}
+
+/*
+ * Check if one of the operands is NaN, copy to result and return 1 if this
+ * is the case. Copying can fail since NaNs are allowed to have a payload
+ * that does not fit in MPD_MINALLOC.
+ */
+static int
+mpd_qcheck_3nans(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_t *c,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ if ((a->flags|b->flags|c->flags)&(MPD_NAN|MPD_SNAN)) {
+ const mpd_t *choice = c;
+ if (mpd_issnan(a)) {
+ choice = a;
+ *status |= MPD_Invalid_operation;
+ }
+ else if (mpd_issnan(b)) {
+ choice = b;
+ *status |= MPD_Invalid_operation;
+ }
+ else if (mpd_issnan(c)) {
+ *status |= MPD_Invalid_operation;
+ }
+ else if (mpd_isqnan(a)) {
+ choice = a;
+ }
+ else if (mpd_isqnan(b)) {
+ choice = b;
+ }
+ mpd_qcopy(result, choice, status);
+ mpd_set_qnan(result);
+ _mpd_fix_nan(result, ctx);
+ return 1;
+ }
+ return 0;
+}
+
+/* Check if rounding digit 'rnd' leads to an increment. */
+static inline int
+_mpd_rnd_incr(const mpd_t *dec, mpd_uint_t rnd, const mpd_context_t *ctx)
+{
+ int ld;
+
+ switch (ctx->round) {
+ case MPD_ROUND_DOWN: case MPD_ROUND_TRUNC:
+ return 0;
+ case MPD_ROUND_HALF_UP:
+ return (rnd >= 5);
+ case MPD_ROUND_HALF_EVEN:
+ return (rnd > 5) || ((rnd == 5) && mpd_isoddcoeff(dec));
+ case MPD_ROUND_CEILING:
+ return !(rnd == 0 || mpd_isnegative(dec));
+ case MPD_ROUND_FLOOR:
+ return !(rnd == 0 || mpd_ispositive(dec));
+ case MPD_ROUND_HALF_DOWN:
+ return (rnd > 5);
+ case MPD_ROUND_UP:
+ return !(rnd == 0);
+ case MPD_ROUND_05UP:
+ ld = (int)mpd_lsd(dec->data[0]);
+ return (!(rnd == 0) && (ld == 0 || ld == 5));
+ default:
+ /* Without a valid context, further results will be undefined. */
+ return 0;
+ }
+}
+
+/*
+ * Apply rounding to a decimal that has been right-shifted into a full
+ * precision decimal. If an increment leads to an overflow of the precision,
+ * adjust the coefficient and the exponent and check the new exponent for
+ * overflow.
+ */
+static inline void
+_mpd_apply_round(mpd_t *dec, mpd_uint_t rnd, const mpd_context_t *ctx, uint32_t *status)
+{
+ if (_mpd_rnd_incr(dec, rnd, ctx)) {
+ /* We have a number with exactly ctx->prec digits. The increment
+ * can only lead to an overflow if the decimal is all nines. In
+ * that case, the result is a power of ten with prec+1 digits.
+ *
+ * If the precision is a multiple of MPD_RDIGITS, this situation is
+ * detected by _mpd_baseincr returning a carry.
+ * If the precision is not a multiple of MPD_RDIGITS, we have to
+ * check if the result has one digit too many.
+ */
+ mpd_uint_t carry = _mpd_baseincr(dec->data, dec->len);
+ if (carry) {
+ dec->data[dec->len-1] = mpd_pow10[MPD_RDIGITS-1];
+ dec->exp += 1;
+ _mpd_check_exp(dec, ctx, status);
+ return;
+ }
+ mpd_setdigits(dec);
+ if (dec->digits > ctx->prec) {
+ mpd_qshiftr_inplace(dec, 1);
+ dec->exp += 1;
+ dec->digits = ctx->prec;
+ _mpd_check_exp(dec, ctx, status);
+ }
+ }
+}
+
+/*
+ * Apply rounding to a decimal. Allow overflow of the precision.
+ */
+static inline void
+_mpd_apply_round_excess(mpd_t *dec, mpd_uint_t rnd, const mpd_context_t *ctx, uint32_t *status)
+{
+ if (_mpd_rnd_incr(dec, rnd, ctx)) {
+ mpd_uint_t carry = _mpd_baseincr(dec->data, dec->len);
+ if (carry) {
+ if (!mpd_qresize(dec, dec->len+1, status)) {
+ return;
+ }
+ dec->data[dec->len] = 1;
+ dec->len += 1;
+ }
+ mpd_setdigits(dec);
+ }
+}
+
+/*
+ * Apply rounding to a decimal that has been right-shifted into a decimal
+ * with full precision or less. Return failure if an increment would
+ * overflow the precision.
+ */
+static inline int
+_mpd_apply_round_fit(mpd_t *dec, mpd_uint_t rnd, const mpd_context_t *ctx, uint32_t *status)
+{
+ if (_mpd_rnd_incr(dec, rnd, ctx)) {
+ mpd_uint_t carry = _mpd_baseincr(dec->data, dec->len);
+ if (carry) {
+ if (!mpd_qresize(dec, dec->len+1, status)) {
+ return 0;
+ }
+ dec->data[dec->len] = 1;
+ dec->len += 1;
+ }
+ mpd_setdigits(dec);
+ if (dec->digits > ctx->prec) {
+ mpd_seterror(dec, MPD_Invalid_operation, status);
+ return 0;
+ }
+ }
+ return 1;
+}
+
+/* Check a normal number for overflow, underflow, clamping. */
+static inline void
+_mpd_check_exp(mpd_t *dec, const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_ssize_t adjexp, etiny, shift;
+ int rnd;
+
+ adjexp = mpd_adjexp(dec);
+ if (adjexp > ctx->emax) {
+
+ if (mpd_iszerocoeff(dec)) {
+ dec->exp = ctx->emax;
+ if (ctx->clamp) {
+ dec->exp -= (ctx->prec-1);
+ }
+ mpd_zerocoeff(dec);
+ *status |= MPD_Clamped;
+ return;
+ }
+
+ switch (ctx->round) {
+ case MPD_ROUND_HALF_UP: case MPD_ROUND_HALF_EVEN:
+ case MPD_ROUND_HALF_DOWN: case MPD_ROUND_UP:
+ case MPD_ROUND_TRUNC:
+ mpd_setspecial(dec, mpd_sign(dec), MPD_INF);
+ break;
+ case MPD_ROUND_DOWN: case MPD_ROUND_05UP:
+ mpd_qmaxcoeff(dec, ctx, status);
+ dec->exp = ctx->emax - ctx->prec + 1;
+ break;
+ case MPD_ROUND_CEILING:
+ if (mpd_isnegative(dec)) {
+ mpd_qmaxcoeff(dec, ctx, status);
+ dec->exp = ctx->emax - ctx->prec + 1;
+ }
+ else {
+ mpd_setspecial(dec, MPD_POS, MPD_INF);
+ }
+ break;
+ case MPD_ROUND_FLOOR:
+ if (mpd_ispositive(dec)) {
+ mpd_qmaxcoeff(dec, ctx, status);
+ dec->exp = ctx->emax - ctx->prec + 1;
+ }
+ else {
+ mpd_setspecial(dec, MPD_NEG, MPD_INF);
+ }
+ break;
+ default: /* debug */
+ abort();
+ }
+
+ *status |= MPD_Overflow|MPD_Inexact|MPD_Rounded;
+
+ } /* fold down */
+ else if (ctx->clamp && dec->exp > mpd_etop(ctx)) {
+ shift = dec->exp - mpd_etop(ctx);
+ /* if shiftl fails, dec is NaN */
+ (void)mpd_qshiftl(dec, dec, shift, status);
+ dec->exp -= shift;
+ *status |= MPD_Clamped;
+ }
+ else if (adjexp < ctx->emin) {
+
+ etiny = mpd_etiny(ctx);
+
+ if (mpd_iszerocoeff(dec)) {
+ if (dec->exp < etiny) {
+ dec->exp = etiny;
+ mpd_zerocoeff(dec);
+ *status |= MPD_Clamped;
+ }
+ return;
+ }
+
+ *status |= MPD_Subnormal;
+ if (dec->exp < etiny) {
+ /* At this point adjexp=exp+digits-1 < emin and exp < etiny=emin-prec+1,
+ * so shift=emin-prec+1-exp > digits-prec, so digits-shift < prec.
+ * [acl2 proof: checkexp-1] */
+ shift = etiny - dec->exp;
+ rnd = (int)mpd_qshiftr_inplace(dec, shift);
+ dec->exp = etiny;
+ /* We always have a spare digit in case of an increment. */
+ _mpd_apply_round_excess(dec, rnd, ctx, status);
+ *status |= MPD_Rounded;
+ if (rnd) {
+ *status |= (MPD_Inexact|MPD_Underflow);
+ if (mpd_iszerocoeff(dec)) {
+ mpd_zerocoeff(dec);
+ *status |= MPD_Clamped;
+ }
+ }
+ }
+ }
+}
+
+/* Check if a normal number must be rounded after the exponent has been checked. */
+static inline void
+_mpd_check_round(mpd_t *dec, const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_uint_t rnd;
+ mpd_ssize_t shift;
+
+ /* must handle specials: _mpd_check_exp() can produce infinities or NaNs */
+ if (mpd_isspecial(dec)) {
+ return;
+ }
+
+ if (dec->digits > ctx->prec) {
+ shift = dec->digits - ctx->prec;
+ rnd = mpd_qshiftr_inplace(dec, shift);
+ dec->exp += shift;
+ _mpd_apply_round(dec, rnd, ctx, status);
+ *status |= MPD_Rounded;
+ if (rnd) {
+ *status |= MPD_Inexact;
+ }
+ }
+}
+
+/* Finalize all operations. */
+void
+mpd_qfinalize(mpd_t *result, const mpd_context_t *ctx, uint32_t *status)
+{
+ if (mpd_isspecial(result)) {
+ if (mpd_isnan(result)) {
+ _mpd_fix_nan(result, ctx);
+ }
+ return;
+ }
+
+ _mpd_check_exp(result, ctx, status);
+ _mpd_check_round(result, ctx, status);
+}
+
+
+/******************************************************************************/
+/* Copying */
+/******************************************************************************/
+
+/* Internal function: Copy a decimal, share data with src: USE WITH CARE! */
+static inline void
+_mpd_copy_shared(mpd_t *dest, const mpd_t *src)
+{
+ dest->flags = src->flags;
+ dest->exp = src->exp;
+ dest->digits = src->digits;
+ dest->len = src->len;
+ dest->alloc = src->alloc;
+ dest->data = src->data;
+
+ mpd_set_shared_data(dest);
+}
+
+/*
+ * Copy a decimal. In case of an error, status is set to MPD_Malloc_error.
+ * Does not raise.
+ */
+int
+mpd_qcopy(mpd_t *result, const mpd_t *a, uint32_t *status)
+{
+ if (result == a) return 1;
+
+ if (!mpd_qresize(result, a->len, status)) {
+ return 0;
+ }
+
+ mpd_copy_flags(result, a);
+ result->exp = a->exp;
+ result->digits = a->digits;
+ result->len = a->len;
+ memcpy(result->data, a->data, a->len * (sizeof *result->data));
+
+ return 1;
+}
+
+/*
+ * Copy to a decimal with a static buffer. The caller has to make sure that
+ * the buffer is big enough. Cannot fail.
+ */
+static void
+mpd_qcopy_static(mpd_t *result, const mpd_t *a)
+{
+ if (result == a) return;
+
+ memcpy(result->data, a->data, a->len * (sizeof *result->data));
+
+ mpd_copy_flags(result, a);
+ result->exp = a->exp;
+ result->digits = a->digits;
+ result->len = a->len;
+}
+
+/*
+ * Return a newly allocated copy of the operand. In case of an error,
+ * status is set to MPD_Malloc_error and the return value is NULL.
+ * Does not raise.
+ */
+mpd_t *
+mpd_qncopy(const mpd_t *a)
+{
+ mpd_t *result;
+
+ if ((result = mpd_qnew_size(a->len)) == NULL) {
+ return NULL;
+ }
+ memcpy(result->data, a->data, a->len * (sizeof *result->data));
+ mpd_copy_flags(result, a);
+ result->exp = a->exp;
+ result->digits = a->digits;
+ result->len = a->len;
+
+ return result;
+}
+
+/*
+ * Copy a decimal and set the sign to positive. In case of an error, the
+ * status is set to MPD_Malloc_error.
+ */
+int
+mpd_qcopy_abs(mpd_t *result, const mpd_t *a, uint32_t *status)
+{
+ if (!mpd_qcopy(result, a, status)) {
+ return 0;
+ }
+ mpd_set_positive(result);
+ return 1;
+}
+
+/*
+ * Copy a decimal and negate the sign. In case of an error, the
+ * status is set to MPD_Malloc_error.
+ */
+int
+mpd_qcopy_negate(mpd_t *result, const mpd_t *a, uint32_t *status)
+{
+ if (!mpd_qcopy(result, a, status)) {
+ return 0;
+ }
+ _mpd_negate(result);
+ return 1;
+}
+
+/*
+ * Copy a decimal, setting the sign of the first operand to the sign of the
+ * second operand. In case of an error, the status is set to MPD_Malloc_error.
+ */
+int
+mpd_qcopy_sign(mpd_t *result, const mpd_t *a, const mpd_t *b, uint32_t *status)
+{
+ uint8_t sign_b = mpd_sign(b); /* result may equal b! */
+
+ if (!mpd_qcopy(result, a, status)) {
+ return 0;
+ }
+ mpd_set_sign(result, sign_b);
+ return 1;
+}
+
+
+/******************************************************************************/
+/* Comparisons */
+/******************************************************************************/
+
+/*
+ * For all functions that compare two operands and return an int the usual
+ * convention applies to the return value:
+ *
+ * -1 if op1 < op2
+ * 0 if op1 == op2
+ * 1 if op1 > op2
+ *
+ * INT_MAX for error
+ */
+
+
+/* Convenience macro. If a and b are not equal, return from the calling
+ * function with the correct comparison value. */
+#define CMP_EQUAL_OR_RETURN(a, b) \
+ if (a != b) { \
+ if (a < b) { \
+ return -1; \
+ } \
+ return 1; \
+ }
+
+/*
+ * Compare the data of big and small. This function does the equivalent
+ * of first shifting small to the left and then comparing the data of
+ * big and small, except that no allocation for the left shift is needed.
+ */
+static int
+_mpd_basecmp(mpd_uint_t *big, mpd_uint_t *small, size_t n, size_t m, size_t shift)
+{
+#if defined(__GNUC__) && !defined(__INTEL_COMPILER)
+ /* spurious uninitialized warnings */
+ mpd_uint_t l=l, lprev=lprev, h=h;
+#else
+ mpd_uint_t l, lprev, h;
+#endif
+ mpd_uint_t q, r;
+ mpd_uint_t ph, x;
+
+ assert(m > 0 && n >= m && shift > 0);
+
+ _mpd_div_word(&q, &r, (mpd_uint_t)shift, MPD_RDIGITS);
+
+ if (r != 0) {
+
+ ph = mpd_pow10[r];
+
+ --m; --n;
+ _mpd_divmod_pow10(&h, &lprev, small[m--], MPD_RDIGITS-r);
+ if (h != 0) {
+ CMP_EQUAL_OR_RETURN(big[n], h)
+ --n;
+ }
+ for (; m != SIZE_MAX; m--,n--) {
+ _mpd_divmod_pow10(&h, &l, small[m], MPD_RDIGITS-r);
+ x = ph * lprev + h;
+ CMP_EQUAL_OR_RETURN(big[n], x)
+ lprev = l;
+ }
+ x = ph * lprev;
+ CMP_EQUAL_OR_RETURN(big[q], x)
+ }
+ else {
+ while (--m != SIZE_MAX) {
+ CMP_EQUAL_OR_RETURN(big[m+q], small[m])
+ }
+ }
+
+ return !_mpd_isallzero(big, q);
+}
+
+/* Compare two decimals with the same adjusted exponent. */
+static int
+_mpd_cmp_same_adjexp(const mpd_t *a, const mpd_t *b)
+{
+ mpd_ssize_t shift, i;
+
+ if (a->exp != b->exp) {
+ /* Cannot wrap: a->exp + a->digits = b->exp + b->digits, so
+ * a->exp - b->exp = b->digits - a->digits. */
+ shift = a->exp - b->exp;
+ if (shift > 0) {
+ return -1 * _mpd_basecmp(b->data, a->data, b->len, a->len, shift);
+ }
+ else {
+ return _mpd_basecmp(a->data, b->data, a->len, b->len, -shift);
+ }
+ }
+
+ /*
+ * At this point adjexp(a) == adjexp(b) and a->exp == b->exp,
+ * so a->digits == b->digits, therefore a->len == b->len.
+ */
+ for (i = a->len-1; i >= 0; --i) {
+ CMP_EQUAL_OR_RETURN(a->data[i], b->data[i])
+ }
+
+ return 0;
+}
+
+/* Compare two numerical values. */
+static int
+_mpd_cmp(const mpd_t *a, const mpd_t *b)
+{
+ mpd_ssize_t adjexp_a, adjexp_b;
+
+ /* equal pointers */
+ if (a == b) {
+ return 0;
+ }
+
+ /* infinities */
+ if (mpd_isinfinite(a)) {
+ if (mpd_isinfinite(b)) {
+ return mpd_isnegative(b) - mpd_isnegative(a);
+ }
+ return mpd_arith_sign(a);
+ }
+ if (mpd_isinfinite(b)) {
+ return -mpd_arith_sign(b);
+ }
+
+ /* zeros */
+ if (mpd_iszerocoeff(a)) {
+ if (mpd_iszerocoeff(b)) {
+ return 0;
+ }
+ return -mpd_arith_sign(b);
+ }
+ if (mpd_iszerocoeff(b)) {
+ return mpd_arith_sign(a);
+ }
+
+ /* different signs */
+ if (mpd_sign(a) != mpd_sign(b)) {
+ return mpd_sign(b) - mpd_sign(a);
+ }
+
+ /* different adjusted exponents */
+ adjexp_a = mpd_adjexp(a);
+ adjexp_b = mpd_adjexp(b);
+ if (adjexp_a != adjexp_b) {
+ if (adjexp_a < adjexp_b) {
+ return -1 * mpd_arith_sign(a);
+ }
+ return mpd_arith_sign(a);
+ }
+
+ /* same adjusted exponents */
+ return _mpd_cmp_same_adjexp(a, b) * mpd_arith_sign(a);
+}
+
+/* Compare the absolutes of two numerical values. */
+static int
+_mpd_cmp_abs(const mpd_t *a, const mpd_t *b)
+{
+ mpd_ssize_t adjexp_a, adjexp_b;
+
+ /* equal pointers */
+ if (a == b) {
+ return 0;
+ }
+
+ /* infinities */
+ if (mpd_isinfinite(a)) {
+ if (mpd_isinfinite(b)) {
+ return 0;
+ }
+ return 1;
+ }
+ if (mpd_isinfinite(b)) {
+ return -1;
+ }
+
+ /* zeros */
+ if (mpd_iszerocoeff(a)) {
+ if (mpd_iszerocoeff(b)) {
+ return 0;
+ }
+ return -1;
+ }
+ if (mpd_iszerocoeff(b)) {
+ return 1;
+ }
+
+ /* different adjusted exponents */
+ adjexp_a = mpd_adjexp(a);
+ adjexp_b = mpd_adjexp(b);
+ if (adjexp_a != adjexp_b) {
+ if (adjexp_a < adjexp_b) {
+ return -1;
+ }
+ return 1;
+ }
+
+ /* same adjusted exponents */
+ return _mpd_cmp_same_adjexp(a, b);
+}
+
+/* Compare two values and return an integer result. */
+int
+mpd_qcmp(const mpd_t *a, const mpd_t *b, uint32_t *status)
+{
+ if (mpd_isspecial(a) || mpd_isspecial(b)) {
+ if (mpd_isnan(a) || mpd_isnan(b)) {
+ *status |= MPD_Invalid_operation;
+ return INT_MAX;
+ }
+ }
+
+ return _mpd_cmp(a, b);
+}
+
+/*
+ * Compare a and b, convert the the usual integer result to a decimal and
+ * store it in 'result'. For convenience, the integer result of the comparison
+ * is returned. Comparisons involving NaNs return NaN/INT_MAX.
+ */
+int
+mpd_qcompare(mpd_t *result, const mpd_t *a, const mpd_t *b,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ int c;
+
+ if (mpd_isspecial(a) || mpd_isspecial(b)) {
+ if (mpd_qcheck_nans(result, a, b, ctx, status)) {
+ return INT_MAX;
+ }
+ }
+
+ c = _mpd_cmp(a, b);
+ _settriple(result, (c < 0), (c != 0), 0);
+ return c;
+}
+
+/* Same as mpd_compare(), but signal for all NaNs, i.e. also for quiet NaNs. */
+int
+mpd_qcompare_signal(mpd_t *result, const mpd_t *a, const mpd_t *b,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ int c;
+
+ if (mpd_isspecial(a) || mpd_isspecial(b)) {
+ if (mpd_qcheck_nans(result, a, b, ctx, status)) {
+ *status |= MPD_Invalid_operation;
+ return INT_MAX;
+ }
+ }
+
+ c = _mpd_cmp(a, b);
+ _settriple(result, (c < 0), (c != 0), 0);
+ return c;
+}
+
+/* Compare the operands using a total order. */
+int
+mpd_cmp_total(const mpd_t *a, const mpd_t *b)
+{
+ mpd_t aa, bb;
+ int nan_a, nan_b;
+ int c;
+
+ if (mpd_sign(a) != mpd_sign(b)) {
+ return mpd_sign(b) - mpd_sign(a);
+ }
+
+
+ if (mpd_isnan(a)) {
+ c = 1;
+ if (mpd_isnan(b)) {
+ nan_a = (mpd_isqnan(a)) ? 1 : 0;
+ nan_b = (mpd_isqnan(b)) ? 1 : 0;
+ if (nan_b == nan_a) {
+ if (a->len > 0 && b->len > 0) {
+ _mpd_copy_shared(&aa, a);
+ _mpd_copy_shared(&bb, b);
+ aa.exp = bb.exp = 0;
+ /* compare payload */
+ c = _mpd_cmp_abs(&aa, &bb);
+ }
+ else {
+ c = (a->len > 0) - (b->len > 0);
+ }
+ }
+ else {
+ c = nan_a - nan_b;
+ }
+ }
+ }
+ else if (mpd_isnan(b)) {
+ c = -1;
+ }
+ else {
+ c = _mpd_cmp_abs(a, b);
+ if (c == 0 && a->exp != b->exp) {
+ c = (a->exp < b->exp) ? -1 : 1;
+ }
+ }
+
+ return c * mpd_arith_sign(a);
+}
+
+/*
+ * Compare a and b according to a total order, convert the usual integer result
+ * to a decimal and store it in 'result'. For convenience, the integer result
+ * of the comparison is returned.
+ */
+int
+mpd_compare_total(mpd_t *result, const mpd_t *a, const mpd_t *b)
+{
+ int c;
+
+ c = mpd_cmp_total(a, b);
+ _settriple(result, (c < 0), (c != 0), 0);
+ return c;
+}
+
+/* Compare the magnitude of the operands using a total order. */
+int
+mpd_cmp_total_mag(const mpd_t *a, const mpd_t *b)
+{
+ mpd_t aa, bb;
+
+ _mpd_copy_shared(&aa, a);
+ _mpd_copy_shared(&bb, b);
+
+ mpd_set_positive(&aa);
+ mpd_set_positive(&bb);
+
+ return mpd_cmp_total(&aa, &bb);
+}
+
+/*
+ * Compare the magnitude of a and b according to a total order, convert the
+ * the usual integer result to a decimal and store it in 'result'.
+ * For convenience, the integer result of the comparison is returned.
+ */
+int
+mpd_compare_total_mag(mpd_t *result, const mpd_t *a, const mpd_t *b)
+{
+ int c;
+
+ c = mpd_cmp_total_mag(a, b);
+ _settriple(result, (c < 0), (c != 0), 0);
+ return c;
+}
+
+/* Determine an ordering for operands that are numerically equal. */
+static inline int
+_mpd_cmp_numequal(const mpd_t *a, const mpd_t *b)
+{
+ int sign_a, sign_b;
+ int c;
+
+ sign_a = mpd_sign(a);
+ sign_b = mpd_sign(b);
+ if (sign_a != sign_b) {
+ c = sign_b - sign_a;
+ }
+ else {
+ c = (a->exp < b->exp) ? -1 : 1;
+ c *= mpd_arith_sign(a);
+ }
+
+ return c;
+}
+
+
+/******************************************************************************/
+/* Shifting the coefficient */
+/******************************************************************************/
+
+/*
+ * Shift the coefficient of the operand to the left, no check for specials.
+ * Both operands may be the same pointer. If the result length has to be
+ * increased, mpd_qresize() might fail with MPD_Malloc_error.
+ */
+int
+mpd_qshiftl(mpd_t *result, const mpd_t *a, mpd_ssize_t n, uint32_t *status)
+{
+ mpd_ssize_t size;
+
+ assert(n >= 0);
+
+ if (mpd_iszerocoeff(a) || n == 0) {
+ mpd_qcopy(result, a, status);
+ return 1;
+ }
+
+ size = mpd_digits_to_size(a->digits+n);
+ if (!mpd_qresize(result, size, status)) {
+ return 0; /* result is NaN */
+ }
+
+ _mpd_baseshiftl(result->data, a->data, size, a->len, n);
+
+ mpd_copy_flags(result, a);
+ result->len = size;
+ result->exp = a->exp;
+ result->digits = a->digits+n;
+
+ return 1;
+}
+
+/* Determine the rounding indicator if all digits of the coefficient are shifted
+ * out of the picture. */
+static mpd_uint_t
+_mpd_get_rnd(const mpd_uint_t *data, mpd_ssize_t len, int use_msd)
+{
+ mpd_uint_t rnd = 0, rest = 0, word;
+
+ word = data[len-1];
+ /* special treatment for the most significant digit if shift == digits */
+ if (use_msd) {
+ _mpd_divmod_pow10(&rnd, &rest, word, mpd_word_digits(word)-1);
+ if (len > 1 && rest == 0) {
+ rest = !_mpd_isallzero(data, len-1);
+ }
+ }
+ else {
+ rest = !_mpd_isallzero(data, len);
+ }
+
+ return (rnd == 0 || rnd == 5) ? rnd + !!rest : rnd;
+}
+
+/*
+ * Same as mpd_qshiftr(), but 'result' is a static array. It is the
+ * caller's responsibility to make sure that the array is big enough.
+ * The function cannot fail.
+ */
+static mpd_uint_t
+mpd_qsshiftr(mpd_t *result, const mpd_t *a, mpd_ssize_t n)
+{
+ mpd_uint_t rnd;
+ mpd_ssize_t size;
+
+ assert(n >= 0);
+
+ if (mpd_iszerocoeff(a) || n == 0) {
+ mpd_qcopy_static(result, a);
+ return 0;
+ }
+
+ if (n >= a->digits) {
+ rnd = _mpd_get_rnd(a->data, a->len, (n==a->digits));
+ mpd_zerocoeff(result);
+ result->digits = 1;
+ size = 1;
+ }
+ else {
+ result->digits = a->digits-n;
+ size = mpd_digits_to_size(result->digits);
+ rnd = _mpd_baseshiftr(result->data, a->data, a->len, n);
+ }
+
+ mpd_copy_flags(result, a);
+ result->exp = a->exp;
+ result->len = size;
+
+ return rnd;
+}
+
+/*
+ * Inplace shift of the coefficient to the right, no check for specials.
+ * Returns the rounding indicator for mpd_rnd_incr().
+ * The function cannot fail.
+ */
+mpd_uint_t
+mpd_qshiftr_inplace(mpd_t *result, mpd_ssize_t n)
+{
+ uint32_t dummy;
+ mpd_uint_t rnd;
+ mpd_ssize_t size;
+
+ assert(n >= 0);
+
+ if (mpd_iszerocoeff(result) || n == 0) {
+ return 0;
+ }
+
+ if (n >= result->digits) {
+ rnd = _mpd_get_rnd(result->data, result->len, (n==result->digits));
+ mpd_zerocoeff(result);
+ result->digits = 1;
+ size = 1;
+ }
+ else {
+ rnd = _mpd_baseshiftr(result->data, result->data, result->len, n);
+ result->digits -= n;
+ size = mpd_digits_to_size(result->digits);
+ /* reducing the size cannot fail */
+ mpd_qresize(result, size, &dummy);
+ }
+
+ result->len = size;
+
+ return rnd;
+}
+
+/*
+ * Shift the coefficient of the operand to the right, no check for specials.
+ * Both operands may be the same pointer. Returns the rounding indicator to
+ * be used by mpd_rnd_incr(). If the result length has to be increased,
+ * mpd_qcopy() or mpd_qresize() might fail with MPD_Malloc_error. In those
+ * cases, MPD_UINT_MAX is returned.
+ */
+mpd_uint_t
+mpd_qshiftr(mpd_t *result, const mpd_t *a, mpd_ssize_t n, uint32_t *status)
+{
+ mpd_uint_t rnd;
+ mpd_ssize_t size;
+
+ assert(n >= 0);
+
+ if (mpd_iszerocoeff(a) || n == 0) {
+ if (!mpd_qcopy(result, a, status)) {
+ return MPD_UINT_MAX;
+ }
+ return 0;
+ }
+
+ if (n >= a->digits) {
+ rnd = _mpd_get_rnd(a->data, a->len, (n==a->digits));
+ mpd_zerocoeff(result);
+ result->digits = 1;
+ size = 1;
+ }
+ else {
+ result->digits = a->digits-n;
+ size = mpd_digits_to_size(result->digits);
+ if (result == a) {
+ rnd = _mpd_baseshiftr(result->data, a->data, a->len, n);
+ /* reducing the size cannot fail */
+ mpd_qresize(result, size, status);
+ }
+ else {
+ if (!mpd_qresize(result, size, status)) {
+ return MPD_UINT_MAX;
+ }
+ rnd = _mpd_baseshiftr(result->data, a->data, a->len, n);
+ }
+ }
+
+ mpd_copy_flags(result, a);
+ result->exp = a->exp;
+ result->len = size;
+
+ return rnd;
+}
+
+
+/******************************************************************************/
+/* Miscellaneous operations */
+/******************************************************************************/
+
+/* Logical And */
+void
+mpd_qand(mpd_t *result, const mpd_t *a, const mpd_t *b,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ const mpd_t *big = a, *small = b;
+ mpd_uint_t x, y, z, xbit, ybit;
+ int k, mswdigits;
+ mpd_ssize_t i;
+
+ if (mpd_isspecial(a) || mpd_isspecial(b) ||
+ mpd_isnegative(a) || mpd_isnegative(b) ||
+ a->exp != 0 || b->exp != 0) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+ if (b->digits > a->digits) {
+ big = b;
+ small = a;
+ }
+ if (!mpd_qresize(result, big->len, status)) {
+ return;
+ }
+
+
+ /* full words */
+ for (i = 0; i < small->len-1; i++) {
+ x = small->data[i];
+ y = big->data[i];
+ z = 0;
+ for (k = 0; k < MPD_RDIGITS; k++) {
+ xbit = x % 10;
+ x /= 10;
+ ybit = y % 10;
+ y /= 10;
+ if (xbit > 1 || ybit > 1) {
+ goto invalid_operation;
+ }
+ z += (xbit&ybit) ? mpd_pow10[k] : 0;
+ }
+ result->data[i] = z;
+ }
+ /* most significant word of small */
+ x = small->data[i];
+ y = big->data[i];
+ z = 0;
+ mswdigits = mpd_word_digits(x);
+ for (k = 0; k < mswdigits; k++) {
+ xbit = x % 10;
+ x /= 10;
+ ybit = y % 10;
+ y /= 10;
+ if (xbit > 1 || ybit > 1) {
+ goto invalid_operation;
+ }
+ z += (xbit&ybit) ? mpd_pow10[k] : 0;
+ }
+ result->data[i++] = z;
+
+ /* scan the rest of y for digit > 1 */
+ for (; k < MPD_RDIGITS; k++) {
+ ybit = y % 10;
+ y /= 10;
+ if (ybit > 1) {
+ goto invalid_operation;
+ }
+ }
+ /* scan the rest of big for digit > 1 */
+ for (; i < big->len; i++) {
+ y = big->data[i];
+ for (k = 0; k < MPD_RDIGITS; k++) {
+ ybit = y % 10;
+ y /= 10;
+ if (ybit > 1) {
+ goto invalid_operation;
+ }
+ }
+ }
+
+ mpd_clear_flags(result);
+ result->exp = 0;
+ result->len = _mpd_real_size(result->data, small->len);
+ mpd_qresize(result, result->len, status);
+ mpd_setdigits(result);
+ _mpd_cap(result, ctx);
+ return;
+
+invalid_operation:
+ mpd_seterror(result, MPD_Invalid_operation, status);
+}
+
+/* Class of an operand. Returns a pointer to the constant name. */
+const char *
+mpd_class(const mpd_t *a, const mpd_context_t *ctx)
+{
+ if (mpd_isnan(a)) {
+ if (mpd_isqnan(a))
+ return "NaN";
+ else
+ return "sNaN";
+ }
+ else if (mpd_ispositive(a)) {
+ if (mpd_isinfinite(a))
+ return "+Infinity";
+ else if (mpd_iszero(a))
+ return "+Zero";
+ else if (mpd_isnormal(a, ctx))
+ return "+Normal";
+ else
+ return "+Subnormal";
+ }
+ else {
+ if (mpd_isinfinite(a))
+ return "-Infinity";
+ else if (mpd_iszero(a))
+ return "-Zero";
+ else if (mpd_isnormal(a, ctx))
+ return "-Normal";
+ else
+ return "-Subnormal";
+ }
+}
+
+/* Logical Xor */
+void
+mpd_qinvert(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ mpd_uint_t x, z, xbit;
+ mpd_ssize_t i, digits, len;
+ mpd_ssize_t q, r;
+ int k;
+
+ if (mpd_isspecial(a) || mpd_isnegative(a) || a->exp != 0) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+
+ digits = (a->digits < ctx->prec) ? ctx->prec : a->digits;
+ _mpd_idiv_word(&q, &r, digits, MPD_RDIGITS);
+ len = (r == 0) ? q : q+1;
+ if (!mpd_qresize(result, len, status)) {
+ return;
+ }
+
+ for (i = 0; i < len; i++) {
+ x = (i < a->len) ? a->data[i] : 0;
+ z = 0;
+ for (k = 0; k < MPD_RDIGITS; k++) {
+ xbit = x % 10;
+ x /= 10;
+ if (xbit > 1) {
+ goto invalid_operation;
+ }
+ z += !xbit ? mpd_pow10[k] : 0;
+ }
+ result->data[i] = z;
+ }
+
+ mpd_clear_flags(result);
+ result->exp = 0;
+ result->len = _mpd_real_size(result->data, len);
+ mpd_setdigits(result);
+ _mpd_cap(result, ctx);
+ return;
+
+invalid_operation:
+ mpd_seterror(result, MPD_Invalid_operation, status);
+}
+
+/* Exponent of the magnitude of the most significant digit of the operand. */
+void
+mpd_qlogb(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status)
+{
+ if (mpd_isspecial(a)) {
+ if (mpd_qcheck_nan(result, a, ctx, status)) {
+ return;
+ }
+ mpd_setspecial(result, MPD_POS, MPD_INF);
+ }
+ else if (mpd_iszerocoeff(a)) {
+ mpd_setspecial(result, MPD_NEG, MPD_INF);
+ *status |= MPD_Division_by_zero;
+ }
+ else {
+ mpd_qset_ssize(result, mpd_adjexp(a), ctx, status);
+ }
+}
+
+/* Logical Or */
+void
+mpd_qor(mpd_t *result, const mpd_t *a, const mpd_t *b,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ const mpd_t *big = a, *small = b;
+ mpd_uint_t x, y, z, xbit, ybit;
+ int k, mswdigits;
+ mpd_ssize_t i;
+
+ if (mpd_isspecial(a) || mpd_isspecial(b) ||
+ mpd_isnegative(a) || mpd_isnegative(b) ||
+ a->exp != 0 || b->exp != 0) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+ if (b->digits > a->digits) {
+ big = b;
+ small = a;
+ }
+ if (!mpd_qresize(result, big->len, status)) {
+ return;
+ }
+
+
+ /* full words */
+ for (i = 0; i < small->len-1; i++) {
+ x = small->data[i];
+ y = big->data[i];
+ z = 0;
+ for (k = 0; k < MPD_RDIGITS; k++) {
+ xbit = x % 10;
+ x /= 10;
+ ybit = y % 10;
+ y /= 10;
+ if (xbit > 1 || ybit > 1) {
+ goto invalid_operation;
+ }
+ z += (xbit|ybit) ? mpd_pow10[k] : 0;
+ }
+ result->data[i] = z;
+ }
+ /* most significant word of small */
+ x = small->data[i];
+ y = big->data[i];
+ z = 0;
+ mswdigits = mpd_word_digits(x);
+ for (k = 0; k < mswdigits; k++) {
+ xbit = x % 10;
+ x /= 10;
+ ybit = y % 10;
+ y /= 10;
+ if (xbit > 1 || ybit > 1) {
+ goto invalid_operation;
+ }
+ z += (xbit|ybit) ? mpd_pow10[k] : 0;
+ }
+
+ /* scan and copy the rest of y for digit > 1 */
+ for (; k < MPD_RDIGITS; k++) {
+ ybit = y % 10;
+ y /= 10;
+ if (ybit > 1) {
+ goto invalid_operation;
+ }
+ z += ybit*mpd_pow10[k];
+ }
+ result->data[i++] = z;
+ /* scan and copy the rest of big for digit > 1 */
+ for (; i < big->len; i++) {
+ y = big->data[i];
+ for (k = 0; k < MPD_RDIGITS; k++) {
+ ybit = y % 10;
+ y /= 10;
+ if (ybit > 1) {
+ goto invalid_operation;
+ }
+ }
+ result->data[i] = big->data[i];
+ }
+
+ mpd_clear_flags(result);
+ result->exp = 0;
+ result->len = _mpd_real_size(result->data, big->len);
+ mpd_setdigits(result);
+ _mpd_cap(result, ctx);
+ return;
+
+invalid_operation:
+ mpd_seterror(result, MPD_Invalid_operation, status);
+}
+
+/*
+ * Rotate the coefficient of a by b->data digits. b must be an integer with
+ * exponent 0.
+ */
+void
+mpd_qrotate(mpd_t *result, const mpd_t *a, const mpd_t *b,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ uint32_t workstatus = 0;
+ MPD_NEW_STATIC(tmp,0,0,0,0);
+ MPD_NEW_STATIC(big,0,0,0,0);
+ MPD_NEW_STATIC(small,0,0,0,0);
+ mpd_ssize_t n, lshift, rshift;
+
+ if (mpd_isspecial(a) || mpd_isspecial(b)) {
+ if (mpd_qcheck_nans(result, a, b, ctx, status)) {
+ return;
+ }
+ }
+ if (b->exp != 0 || mpd_isinfinite(b)) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+
+ n = mpd_qget_ssize(b, &workstatus);
+ if (workstatus&MPD_Invalid_operation) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+ if (n > ctx->prec || n < -ctx->prec) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+ if (mpd_isinfinite(a)) {
+ mpd_qcopy(result, a, status);
+ return;
+ }
+
+ if (n >= 0) {
+ lshift = n;
+ rshift = ctx->prec-n;
+ }
+ else {
+ lshift = ctx->prec+n;
+ rshift = -n;
+ }
+
+ if (a->digits > ctx->prec) {
+ if (!mpd_qcopy(&tmp, a, status)) {
+ return;
+ }
+ _mpd_cap(&tmp, ctx);
+ a = &tmp;
+ }
+
+ if (!mpd_qshiftl(&big, a, lshift, status)) {
+ mpd_seterror(result, MPD_Malloc_error, status);
+ goto finish;
+ }
+ _mpd_cap(&big, ctx);
+
+ if (mpd_qshiftr(&small, a, rshift, status) == MPD_UINT_MAX) {
+ mpd_seterror(result, MPD_Malloc_error, status);
+ goto finish;
+ }
+ _mpd_qadd(result, &big, &small, ctx, status);
+
+
+finish:
+ mpd_del(&tmp);
+ mpd_del(&big);
+ mpd_del(&small);
+}
+
+/*
+ * b must be an integer with exponent 0 and in the range +-2*(emax + prec).
+ * XXX: In my opinion +-(2*emax + prec) would be more sensible.
+ * The result is a with the value of b added to its exponent.
+ */
+void
+mpd_qscaleb(mpd_t *result, const mpd_t *a, const mpd_t *b,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ uint32_t workstatus = 0;
+ mpd_uint_t n, maxjump;
+ int64_t exp;
+
+ if (mpd_isspecial(a) || mpd_isspecial(b)) {
+ if (mpd_qcheck_nans(result, a, b, ctx, status)) {
+ return;
+ }
+ }
+ if (b->exp != 0 || mpd_isinfinite(b)) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+
+ n = mpd_qget_uint(b, &workstatus);
+ /* the spec demands this */
+ maxjump = 2 * (ctx->emax + ctx->prec);
+
+ if (n > maxjump || workstatus&MPD_Invalid_operation) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+ if (mpd_isinfinite(a)) {
+ mpd_qcopy(result, a, status);
+ return;
+ }
+
+ exp = a->exp + (int64_t)n * mpd_arith_sign(b);
+ exp = (exp > MPD_EXP_INF) ? MPD_EXP_INF : exp;
+ exp = (exp < MPD_EXP_CLAMP) ? MPD_EXP_CLAMP : exp;
+ mpd_qcopy(result, a, status);
+ result->exp = (mpd_ssize_t)exp;
+
+ mpd_qfinalize(result, ctx, status);
+}
+
+/*
+ * Shift the coefficient by n digits, positive n is a left shift. In the case
+ * of a left shift, the result is decapitated to fit the context precision. If
+ * you don't want that, use mpd_shiftl().
+ */
+void
+mpd_qshiftn(mpd_t *result, const mpd_t *a, mpd_ssize_t n, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ if (mpd_isspecial(a)) {
+ if (mpd_qcheck_nan(result, a, ctx, status)) {
+ return;
+ }
+ mpd_qcopy(result, a, status);
+ return;
+ }
+
+ if (n >= 0 && n <= ctx->prec) {
+ mpd_qshiftl(result, a, n, status);
+ _mpd_cap(result, ctx);
+ }
+ else if (n < 0 && n >= -ctx->prec) {
+ if (!mpd_qcopy(result, a, status)) {
+ return;
+ }
+ _mpd_cap(result, ctx);
+ mpd_qshiftr_inplace(result, -n);
+ }
+ else {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ }
+}
+
+/*
+ * Same as mpd_shiftn(), but the shift is specified by the decimal b, which
+ * must be an integer with a zero exponent. Infinities remain infinities.
+ */
+void
+mpd_qshift(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ uint32_t workstatus = 0;
+ mpd_ssize_t n;
+
+ if (mpd_isspecial(a) || mpd_isspecial(b)) {
+ if (mpd_qcheck_nans(result, a, b, ctx, status)) {
+ return;
+ }
+ }
+ if (b->exp != 0 || mpd_isinfinite(b)) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+
+ n = mpd_qget_ssize(b, &workstatus);
+ if (workstatus&MPD_Invalid_operation) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+ if (n > ctx->prec || n < -ctx->prec) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+ if (mpd_isinfinite(a)) {
+ mpd_qcopy(result, a, status);
+ return;
+ }
+
+ if (n >= 0) {
+ mpd_qshiftl(result, a, n, status);
+ _mpd_cap(result, ctx);
+ }
+ else {
+ if (!mpd_qcopy(result, a, status)) {
+ return;
+ }
+ _mpd_cap(result, ctx);
+ mpd_qshiftr_inplace(result, -n);
+ }
+}
+
+/* Logical Xor */
+void
+mpd_qxor(mpd_t *result, const mpd_t *a, const mpd_t *b,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ const mpd_t *big = a, *small = b;
+ mpd_uint_t x, y, z, xbit, ybit;
+ int k, mswdigits;
+ mpd_ssize_t i;
+
+ if (mpd_isspecial(a) || mpd_isspecial(b) ||
+ mpd_isnegative(a) || mpd_isnegative(b) ||
+ a->exp != 0 || b->exp != 0) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+ if (b->digits > a->digits) {
+ big = b;
+ small = a;
+ }
+ if (!mpd_qresize(result, big->len, status)) {
+ return;
+ }
+
+
+ /* full words */
+ for (i = 0; i < small->len-1; i++) {
+ x = small->data[i];
+ y = big->data[i];
+ z = 0;
+ for (k = 0; k < MPD_RDIGITS; k++) {
+ xbit = x % 10;
+ x /= 10;
+ ybit = y % 10;
+ y /= 10;
+ if (xbit > 1 || ybit > 1) {
+ goto invalid_operation;
+ }
+ z += (xbit^ybit) ? mpd_pow10[k] : 0;
+ }
+ result->data[i] = z;
+ }
+ /* most significant word of small */
+ x = small->data[i];
+ y = big->data[i];
+ z = 0;
+ mswdigits = mpd_word_digits(x);
+ for (k = 0; k < mswdigits; k++) {
+ xbit = x % 10;
+ x /= 10;
+ ybit = y % 10;
+ y /= 10;
+ if (xbit > 1 || ybit > 1) {
+ goto invalid_operation;
+ }
+ z += (xbit^ybit) ? mpd_pow10[k] : 0;
+ }
+
+ /* scan and copy the rest of y for digit > 1 */
+ for (; k < MPD_RDIGITS; k++) {
+ ybit = y % 10;
+ y /= 10;
+ if (ybit > 1) {
+ goto invalid_operation;
+ }
+ z += ybit*mpd_pow10[k];
+ }
+ result->data[i++] = z;
+ /* scan and copy the rest of big for digit > 1 */
+ for (; i < big->len; i++) {
+ y = big->data[i];
+ for (k = 0; k < MPD_RDIGITS; k++) {
+ ybit = y % 10;
+ y /= 10;
+ if (ybit > 1) {
+ goto invalid_operation;
+ }
+ }
+ result->data[i] = big->data[i];
+ }
+
+ mpd_clear_flags(result);
+ result->exp = 0;
+ result->len = _mpd_real_size(result->data, big->len);
+ mpd_setdigits(result);
+ _mpd_cap(result, ctx);
+ return;
+
+invalid_operation:
+ mpd_seterror(result, MPD_Invalid_operation, status);
+}
+
+
+/******************************************************************************/
+/* Arithmetic operations */
+/******************************************************************************/
+
+/*
+ * The absolute value of a. If a is negative, the result is the same
+ * as the result of the minus operation. Otherwise, the result is the
+ * result of the plus operation.
+ */
+void
+mpd_qabs(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status)
+{
+ if (mpd_isspecial(a)) {
+ if (mpd_qcheck_nan(result, a, ctx, status)) {
+ return;
+ }
+ }
+
+ if (mpd_isnegative(a)) {
+ mpd_qminus(result, a, ctx, status);
+ }
+ else {
+ mpd_qplus(result, a, ctx, status);
+ }
+
+ mpd_qfinalize(result, ctx, status);
+}
+
+static inline void
+_mpd_ptrswap(mpd_t **a, mpd_t **b)
+{
+ mpd_t *t = *a;
+ *a = *b;
+ *b = t;
+}
+
+/* Add or subtract infinities. */
+static void
+_mpd_qaddsub_inf(mpd_t *result, const mpd_t *a, const mpd_t *b, uint8_t sign_b, uint32_t *status)
+{
+ if (mpd_isinfinite(a)) {
+ if (mpd_sign(a) != sign_b && mpd_isinfinite(b)) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ }
+ else {
+ mpd_setspecial(result, mpd_sign(a), MPD_INF);
+ }
+ return;
+ }
+ assert(mpd_isinfinite(b));
+ mpd_setspecial(result, sign_b, MPD_INF);
+}
+
+/* Add or subtract non-special numbers. */
+static void
+_mpd_qaddsub(mpd_t *result, const mpd_t *a, const mpd_t *b, uint8_t sign_b,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_t *big, *small;
+ MPD_NEW_STATIC(big_aligned,0,0,0,0);
+ MPD_NEW_CONST(tiny,0,0,0,1,1,1);
+ mpd_uint_t carry;
+ mpd_ssize_t newsize, shift;
+ mpd_ssize_t exp, i;
+ int swap = 0;
+
+
+ /* compare exponents */
+ big = (mpd_t *)a; small = (mpd_t *)b;
+ if (big->exp != small->exp) {
+ if (small->exp > big->exp) {
+ _mpd_ptrswap(&big, &small);
+ swap++;
+ }
+ if (!mpd_iszerocoeff(big)) {
+ /* Test for adjexp(small) + big->digits < adjexp(big), if big-digits > prec
+ * Test for adjexp(small) + prec + 1 < adjexp(big), if big-digits <= prec
+ * If true, the magnitudes of the numbers are so far apart that one can as
+ * well add or subtract 1*10**big->exp. */
+ exp = big->exp - 1;
+ exp += (big->digits > ctx->prec) ? 0 : big->digits-ctx->prec-1;
+ if (mpd_adjexp(small) < exp) {
+ mpd_copy_flags(&tiny, small);
+ tiny.exp = exp;
+ tiny.digits = 1;
+ tiny.len = 1;
+ tiny.data[0] = mpd_iszerocoeff(small) ? 0 : 1;
+ small = &tiny;
+ }
+ /* this cannot wrap: the difference is positive and <= maxprec+1 */
+ shift = big->exp - small->exp;
+ if (!mpd_qshiftl(&big_aligned, big, shift, status)) {
+ mpd_seterror(result, MPD_Malloc_error, status);
+ goto finish;
+ }
+ big = &big_aligned;
+ }
+ }
+ result->exp = small->exp;
+
+
+ /* compare length of coefficients */
+ if (big->len < small->len) {
+ _mpd_ptrswap(&big, &small);
+ swap++;
+ }
+
+ newsize = big->len;
+ if (!mpd_qresize(result, newsize, status)) {
+ goto finish;
+ }
+
+ if (mpd_sign(a) == sign_b) {
+
+ carry = _mpd_baseadd(result->data, big->data, small->data, big->len, small->len);
+
+ if (carry) {
+ newsize = big->len + 1;
+ if (!mpd_qresize(result, newsize, status)) {
+ goto finish;
+ }
+ result->data[newsize-1] = carry;
+ }
+
+ result->len = newsize;
+ mpd_set_flags(result, sign_b);
+ }
+ else {
+ if (big->len == small->len) {
+ for (i=big->len-1; i >= 0; --i) {
+ if (big->data[i] != small->data[i]) {
+ if (big->data[i] < small->data[i]) {
+ _mpd_ptrswap(&big, &small);
+ swap++;
+ }
+ break;
+ }
+ }
+ }
+
+ _mpd_basesub(result->data, big->data, small->data, big->len, small->len);
+ newsize = _mpd_real_size(result->data, big->len);
+ /* resize to smaller cannot fail */
+ (void)mpd_qresize(result, newsize, status);
+
+ result->len = newsize;
+ sign_b = (swap & 1) ? sign_b : mpd_sign(a);
+ mpd_set_flags(result, sign_b);
+
+ if (mpd_iszerocoeff(result)) {
+ mpd_set_positive(result);
+ if (ctx->round == MPD_ROUND_FLOOR) {
+ mpd_set_negative(result);
+ }
+ }
+ }
+
+ mpd_setdigits(result);
+
+finish:
+ mpd_del(&big_aligned);
+}
+
+/* Add a and b. No specials, no finalizing. */
+static void
+_mpd_qadd(mpd_t *result, const mpd_t *a, const mpd_t *b,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ _mpd_qaddsub(result, a, b, mpd_sign(b), ctx, status);
+}
+
+/* Subtract b from a. No specials, no finalizing. */
+static void
+_mpd_qsub(mpd_t *result, const mpd_t *a, const mpd_t *b,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ _mpd_qaddsub(result, a, b, !mpd_sign(b), ctx, status);
+}
+
+/* Add a and b. */
+void
+mpd_qadd(mpd_t *result, const mpd_t *a, const mpd_t *b,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ if (mpd_isspecial(a) || mpd_isspecial(b)) {
+ if (mpd_qcheck_nans(result, a, b, ctx, status)) {
+ return;
+ }
+ _mpd_qaddsub_inf(result, a, b, mpd_sign(b), status);
+ return;
+ }
+
+ _mpd_qaddsub(result, a, b, mpd_sign(b), ctx, status);
+ mpd_qfinalize(result, ctx, status);
+}
+
+/* Subtract b from a. */
+void
+mpd_qsub(mpd_t *result, const mpd_t *a, const mpd_t *b,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ if (mpd_isspecial(a) || mpd_isspecial(b)) {
+ if (mpd_qcheck_nans(result, a, b, ctx, status)) {
+ return;
+ }
+ _mpd_qaddsub_inf(result, a, b, !mpd_sign(b), status);
+ return;
+ }
+
+ _mpd_qaddsub(result, a, b, !mpd_sign(b), ctx, status);
+ mpd_qfinalize(result, ctx, status);
+}
+
+/* Add decimal and mpd_ssize_t. */
+void
+mpd_qadd_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ mpd_t bb;
+ mpd_uint_t bdata[2];
+
+ bb.data = bdata;
+ bb.flags = MPD_STATIC|MPD_CONST_DATA;
+
+ mpd_qsset_ssize(&bb, b, ctx, status);
+ mpd_qadd(result, a, &bb, ctx, status);
+}
+
+/* Add decimal and mpd_uint_t. */
+void
+mpd_qadd_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ mpd_t bb;
+ mpd_uint_t bdata[2];
+
+ bb.data = bdata;
+ bb.flags = MPD_STATIC|MPD_CONST_DATA;
+
+ mpd_qsset_uint(&bb, b, ctx, status);
+ mpd_qadd(result, a, &bb, ctx, status);
+}
+
+/* Subtract mpd_ssize_t from decimal. */
+void
+mpd_qsub_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ mpd_t bb;
+ mpd_uint_t bdata[2];
+
+ bb.data = bdata;
+ bb.flags = MPD_STATIC|MPD_CONST_DATA;
+
+ mpd_qsset_ssize(&bb, b, ctx, status);
+ mpd_qsub(result, a, &bb, ctx, status);
+}
+
+/* Subtract mpd_uint_t from decimal. */
+void
+mpd_qsub_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ mpd_t bb;
+ mpd_uint_t bdata[2];
+
+ bb.data = bdata;
+ bb.flags = MPD_STATIC|MPD_CONST_DATA;
+
+ mpd_qsset_uint(&bb, b, ctx, status);
+ mpd_qsub(result, a, &bb, ctx, status);
+}
+
+/* Add decimal and int32_t. */
+void
+mpd_qadd_i32(mpd_t *result, const mpd_t *a, int32_t b, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ mpd_qadd_ssize(result, a, b, ctx, status);
+}
+
+/* Add decimal and uint32_t. */
+void
+mpd_qadd_u32(mpd_t *result, const mpd_t *a, uint32_t b, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ mpd_qadd_uint(result, a, b, ctx, status);
+}
+
+#ifdef CONFIG_64
+/* Add decimal and int64_t. */
+void
+mpd_qadd_i64(mpd_t *result, const mpd_t *a, int64_t b, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ mpd_qadd_ssize(result, a, b, ctx, status);
+}
+
+/* Add decimal and uint64_t. */
+void
+mpd_qadd_u64(mpd_t *result, const mpd_t *a, uint64_t b, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ mpd_qadd_uint(result, a, b, ctx, status);
+}
+#endif
+
+
+/* Divide infinities. */
+static void
+_mpd_qdiv_inf(mpd_t *result, const mpd_t *a, const mpd_t *b,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ if (mpd_isinfinite(a)) {
+ if (mpd_isinfinite(b)) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+ mpd_setspecial(result, mpd_sign(a)^mpd_sign(b), MPD_INF);
+ return;
+ }
+ assert(mpd_isinfinite(b));
+ _settriple(result, mpd_sign(a)^mpd_sign(b), 0, mpd_etiny(ctx));
+ *status |= MPD_Clamped;
+}
+
+enum {NO_IDEAL_EXP, SET_IDEAL_EXP};
+/* Divide a by b. */
+static void
+_mpd_qdiv(int action, mpd_t *q, const mpd_t *a, const mpd_t *b,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ MPD_NEW_STATIC(aligned,0,0,0,0);
+ mpd_uint_t ld, carry = 0;
+ mpd_ssize_t shift, exp, tz;
+ mpd_ssize_t newsize;
+ mpd_ssize_t ideal_exp;
+ mpd_uint_t rem;
+ uint8_t sign_a = mpd_sign(a);
+ uint8_t sign_b = mpd_sign(b);
+
+
+ if (mpd_isspecial(a) || mpd_isspecial(b)) {
+ if (mpd_qcheck_nans(q, a, b, ctx, status)) {
+ return;
+ }
+ _mpd_qdiv_inf(q, a, b, ctx, status);
+ return;
+ }
+ if (mpd_iszerocoeff(b)) {
+ if (mpd_iszerocoeff(a)) {
+ mpd_seterror(q, MPD_Division_undefined, status);
+ }
+ else {
+ mpd_setspecial(q, sign_a^sign_b, MPD_INF);
+ *status |= MPD_Division_by_zero;
+ }
+ return;
+ }
+ if (mpd_iszerocoeff(a)) {
+ exp = a->exp - b->exp;
+ _settriple(q, sign_a^sign_b, 0, exp);
+ mpd_qfinalize(q, ctx, status);
+ return;
+ }
+
+ shift = (b->digits - a->digits) + ctx->prec + 1;
+ ideal_exp = a->exp - b->exp;
+ exp = ideal_exp - shift;
+ if (shift > 0) {
+ if (!mpd_qshiftl(&aligned, a, shift, status)) {
+ mpd_seterror(q, MPD_Malloc_error, status);
+ goto finish;
+ }
+ a = &aligned;
+ }
+ else if (shift < 0) {
+ shift = -shift;
+ if (!mpd_qshiftl(&aligned, b, shift, status)) {
+ mpd_seterror(q, MPD_Malloc_error, status);
+ goto finish;
+ }
+ b = &aligned;
+ }
+
+
+ newsize = a->len - b->len + 1;
+ if ((q != b && q != a) || (q == b && newsize > b->len)) {
+ if (!mpd_qresize(q, newsize, status)) {
+ mpd_seterror(q, MPD_Malloc_error, status);
+ goto finish;
+ }
+ }
+
+
+ if (b->len == 1) {
+ rem = _mpd_shortdiv(q->data, a->data, a->len, b->data[0]);
+ }
+ else if (ctx->prec < MPD_NEWTONDIV_CUTOFF || b->digits < MPD_NEWTONDIV_CUTOFF) {
+ int ret = _mpd_basedivmod(q->data, NULL, a->data, b->data,
+ a->len, b->len);
+ if (ret < 0) {
+ mpd_seterror(q, MPD_Malloc_error, status);
+ goto finish;
+ }
+ rem = ret;
+ }
+ else {
+ MPD_NEW_STATIC(r,0,0,0,0);
+ _mpd_qbarrett_divmod(q, &r, a, b, ctx, status);
+ rem = !mpd_iszerocoeff(&r);
+ mpd_del(&r);
+ newsize = q->len;
+ }
+
+ newsize = _mpd_real_size(q->data, newsize);
+ /* resize to smaller cannot fail */
+ mpd_qresize(q, newsize, status);
+ q->len = newsize;
+ mpd_setdigits(q);
+
+ shift = ideal_exp - exp;
+ if (rem) {
+ ld = mpd_lsd(q->data[0]);
+ if (ld == 0 || ld == 5) {
+ carry = _mpd_baseincr(q->data, q->len);
+ if (carry) {
+ if (!mpd_qresize(q, q->len+1, status)) {
+ mpd_seterror(q, MPD_Malloc_error, status);
+ goto finish;
+ }
+ q->data[q->len] = 1;
+ }
+ }
+ }
+ else if (action == SET_IDEAL_EXP && shift > 0) {
+ tz = mpd_trail_zeros(q);
+ shift = (tz > shift) ? shift : tz;
+ mpd_qshiftr_inplace(q, shift);
+ exp += shift;
+ }
+
+ mpd_set_flags(q, sign_a^sign_b);
+ q->exp = exp;
+
+
+finish:
+ mpd_del(&aligned);
+ mpd_qfinalize(q, ctx, status);
+}
+
+/* Divide a by b. */
+void
+mpd_qdiv(mpd_t *q, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ _mpd_qdiv(SET_IDEAL_EXP, q, a, b, ctx, status);
+}
+
+/* Internal function, used with the actions specified in the enum below. */
+static void
+_mpd_qdivmod(mpd_t *q, mpd_t *r, const mpd_t *a, const mpd_t *b,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ MPD_NEW_STATIC(aligned,0,0,0,0);
+ mpd_ssize_t qsize, rsize;
+ mpd_ssize_t ideal_exp, expdiff, shift;
+ uint8_t sign_a = mpd_sign(a);
+ uint8_t sign_ab = mpd_sign(a)^mpd_sign(b);
+
+
+ ideal_exp = (a->exp > b->exp) ? b->exp : a->exp;
+ if (mpd_iszerocoeff(a)) {
+ if (!mpd_qcopy(r, a, status)) {
+ goto nanresult;
+ }
+ r->exp = ideal_exp;
+ _settriple(q, sign_ab, 0, 0);
+ return;
+ }
+
+ expdiff = mpd_adjexp(a) - mpd_adjexp(b);
+ if (expdiff < 0) {
+ if (a->exp > b->exp) {
+ /* positive and less than b->digits - a->digits */
+ shift = a->exp - b->exp;
+ if (!mpd_qshiftl(r, a, shift, status)) {
+ goto nanresult;
+ }
+ r->exp = ideal_exp;
+ }
+ else {
+ if (!mpd_qcopy(r, a, status)) {
+ goto nanresult;
+ }
+ }
+ _settriple(q, sign_ab, 0, 0);
+ return;
+ }
+ if (expdiff > ctx->prec) {
+ *status |= MPD_Division_impossible;
+ goto nanresult;
+ }
+
+
+ /*
+ * At this point we have:
+ * (1) 0 <= a->exp + a->digits - b->exp - b->digits <= prec
+ * (2) a->exp - b->exp >= b->digits - a->digits
+ * (3) a->exp - b->exp <= prec + b->digits - a->digits
+ */
+ if (a->exp != b->exp) {
+ shift = a->exp - b->exp;
+ if (shift > 0) {
+ /* by (3), after the shift a->digits <= prec + b->digits */
+ if (!mpd_qshiftl(&aligned, a, shift, status)) {
+ goto nanresult;
+ }
+ a = &aligned;
+ }
+ else {
+ shift = -shift;
+ /* by (2), after the shift b->digits <= a->digits */
+ if (!mpd_qshiftl(&aligned, b, shift, status)) {
+ goto nanresult;
+ }
+ b = &aligned;
+ }
+ }
+
+
+ qsize = a->len - b->len + 1;
+ if (!(q == a && qsize < a->len) && !(q == b && qsize < b->len)) {
+ if (!mpd_qresize(q, qsize, status)) {
+ goto nanresult;
+ }
+ }
+
+ rsize = b->len;
+ if (!(r == a && rsize < a->len)) {
+ if (!mpd_qresize(r, rsize, status)) {
+ goto nanresult;
+ }
+ }
+
+ if (b->len == 1) {
+ if (a->len == 1) {
+ _mpd_div_word(&q->data[0], &r->data[0], a->data[0], b->data[0]);
+ }
+ else {
+ r->data[0] = _mpd_shortdiv(q->data, a->data, a->len, b->data[0]);
+ }
+ }
+ else if (ctx->prec < MPD_NEWTONDIV_CUTOFF || b->digits < MPD_NEWTONDIV_CUTOFF) {
+ int ret;
+ ret = _mpd_basedivmod(q->data, r->data, a->data, b->data,
+ a->len, b->len);
+ if (ret == -1) {
+ *status |= MPD_Malloc_error;
+ goto nanresult;
+ }
+ }
+ else {
+ _mpd_qbarrett_divmod(q, r, a, b, ctx, status);
+ if (mpd_isinfinite(q) || q->digits > ctx->prec) {
+ *status |= MPD_Division_impossible;
+ goto nanresult;
+ }
+ qsize = q->len;
+ rsize = r->len;
+ }
+
+ qsize = _mpd_real_size(q->data, qsize);
+ /* resize to smaller cannot fail */
+ mpd_qresize(q, qsize, status);
+ q->len = qsize;
+ mpd_setdigits(q);
+ mpd_set_flags(q, sign_ab);
+ q->exp = 0;
+ if (q->digits > ctx->prec) {
+ *status |= MPD_Division_impossible;
+ goto nanresult;
+ }
+
+ rsize = _mpd_real_size(r->data, rsize);
+ /* resize to smaller cannot fail */
+ mpd_qresize(r, rsize, status);
+ r->len = rsize;
+ mpd_setdigits(r);
+ mpd_set_flags(r, sign_a);
+ r->exp = ideal_exp;
+
+out:
+ mpd_del(&aligned);
+ return;
+
+nanresult:
+ mpd_setspecial(q, MPD_POS, MPD_NAN);
+ mpd_setspecial(r, MPD_POS, MPD_NAN);
+ goto out;
+}
+
+/* Integer division with remainder, special cases have been dealt with. */
+void
+mpd_qdivmod(mpd_t *q, mpd_t *r, const mpd_t *a, const mpd_t *b,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ uint8_t sign = mpd_sign(a)^mpd_sign(b);
+
+ if (mpd_isspecial(a) || mpd_isspecial(b)) {
+ if (mpd_qcheck_nans(q, a, b, ctx, status)) {
+ mpd_qcopy(r, q, status);
+ return;
+ }
+ if (mpd_isinfinite(a)) {
+ if (mpd_isinfinite(b)) {
+ mpd_setspecial(q, MPD_POS, MPD_NAN);
+ }
+ else {
+ mpd_setspecial(q, sign, MPD_INF);
+ }
+ mpd_setspecial(r, MPD_POS, MPD_NAN);
+ *status |= MPD_Invalid_operation;
+ return;
+ }
+ if (mpd_isinfinite(b)) {
+ if (!mpd_qcopy(r, a, status)) {
+ mpd_seterror(q, MPD_Malloc_error, status);
+ return;
+ }
+ mpd_qfinalize(r, ctx, status);
+ _settriple(q, sign, 0, 0);
+ return;
+ }
+ /* debug */
+ abort();
+ }
+ if (mpd_iszerocoeff(b)) {
+ if (mpd_iszerocoeff(a)) {
+ mpd_setspecial(q, MPD_POS, MPD_NAN);
+ mpd_setspecial(r, MPD_POS, MPD_NAN);
+ *status |= MPD_Division_undefined;
+ }
+ else {
+ mpd_setspecial(q, sign, MPD_INF);
+ mpd_setspecial(r, MPD_POS, MPD_NAN);
+ *status |= (MPD_Division_by_zero|MPD_Invalid_operation);
+ }
+ return;
+ }
+
+ _mpd_qdivmod(q, r, a, b, ctx, status);
+ mpd_qfinalize(q, ctx, status);
+ mpd_qfinalize(r, ctx, status);
+}
+
+void
+mpd_qdivint(mpd_t *q, const mpd_t *a, const mpd_t *b,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ MPD_NEW_STATIC(r,0,0,0,0);
+ uint8_t sign = mpd_sign(a)^mpd_sign(b);
+
+ if (mpd_isspecial(a) || mpd_isspecial(b)) {
+ if (mpd_qcheck_nans(q, a, b, ctx, status)) {
+ return;
+ }
+ if (mpd_isinfinite(a) && mpd_isinfinite(b)) {
+ mpd_seterror(q, MPD_Invalid_operation, status);
+ return;
+ }
+ if (mpd_isinfinite(a)) {
+ mpd_setspecial(q, sign, MPD_INF);
+ return;
+ }
+ if (mpd_isinfinite(b)) {
+ _settriple(q, sign, 0, 0);
+ return;
+ }
+ /* debug */
+ abort();
+ }
+ if (mpd_iszerocoeff(b)) {
+ if (mpd_iszerocoeff(a)) {
+ mpd_seterror(q, MPD_Division_undefined, status);
+ }
+ else {
+ mpd_setspecial(q, sign, MPD_INF);
+ *status |= MPD_Division_by_zero;
+ }
+ return;
+ }
+
+
+ _mpd_qdivmod(q, &r, a, b, ctx, status);
+ mpd_del(&r);
+ mpd_qfinalize(q, ctx, status);
+}
+
+/* Divide decimal by mpd_ssize_t. */
+void
+mpd_qdiv_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ mpd_t bb;
+ mpd_uint_t bdata[2];
+
+ bb.data = bdata;
+ bb.flags = MPD_STATIC|MPD_CONST_DATA;
+
+ mpd_qsset_ssize(&bb, b, ctx, status);
+ mpd_qdiv(result, a, &bb, ctx, status);
+}
+
+/* Divide decimal by mpd_uint_t. */
+void
+mpd_qdiv_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ mpd_t bb;
+ mpd_uint_t bdata[2];
+
+ bb.data = bdata;
+ bb.flags = MPD_STATIC|MPD_CONST_DATA;
+
+ mpd_qsset_uint(&bb, b, ctx, status);
+ mpd_qdiv(result, a, &bb, ctx, status);
+}
+
+/* Divide decimal by int32_t. */
+void
+mpd_qdiv_i32(mpd_t *result, const mpd_t *a, int32_t b, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ mpd_qdiv_ssize(result, a, b, ctx, status);
+}
+
+/* Divide decimal by uint32_t. */
+void
+mpd_qdiv_u32(mpd_t *result, const mpd_t *a, uint32_t b, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ mpd_qdiv_uint(result, a, b, ctx, status);
+}
+
+#ifdef CONFIG_64
+/* Divide decimal by int64_t. */
+void
+mpd_qdiv_i64(mpd_t *result, const mpd_t *a, int64_t b, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ mpd_qdiv_ssize(result, a, b, ctx, status);
+}
+
+/* Divide decimal by uint64_t. */
+void
+mpd_qdiv_u64(mpd_t *result, const mpd_t *a, uint64_t b, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ mpd_qdiv_uint(result, a, b, ctx, status);
+}
+#endif
+
+/*
+ * Get the number of iterations for the Horner scheme in _mpd_qexp().
+ */
+static inline mpd_ssize_t
+_mpd_get_exp_iterations(const mpd_t *a, mpd_ssize_t prec)
+{
+ mpd_uint_t dummy;
+ mpd_uint_t msdigits;
+ double f;
+
+ /* 9 is MPD_RDIGITS for 32 bit platforms */
+ _mpd_get_msdigits(&dummy, &msdigits, a, 9);
+ f = ((double)msdigits + 1) / mpd_pow10[mpd_word_digits(msdigits)];
+
+#ifdef CONFIG_64
+ #if defined(__x86_64__) && defined(HAVE_80BIT_LONG_DOUBLE)
+ return ceill((1.435*(long double)prec - 1.182) / log10l((long double)prec/f));
+ #else
+ /* prec > floor((1ULL<<53) / 1.435) */
+ if (prec > 6276793905742851LL) {
+ return MPD_SSIZE_MAX;
+ }
+ return ceil((1.435*(double)prec - 1.182) / log10((double)prec/f));
+ #endif
+#else /* CONFIG_32 */
+ return ceil((1.435*(double)prec - 1.182) / log10((double)prec/f));
+#endif
+}
+
+/*
+ * Internal function, specials have been dealt with.
+ *
+ * The algorithm is from Hull&Abrham, Variable Precision Exponential Function,
+ * ACM Transactions on Mathematical Software, Vol. 12, No. 2, June 1986.
+ *
+ * Main differences:
+ *
+ * - The number of iterations for the Horner scheme is calculated using the
+ * C log10() function.
+ *
+ * - The analysis for early abortion has been adapted for the mpd_t
+ * ranges.
+ */
+static void
+_mpd_qexp(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_context_t workctx;
+ MPD_NEW_STATIC(tmp,0,0,0,0);
+ MPD_NEW_STATIC(sum,0,0,0,0);
+ MPD_NEW_CONST(word,0,0,0,1,1,1);
+ mpd_ssize_t j, n, t;
+
+ /*
+ * We are calculating e^x = e^(r*10^t) = (e^r)^(10^t), where r < 1 and t >= 0.
+ *
+ * If t > 0, we have:
+ *
+ * (1) 0.1 <= r < 1, so e^r >= e^0.1. Overflow in the final power operation
+ * will occur when (e^0.1)^(10^t) > 10^(emax+1). If we consider MAX_EMAX,
+ * this will happen for t > 10 (32 bit) or (t > 19) (64 bit).
+ *
+ * (2) -1 < r <= -0.1, so e^r > e^-1. Underflow in the final power operation
+ * will occur when (e^-1)^(10^t) < 10^(etiny-1). If we consider MIN_ETINY,
+ * this will also happen for t > 10 (32 bit) or (t > 19) (64 bit).
+ */
+#ifdef CONFIG_32
+ #define MPD_EXP_MAX_T 10
+#elif defined(CONFIG_64)
+ #define MPD_EXP_MAX_T 19
+#endif
+ t = a->digits + a->exp;
+ t = (t > 0) ? t : 0;
+ if (t > MPD_EXP_MAX_T) {
+ if (mpd_ispositive(a)) {
+ mpd_setspecial(result, MPD_POS, MPD_INF);
+ *status |= MPD_Overflow|MPD_Inexact|MPD_Rounded;
+ }
+ else {
+ _settriple(result, MPD_POS, 0, mpd_etiny(ctx));
+ *status |= (MPD_Inexact|MPD_Rounded|MPD_Subnormal|MPD_Underflow|MPD_Clamped);
+ }
+ return;
+ }
+
+ mpd_maxcontext(&workctx);
+ workctx.round = MPD_ROUND_HALF_EVEN;
+ workctx.prec = (ctx->prec > a->digits ? ctx->prec : a->digits) + t + 2;
+ workctx.prec = (workctx.prec < 9) ? 9 : workctx.prec;
+
+ if ((n = _mpd_get_exp_iterations(a, workctx.prec)) == MPD_SSIZE_MAX) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ goto finish;
+ }
+
+ if (!mpd_qcopy(result, a, status)) {
+ goto finish;
+ }
+ result->exp -= t;
+
+ _settriple(&sum, MPD_POS, 1, 0);
+
+ for (j = n-1; j >= 1; j--) {
+ word.data[0] = j;
+ mpd_setdigits(&word);
+ mpd_qdiv(&tmp, result, &word, &workctx, &workctx.status);
+ mpd_qmul(&sum, &sum, &tmp, &workctx, &workctx.status);
+ mpd_qadd(&sum, &sum, &one, &workctx, &workctx.status);
+ }
+
+ if (t <= MPD_MAX_POW10) {
+ _mpd_qpow_uint(result, &sum, mpd_pow10[t], MPD_POS, &workctx, status);
+ }
+ else {
+ t -= MPD_MAX_POW10;
+ _mpd_qpow_uint(&tmp, &sum, mpd_pow10[MPD_MAX_POW10], MPD_POS, &workctx, status);
+ _mpd_qpow_uint(result, &tmp, mpd_pow10[t], MPD_POS, &workctx, status);
+ }
+
+
+finish:
+ mpd_del(&tmp);
+ mpd_del(&sum);
+ *status |= (workctx.status&MPD_Errors);
+ *status |= (MPD_Inexact|MPD_Rounded);
+}
+
+/* exp(a) */
+void
+mpd_qexp(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_context_t workctx;
+
+ if (mpd_isspecial(a)) {
+ if (mpd_qcheck_nan(result, a, ctx, status)) {
+ return;
+ }
+ if (mpd_isnegative(a)) {
+ _settriple(result, MPD_POS, 0, 0);
+ }
+ else {
+ mpd_setspecial(result, MPD_POS, MPD_INF);
+ }
+ return;
+ }
+ if (mpd_iszerocoeff(a)) {
+ _settriple(result, MPD_POS, 1, 0);
+ return;
+ }
+
+ workctx = *ctx;
+ workctx.round = MPD_ROUND_HALF_EVEN;
+
+ if (ctx->allcr) {
+ MPD_NEW_STATIC(t1, 0,0,0,0);
+ MPD_NEW_STATIC(t2, 0,0,0,0);
+ MPD_NEW_STATIC(ulp, 0,0,0,0);
+ MPD_NEW_STATIC(aa, 0,0,0,0);
+ mpd_ssize_t prec;
+
+ if (result == a) {
+ mpd_qcopy(&aa, a, status);
+ a = &aa;
+ }
+
+ prec = ctx->prec + 3;
+ while (1) {
+ workctx.prec = prec;
+ _mpd_qexp(result, a, &workctx, status);
+ _ssettriple(&ulp, MPD_POS, 1, result->exp + result->digits-workctx.prec-1);
+
+ workctx.prec = ctx->prec;
+ mpd_qadd(&t1, result, &ulp, &workctx, status);
+ mpd_qsub(&t2, result, &ulp, &workctx, status);
+ if (mpd_isspecial(result) || mpd_iszerocoeff(result) ||
+ mpd_qcmp(&t1, &t2, status) == 0) {
+ mpd_qfinalize(result, &workctx, status);
+ break;
+ }
+ prec += MPD_RDIGITS;
+ }
+ mpd_del(&t1);
+ mpd_del(&t2);
+ mpd_del(&ulp);
+ mpd_del(&aa);
+ }
+ else {
+ _mpd_qexp(result, a, &workctx, status);
+ mpd_qfinalize(result, &workctx, status);
+ }
+}
+
+/* Fused multiply-add: (a * b) + c, with a single final rounding. */
+void
+mpd_qfma(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_t *c,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ uint32_t workstatus = 0;
+ mpd_t *cc = (mpd_t *)c;
+
+ if (result == c) {
+ if ((cc = mpd_qncopy(c)) == NULL) {
+ mpd_seterror(result, MPD_Malloc_error, status);
+ return;
+ }
+ }
+
+ _mpd_qmul(result, a, b, ctx, &workstatus);
+ if (!(workstatus&MPD_Invalid_operation)) {
+ mpd_qadd(result, result, cc, ctx, &workstatus);
+ }
+
+ if (cc != c) mpd_del(cc);
+ *status |= workstatus;
+}
+
+static inline int
+ln_schedule_prec(mpd_ssize_t klist[MPD_MAX_PREC_LOG2], mpd_ssize_t maxprec, mpd_ssize_t initprec)
+{
+ mpd_ssize_t k;
+ int i;
+
+ assert(maxprec >= 2 && initprec >= 2);
+ if (maxprec <= initprec) return -1;
+
+ i = 0; k = maxprec;
+ do {
+ k = (k+2) / 2;
+ klist[i++] = k;
+ } while (k > initprec);
+
+ return i-1;
+}
+
+/* Two word initial approximations for ln(10) */
+#ifdef CONFIG_64
+#if MPD_RDIGITS != 19
+ #error "mpdecimal.c: MPD_RDIGITS must be 19."
+#endif
+static mpd_uint_t mpd_ln10data[MPD_MINALLOC_MAX] = {179914546843642076, 2302585092994045684};
+#else
+#if MPD_RDIGITS != 9
+ #error "mpdecimal.c: MPD_RDIGITS must be 9."
+#endif
+static mpd_uint_t mpd_ln10data[MPD_MINALLOC_MAX] = {299404568, 230258509};
+#endif
+/* mpd_ln10 is cached in order to speed up computations */
+mpd_t mpd_ln10 = {MPD_STATIC|MPD_STATIC_DATA, -(2*MPD_RDIGITS-1),
+ 2*MPD_RDIGITS, 2, MPD_MINALLOC_MAX, mpd_ln10data};
+
+/*
+ * Initializes or updates mpd_ln10. If mpd_ln10 is cached and has exactly the
+ * requested precision, the function returns. If the cached precision is greater
+ * than the requested precision, mpd_ln10 is shifted to the requested precision.
+ *
+ * The function can fail with MPD_Malloc_error.
+ */
+void
+mpd_update_ln10(mpd_ssize_t maxprec, uint32_t *status)
+{
+ mpd_context_t varcontext, maxcontext;
+ MPD_NEW_STATIC(tmp, 0,0,0,0);
+ MPD_NEW_CONST(static10, 0,0,2,1,1,10);
+ mpd_ssize_t klist[MPD_MAX_PREC_LOG2];
+ int i;
+
+ if (mpd_ln10.digits > maxprec) {
+ /* shift to smaller cannot fail */
+ mpd_qshiftr_inplace(&mpd_ln10, mpd_ln10.digits-maxprec);
+ mpd_ln10.exp = -(mpd_ln10.digits-1);
+ return;
+ }
+ else if (mpd_ln10.digits == maxprec) {
+ return;
+ }
+
+ mpd_maxcontext(&maxcontext);
+ mpd_maxcontext(&varcontext);
+ varcontext.round = MPD_ROUND_TRUNC;
+
+ i = ln_schedule_prec(klist, maxprec+2, mpd_ln10.digits);
+ for (; i >= 0; i--) {
+ varcontext.prec = 2*klist[i]+3;
+ mpd_ln10.flags ^= MPD_NEG;
+ _mpd_qexp(&tmp, &mpd_ln10, &varcontext, status);
+ mpd_ln10.flags ^= MPD_NEG;
+ mpd_qmul(&tmp, &static10, &tmp, &varcontext, status);
+ mpd_qsub(&tmp, &tmp, &one, &maxcontext, status);
+ mpd_qadd(&mpd_ln10, &mpd_ln10, &tmp, &maxcontext, status);
+ }
+
+ mpd_del(&tmp);
+ varcontext.prec = maxprec;
+ varcontext.round = MPD_ROUND_HALF_EVEN;
+ mpd_qfinalize(&mpd_ln10, &varcontext, status);
+}
+
+/* Initial approximations for the ln() iteration */
+static const uint16_t lnapprox[900] = {
+ /* index 0 - 400: log((i+100)/100) * 1000 */
+ 0, 10, 20, 30, 39, 49, 58, 68, 77, 86, 95, 104, 113, 122, 131, 140, 148, 157,
+ 166, 174, 182, 191, 199, 207, 215, 223, 231, 239, 247, 255, 262, 270, 278,
+ 285, 293, 300, 308, 315, 322, 329, 336, 344, 351, 358, 365, 372, 378, 385,
+ 392, 399, 406, 412, 419, 425, 432, 438, 445, 451, 457, 464, 470, 476, 482,
+ 489, 495, 501, 507, 513, 519, 525, 531, 536, 542, 548, 554, 560, 565, 571,
+ 577, 582, 588, 593, 599, 604, 610, 615, 621, 626, 631, 637, 642, 647, 652,
+ 658, 663, 668, 673, 678, 683, 688, 693, 698, 703, 708, 713, 718, 723, 728,
+ 732, 737, 742, 747, 751, 756, 761, 766, 770, 775, 779, 784, 788, 793, 798,
+ 802, 806, 811, 815, 820, 824, 829, 833, 837, 842, 846, 850, 854, 859, 863,
+ 867, 871, 876, 880, 884, 888, 892, 896, 900, 904, 908, 912, 916, 920, 924,
+ 928, 932, 936, 940, 944, 948, 952, 956, 959, 963, 967, 971, 975, 978, 982,
+ 986, 990, 993, 997, 1001, 1004, 1008, 1012, 1015, 1019, 1022, 1026, 1030,
+ 1033, 1037, 1040, 1044, 1047, 1051, 1054, 1058, 1061, 1065, 1068, 1072, 1075,
+ 1078, 1082, 1085, 1089, 1092, 1095, 1099, 1102, 1105, 1109, 1112, 1115, 1118,
+ 1122, 1125, 1128, 1131, 1135, 1138, 1141, 1144, 1147, 1151, 1154, 1157, 1160,
+ 1163, 1166, 1169, 1172, 1176, 1179, 1182, 1185, 1188, 1191, 1194, 1197, 1200,
+ 1203, 1206, 1209, 1212, 1215, 1218, 1221, 1224, 1227, 1230, 1233, 1235, 1238,
+ 1241, 1244, 1247, 1250, 1253, 1256, 1258, 1261, 1264, 1267, 1270, 1273, 1275,
+ 1278, 1281, 1284, 1286, 1289, 1292, 1295, 1297, 1300, 1303, 1306, 1308, 1311,
+ 1314, 1316, 1319, 1322, 1324, 1327, 1330, 1332, 1335, 1338, 1340, 1343, 1345,
+ 1348, 1351, 1353, 1356, 1358, 1361, 1364, 1366, 1369, 1371, 1374, 1376, 1379,
+ 1381, 1384, 1386, 1389, 1391, 1394, 1396, 1399, 1401, 1404, 1406, 1409, 1411,
+ 1413, 1416, 1418, 1421, 1423, 1426, 1428, 1430, 1433, 1435, 1437, 1440, 1442,
+ 1445, 1447, 1449, 1452, 1454, 1456, 1459, 1461, 1463, 1466, 1468, 1470, 1472,
+ 1475, 1477, 1479, 1482, 1484, 1486, 1488, 1491, 1493, 1495, 1497, 1500, 1502,
+ 1504, 1506, 1509, 1511, 1513, 1515, 1517, 1520, 1522, 1524, 1526, 1528, 1530,
+ 1533, 1535, 1537, 1539, 1541, 1543, 1545, 1548, 1550, 1552, 1554, 1556, 1558,
+ 1560, 1562, 1564, 1567, 1569, 1571, 1573, 1575, 1577, 1579, 1581, 1583, 1585,
+ 1587, 1589, 1591, 1593, 1595, 1597, 1599, 1601, 1603, 1605, 1607, 1609,
+ /* index 401 - 899: -log((i+100)/1000) * 1000 */
+ 691, 689, 687, 685, 683, 681, 679, 677, 675, 673, 671, 669, 668, 666, 664,
+ 662, 660, 658, 656, 654, 652, 650, 648, 646, 644, 642, 641, 639, 637, 635,
+ 633, 631, 629, 627, 626, 624, 622, 620, 618, 616, 614, 612, 611, 609, 607,
+ 605, 603, 602, 600, 598, 596, 594, 592, 591, 589, 587, 585, 583, 582, 580,
+ 578, 576, 574, 573, 571, 569, 567, 566, 564, 562, 560, 559, 557, 555, 553,
+ 552, 550, 548, 546, 545, 543, 541, 540, 538, 536, 534, 533, 531, 529, 528,
+ 526, 524, 523, 521, 519, 518, 516, 514, 512, 511, 509, 508, 506, 504, 502,
+ 501, 499, 498, 496, 494, 493, 491, 489, 488, 486, 484, 483, 481, 480, 478,
+ 476, 475, 473, 472, 470, 468, 467, 465, 464, 462, 460, 459, 457, 456, 454,
+ 453, 451, 449, 448, 446, 445, 443, 442, 440, 438, 437, 435, 434, 432, 431,
+ 429, 428, 426, 425, 423, 422, 420, 419, 417, 416, 414, 412, 411, 410, 408,
+ 406, 405, 404, 402, 400, 399, 398, 396, 394, 393, 392, 390, 389, 387, 386,
+ 384, 383, 381, 380, 378, 377, 375, 374, 372, 371, 370, 368, 367, 365, 364,
+ 362, 361, 360, 358, 357, 355, 354, 352, 351, 350, 348, 347, 345, 344, 342,
+ 341, 340, 338, 337, 336, 334, 333, 331, 330, 328, 327, 326, 324, 323, 322,
+ 320, 319, 318, 316, 315, 313, 312, 311, 309, 308, 306, 305, 304, 302, 301,
+ 300, 298, 297, 296, 294, 293, 292, 290, 289, 288, 286, 285, 284, 282, 281,
+ 280, 278, 277, 276, 274, 273, 272, 270, 269, 268, 267, 265, 264, 263, 261,
+ 260, 259, 258, 256, 255, 254, 252, 251, 250, 248, 247, 246, 245, 243, 242,
+ 241, 240, 238, 237, 236, 234, 233, 232, 231, 229, 228, 227, 226, 224, 223,
+ 222, 221, 219, 218, 217, 216, 214, 213, 212, 211, 210, 208, 207, 206, 205,
+ 203, 202, 201, 200, 198, 197, 196, 195, 194, 192, 191, 190, 189, 188, 186,
+ 185, 184, 183, 182, 180, 179, 178, 177, 176, 174, 173, 172, 171, 170, 168,
+ 167, 166, 165, 164, 162, 161, 160, 159, 158, 157, 156, 154, 153, 152, 151,
+ 150, 148, 147, 146, 145, 144, 143, 142, 140, 139, 138, 137, 136, 135, 134,
+ 132, 131, 130, 129, 128, 127, 126, 124, 123, 122, 121, 120, 119, 118, 116,
+ 115, 114, 113, 112, 111, 110, 109, 108, 106, 105, 104, 103, 102, 101, 100,
+ 99, 98, 97, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 84, 83, 82, 81, 80, 79,
+ 78, 77, 76, 75, 74, 73, 72, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59,
+ 58, 57, 56, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39,
+ 38, 37, 36, 35, 34, 33, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19,
+ 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
+};
+
+/* Internal ln() function that does not check for specials or zero. */
+static void
+_mpd_qln(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_context_t varcontext, maxcontext;
+ mpd_t *z = (mpd_t *) result;
+ MPD_NEW_STATIC(v,0,0,0,0);
+ MPD_NEW_STATIC(vtmp,0,0,0,0);
+ MPD_NEW_STATIC(tmp,0,0,0,0);
+ mpd_ssize_t klist[MPD_MAX_PREC_LOG2];
+ mpd_ssize_t maxprec, shift, t;
+ mpd_ssize_t a_digits, a_exp;
+ mpd_uint_t dummy, x;
+ int i;
+
+ if (_mpd_cmp(a, &one) == 0) {
+ _settriple(result, MPD_POS, 0, 0);
+ return;
+ }
+
+ /*
+ * We are calculating ln(a) = ln(v * 10^t) = ln(v) + t*ln(10),
+ * where 0.5 < v <= 5.
+ */
+ if (!mpd_qcopy(&v, a, status)) {
+ mpd_seterror(result, MPD_Malloc_error, status);
+ goto finish;
+ }
+
+ /* Initial approximation: we have at least one non-zero digit */
+ _mpd_get_msdigits(&dummy, &x, &v, 3);
+ if (x < 10) x *= 10;
+ if (x < 100) x *= 10;
+ x -= 100;
+
+ /* a may equal z */
+ a_digits = a->digits;
+ a_exp = a->exp;
+
+ mpd_minalloc(z);
+ mpd_clear_flags(z);
+ z->data[0] = lnapprox[x];
+ z->len = 1;
+ z->exp = -3;
+ mpd_setdigits(z);
+
+ if (x <= 400) {
+ v.exp = -(a_digits - 1);
+ t = a_exp + a_digits - 1;
+ }
+ else {
+ v.exp = -a_digits;
+ t = a_exp + a_digits;
+ mpd_set_negative(z);
+ }
+
+
+ mpd_maxcontext(&maxcontext);
+ mpd_maxcontext(&varcontext);
+ varcontext.round = MPD_ROUND_TRUNC;
+
+ maxprec = (a->digits > ctx->prec) ? a->digits : ctx->prec;
+ maxprec += 2;
+ if (x <= 10 || x >= 805) {
+ /* v is close to 1: We estimate the magnitude of
+ * the logarithm and adjust the precision upwards.
+ * x/10 < x/(1+x) < ln(1+x), for 0 < x < 1
+ * ln(1+x) < x, for -1 < x < 0
+ */
+ mpd_qsub(&tmp, &one, &v, &varcontext, &varcontext.status);
+ maxprec -= (tmp.exp < 0) ? tmp.exp : 0;
+ maxprec++;
+ }
+
+ i = ln_schedule_prec(klist, maxprec, 2);
+ for (; i >= 0; i--) {
+ varcontext.prec = 2*klist[i]+3;
+ z->flags ^= MPD_NEG;
+ _mpd_qexp(&tmp, z, &varcontext, status);
+ z->flags ^= MPD_NEG;
+
+ if (v.digits > varcontext.prec) {
+ shift = v.digits - varcontext.prec;
+ mpd_qshiftr(&vtmp, &v, shift, status);
+ vtmp.exp += shift;
+ mpd_qmul(&tmp, &vtmp, &tmp, &varcontext, status);
+ }
+ else {
+ mpd_qmul(&tmp, &v, &tmp, &varcontext, status);
+ }
+
+ mpd_qsub(&tmp, &tmp, &one, &maxcontext, status);
+ mpd_qadd(z, z, &tmp, &maxcontext, status);
+ }
+
+ mpd_update_ln10(maxprec+2, status);
+ mpd_qmul_ssize(&tmp, &mpd_ln10, t, &maxcontext, status);
+ mpd_qadd(result, &tmp, z, &maxcontext, status);
+
+
+finish:
+ mpd_del(&v);
+ mpd_del(&vtmp);
+ mpd_del(&tmp);
+}
+
+/* ln(a) */
+void
+mpd_qln(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_context_t workctx;
+
+ if (mpd_isspecial(a)) {
+ if (mpd_qcheck_nan(result, a, ctx, status)) {
+ return;
+ }
+ if (mpd_isnegative(a)) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+ mpd_setspecial(result, MPD_POS, MPD_INF);
+ return;
+ }
+ if (mpd_iszerocoeff(a)) {
+ mpd_setspecial(result, MPD_NEG, MPD_INF);
+ return;
+ }
+ if (mpd_isnegative(a)) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+
+ workctx = *ctx;
+ workctx.round = MPD_ROUND_HALF_EVEN;
+
+ if (ctx->allcr) {
+ MPD_NEW_STATIC(t1, 0,0,0,0);
+ MPD_NEW_STATIC(t2, 0,0,0,0);
+ MPD_NEW_STATIC(ulp, 0,0,0,0);
+ MPD_NEW_STATIC(aa, 0,0,0,0);
+ mpd_ssize_t prec;
+
+ if (result == a) {
+ mpd_qcopy(&aa, a, status);
+ a = &aa;
+ }
+
+ prec = ctx->prec + 3;
+ while (1) {
+ workctx.prec = prec;
+ _mpd_qln(result, a, &workctx, status);
+ _ssettriple(&ulp, MPD_POS, 1, result->exp + result->digits-workctx.prec-1);
+
+ workctx.prec = ctx->prec;
+ mpd_qadd(&t1, result, &ulp, &workctx, status);
+ mpd_qsub(&t2, result, &ulp, &workctx, status);
+ if (mpd_isspecial(result) || mpd_iszerocoeff(result) ||
+ mpd_qcmp(&t1, &t2, status) == 0) {
+ mpd_qfinalize(result, &workctx, status);
+ break;
+ }
+ prec += MPD_RDIGITS;
+ }
+ mpd_del(&t1);
+ mpd_del(&t2);
+ mpd_del(&ulp);
+ mpd_del(&aa);
+ }
+ else {
+ _mpd_qln(result, a, &workctx, status);
+ mpd_qfinalize(result, &workctx, status);
+ }
+}
+
+/* Internal log10() function that does not check for specials, zero, ... */
+static void
+_mpd_qlog10(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_context_t workctx;
+
+ mpd_maxcontext(&workctx);
+ workctx.prec = ctx->prec + a->digits + 3;
+ _mpd_qln(result, a, &workctx, status);
+ mpd_update_ln10(ctx->prec + 3, status);
+
+ workctx = *ctx;
+ workctx.round = MPD_ROUND_HALF_EVEN;
+ mpd_qdiv(result, result, &mpd_ln10, &workctx, status);
+}
+
+/* log10(a) */
+void
+mpd_qlog10(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_context_t workctx;
+
+ workctx = *ctx;
+ workctx.round = MPD_ROUND_HALF_EVEN;
+
+ if (mpd_isspecial(a)) {
+ if (mpd_qcheck_nan(result, a, ctx, status)) {
+ return;
+ }
+ if (mpd_isnegative(a)) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+ mpd_setspecial(result, MPD_POS, MPD_INF);
+ return;
+ }
+ if (mpd_iszerocoeff(a)) {
+ mpd_setspecial(result, MPD_NEG, MPD_INF);
+ return;
+ }
+ if (mpd_isnegative(a)) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+ if (mpd_coeff_ispow10(a)) {
+ uint8_t sign = 0;
+ mpd_ssize_t adjexp = mpd_adjexp(a);
+ if (adjexp < 0) {
+ sign = 1;
+ adjexp = -adjexp;
+ }
+ _settriple(result, sign, adjexp, 0);
+ mpd_qfinalize(result, &workctx, status);
+ return;
+ }
+
+ if (ctx->allcr) {
+ MPD_NEW_STATIC(t1, 0,0,0,0);
+ MPD_NEW_STATIC(t2, 0,0,0,0);
+ MPD_NEW_STATIC(ulp, 0,0,0,0);
+ MPD_NEW_STATIC(aa, 0,0,0,0);
+ mpd_ssize_t prec;
+
+ if (result == a) {
+ mpd_qcopy(&aa, a, status);
+ a = &aa;
+ }
+
+ prec = ctx->prec + 3;
+ while (1) {
+ workctx.prec = prec;
+ _mpd_qlog10(result, a, &workctx, status);
+ _ssettriple(&ulp, MPD_POS, 1, result->exp + result->digits-workctx.prec-1);
+
+ workctx.prec = ctx->prec;
+ mpd_qadd(&t1, result, &ulp, &workctx, status);
+ mpd_qsub(&t2, result, &ulp, &workctx, status);
+ if (mpd_isspecial(result) || mpd_iszerocoeff(result) ||
+ mpd_qcmp(&t1, &t2, status) == 0) {
+ mpd_qfinalize(result, &workctx, status);
+ break;
+ }
+ prec += MPD_RDIGITS;
+ }
+ mpd_del(&t1);
+ mpd_del(&t2);
+ mpd_del(&ulp);
+ mpd_del(&aa);
+ }
+ else {
+ _mpd_qlog10(result, a, &workctx, status);
+ }
+}
+
+/*
+ * Maximum of the two operands. Attention: If one operand is a quiet NaN and the
+ * other is numeric, the numeric operand is returned. This may not be what one
+ * expects.
+ */
+void
+mpd_qmax(mpd_t *result, const mpd_t *a, const mpd_t *b,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ int c;
+
+ if (mpd_isqnan(a) && !mpd_isnan(b)) {
+ mpd_qcopy(result, b, status);
+ }
+ else if (mpd_isqnan(b) && !mpd_isnan(a)) {
+ mpd_qcopy(result, a, status);
+ }
+ else if (mpd_qcheck_nans(result, a, b, ctx, status)) {
+ return;
+ }
+ else {
+ c = _mpd_cmp(a, b);
+ if (c == 0) {
+ c = _mpd_cmp_numequal(a, b);
+ }
+
+ if (c < 0) {
+ mpd_qcopy(result, b, status);
+ }
+ else {
+ mpd_qcopy(result, a, status);
+ }
+ }
+
+ mpd_qfinalize(result, ctx, status);
+}
+
+/*
+ * Maximum magnitude: Same as mpd_max(), but compares the operands with their
+ * sign ignored.
+ */
+void
+mpd_qmax_mag(mpd_t *result, const mpd_t *a, const mpd_t *b,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ int c;
+
+ if (mpd_isqnan(a) && !mpd_isnan(b)) {
+ mpd_qcopy(result, b, status);
+ }
+ else if (mpd_isqnan(b) && !mpd_isnan(a)) {
+ mpd_qcopy(result, a, status);
+ }
+ else if (mpd_qcheck_nans(result, a, b, ctx, status)) {
+ return;
+ }
+ else {
+ c = _mpd_cmp_abs(a, b);
+ if (c == 0) {
+ c = _mpd_cmp_numequal(a, b);
+ }
+
+ if (c < 0) {
+ mpd_qcopy(result, b, status);
+ }
+ else {
+ mpd_qcopy(result, a, status);
+ }
+ }
+
+ mpd_qfinalize(result, ctx, status);
+}
+
+/*
+ * Minimum of the two operands. Attention: If one operand is a quiet NaN and the
+ * other is numeric, the numeric operand is returned. This may not be what one
+ * expects.
+ */
+void
+mpd_qmin(mpd_t *result, const mpd_t *a, const mpd_t *b,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ int c;
+
+ if (mpd_isqnan(a) && !mpd_isnan(b)) {
+ mpd_qcopy(result, b, status);
+ }
+ else if (mpd_isqnan(b) && !mpd_isnan(a)) {
+ mpd_qcopy(result, a, status);
+ }
+ else if (mpd_qcheck_nans(result, a, b, ctx, status)) {
+ return;
+ }
+ else {
+ c = _mpd_cmp(a, b);
+ if (c == 0) {
+ c = _mpd_cmp_numequal(a, b);
+ }
+
+ if (c < 0) {
+ mpd_qcopy(result, a, status);
+ }
+ else {
+ mpd_qcopy(result, b, status);
+ }
+ }
+
+ mpd_qfinalize(result, ctx, status);
+}
+
+/*
+ * Minimum magnitude: Same as mpd_min(), but compares the operands with their
+ * sign ignored.
+ */
+void
+mpd_qmin_mag(mpd_t *result, const mpd_t *a, const mpd_t *b,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ int c;
+
+ if (mpd_isqnan(a) && !mpd_isnan(b)) {
+ mpd_qcopy(result, b, status);
+ }
+ else if (mpd_isqnan(b) && !mpd_isnan(a)) {
+ mpd_qcopy(result, a, status);
+ }
+ else if (mpd_qcheck_nans(result, a, b, ctx, status)) {
+ return;
+ }
+ else {
+ c = _mpd_cmp_abs(a, b);
+ if (c == 0) {
+ c = _mpd_cmp_numequal(a, b);
+ }
+
+ if (c < 0) {
+ mpd_qcopy(result, a, status);
+ }
+ else {
+ mpd_qcopy(result, b, status);
+ }
+ }
+
+ mpd_qfinalize(result, ctx, status);
+}
+
+/* Minimum space needed for the result array in _karatsuba_rec(). */
+static inline size_t
+_kmul_resultsize(size_t la, size_t lb)
+{
+ size_t n, m;
+
+ n = add_size_t(la, lb);
+ n = add_size_t(n, 1);
+
+ m = (la+1)/2 + 1;
+ m = mul_size_t(m, 3);
+
+ return (m > n) ? m : n;
+}
+
+/* Work space needed in _karatsuba_rec(). lim >= 4 */
+static inline size_t
+_kmul_worksize(size_t n, size_t lim)
+{
+ size_t m;
+
+ if (n <= lim) {
+ return 0;
+ }
+
+ m = (n+1)/2 + 1;
+
+ return add_size_t(mul_size_t(m, 2), _kmul_worksize(m, lim));
+}
+
+
+#define MPD_KARATSUBA_BASECASE 16 /* must be >= 4 */
+
+/*
+ * Add the product of a and b to c.
+ * c must be _kmul_resultsize(la, lb) in size.
+ * w is used as a work array and must be _kmul_worksize(a, lim) in size.
+ * Roman E. Maeder, Storage Allocation for the Karatsuba Integer Multiplication
+ * Algorithm. In "Design and implementation of symbolic computation systems",
+ * Springer, 1993, ISBN 354057235X, 9783540572350.
+ */
+static void
+_karatsuba_rec(mpd_uint_t *c, const mpd_uint_t *a, const mpd_uint_t *b, mpd_uint_t *w,
+ size_t la, size_t lb)
+{
+ size_t m, lt;
+
+ assert (la >= lb && lb > 0);
+
+ if (la <= MPD_KARATSUBA_BASECASE) {
+ _mpd_basemul(c, a, b, la, lb);
+ return;
+ }
+
+ m = (la+1)/2; // ceil(la/2)
+
+ /* lb <= m < la */
+ if (lb <= m) {
+
+ /* lb can now be larger than la-m */
+ if (lb > la-m) {
+ lt = lb + lb + 1; // space needed for result array
+ mpd_uint_zero(w, lt); // clear result array
+ _karatsuba_rec(w, b, a+m, w+lt, lb, la-m); // b*ah
+ }
+ else {
+ lt = (la-m) + (la-m) + 1; // space needed for result array
+ mpd_uint_zero(w, lt); // clear result array
+ _karatsuba_rec(w, a+m, b, w+lt, la-m, lb); // ah*b
+ }
+ _mpd_baseaddto(c+m, w, (la-m)+lb); // add ah*b*B**m
+
+ lt = m + m + 1; // space needed for the result array
+ mpd_uint_zero(w, lt); // clear result array
+ _karatsuba_rec(w, a, b, w+lt, m, lb); // al*b
+ _mpd_baseaddto(c, w, m+lb); // add al*b
+
+ return;
+ }
+
+ /* la >= lb > m */
+ memcpy(w, a, m * sizeof *w);
+ w[m] = 0;
+ _mpd_baseaddto(w, a+m, la-m);
+
+ memcpy(w+(m+1), b, m * sizeof *w);
+ w[m+1+m] = 0;
+ _mpd_baseaddto(w+(m+1), b+m, lb-m);
+
+ _karatsuba_rec(c+m, w, w+(m+1), w+2*(m+1), m+1, m+1);
+
+ lt = (la-m) + (la-m) + 1;
+ mpd_uint_zero(w, lt);
+
+ _karatsuba_rec(w, a+m, b+m, w+lt, la-m, lb-m);
+
+ _mpd_baseaddto(c+2*m, w, (la-m) + (lb-m));
+ _mpd_basesubfrom(c+m, w, (la-m) + (lb-m));
+
+ lt = m + m + 1;
+ mpd_uint_zero(w, lt);
+
+ _karatsuba_rec(w, a, b, w+lt, m, m);
+ _mpd_baseaddto(c, w, m+m);
+ _mpd_basesubfrom(c+m, w, m+m);
+
+ return;
+}
+
+/*
+ * Multiply u and v, using Karatsuba multiplication. Returns a pointer
+ * to the result or NULL in case of failure (malloc error).
+ * Conditions: ulen >= vlen, ulen >= 4
+ */
+mpd_uint_t *
+_mpd_kmul(const mpd_uint_t *u, const mpd_uint_t *v, size_t ulen, size_t vlen, size_t *rsize)
+{
+ mpd_uint_t *result = NULL, *w = NULL;
+ size_t m;
+
+ assert(ulen >= 4);
+ assert(ulen >= vlen);
+
+ *rsize = _kmul_resultsize(ulen, vlen);
+ if ((result = mpd_calloc(*rsize, sizeof *result)) == NULL) {
+ return NULL;
+ }
+
+ m = _kmul_worksize(ulen, MPD_KARATSUBA_BASECASE);
+ if (m && ((w = mpd_calloc(m, sizeof *w)) == NULL)) {
+ mpd_free(result);
+ return NULL;
+ }
+
+ _karatsuba_rec(result, u, v, w, ulen, vlen);
+
+
+ if (w) mpd_free(w);
+ return result;
+}
+
+
+/* Determine the minimum length for the number theoretic transform. */
+static inline size_t
+_mpd_get_transform_len(size_t rsize)
+{
+ size_t log2rsize;
+ size_t x, step;
+
+ assert(rsize >= 4);
+ log2rsize = BSR(rsize);
+
+ if (rsize <= 1024) {
+ x = ONE_UM<<log2rsize;
+ return (rsize == x) ? x : x<<1;
+ }
+ else if (rsize <= MPD_MAXTRANSFORM_2N) {
+ x = ONE_UM<<log2rsize;
+ if (rsize == x) return x;
+ step = x>>1;
+ x += step;
+ return (rsize <= x) ? x : x + step;
+ }
+ else if (rsize <= MPD_MAXTRANSFORM_2N+MPD_MAXTRANSFORM_2N/2) {
+ return MPD_MAXTRANSFORM_2N+MPD_MAXTRANSFORM_2N/2;
+ }
+ else if (rsize <= 3*MPD_MAXTRANSFORM_2N) {
+ return 3*MPD_MAXTRANSFORM_2N;
+ }
+ else {
+ return SIZE_MAX;
+ }
+}
+
+#ifdef PPRO
+#ifndef _MSC_VER
+static inline unsigned short
+_mpd_get_control87(void)
+{
+ unsigned short cw;
+
+ __asm__ __volatile__ ("fnstcw %0" : "=m" (cw));
+ return cw;
+}
+
+static inline void
+_mpd_set_control87(unsigned short cw)
+{
+ __asm__ __volatile__ ("fldcw %0" : : "m" (cw));
+}
+#endif
+
+unsigned int
+mpd_set_fenv(void)
+{
+ unsigned int cw;
+#ifdef _MSC_VER
+ cw = _control87(0, 0);
+ _control87((_RC_CHOP|_PC_64), (_MCW_RC|_MCW_PC));
+#else
+ cw = _mpd_get_control87();
+ _mpd_set_control87(cw|0x780);
+#endif
+ return cw;
+}
+
+void
+mpd_restore_fenv(unsigned int cw)
+{
+#ifdef _MSC_VER
+ _control87(cw, (_MCW_RC|_MCW_PC));
+#else
+ _mpd_set_control87((unsigned short)cw);
+#endif
+}
+#endif /* PPRO */
+
+/*
+ * Multiply u and v, using the fast number theoretic transform. Returns
+ * a pointer to the result or NULL in case of failure (malloc error).
+ */
+mpd_uint_t *
+_mpd_fntmul(const mpd_uint_t *u, const mpd_uint_t *v, size_t ulen, size_t vlen, size_t *rsize)
+{
+ mpd_uint_t *c1 = NULL, *c2 = NULL, *c3 = NULL, *vtmp = NULL;
+ size_t n;
+
+#ifdef PPRO
+ unsigned int cw;
+ cw = mpd_set_fenv();
+#endif
+
+ *rsize = add_size_t(ulen, vlen);
+ if ((n = _mpd_get_transform_len(*rsize)) == SIZE_MAX) {
+ goto malloc_error;
+ }
+
+ if ((c1 = mpd_calloc(sizeof *c1, n)) == NULL) {
+ goto malloc_error;
+ }
+ if ((c2 = mpd_calloc(sizeof *c2, n)) == NULL) {
+ goto malloc_error;
+ }
+ if ((c3 = mpd_calloc(sizeof *c3, n)) == NULL) {
+ goto malloc_error;
+ }
+
+ memcpy(c1, u, ulen * (sizeof *c1));
+ memcpy(c2, u, ulen * (sizeof *c2));
+ memcpy(c3, u, ulen * (sizeof *c3));
+
+ if (u == v) {
+
+ fnt_autoconvolute(c1, n, P1);
+ fnt_autoconvolute(c2, n, P2);
+ fnt_autoconvolute(c3, n, P3);
+ }
+ else {
+ if ((vtmp = mpd_calloc(sizeof *vtmp, n)) == NULL) {
+ goto malloc_error;
+ }
+
+ memcpy(vtmp, v, vlen * (sizeof *vtmp));
+ fnt_convolute(c1, vtmp, n, P1);
+
+ memcpy(vtmp, v, vlen * (sizeof *vtmp));
+ mpd_uint_zero(vtmp+vlen, n-vlen);
+ fnt_convolute(c2, vtmp, n, P2);
+
+ memcpy(vtmp, v, vlen * (sizeof *vtmp));
+ mpd_uint_zero(vtmp+vlen, n-vlen);
+ fnt_convolute(c3, vtmp, n, P3);
+
+ mpd_free(vtmp);
+ }
+
+ crt3(c1, c2, c3, *rsize);
+
+out:
+#ifdef PPRO
+ mpd_restore_fenv(cw);
+#endif
+ if (c2) mpd_free(c2);
+ if (c3) mpd_free(c3);
+ return c1;
+
+malloc_error:
+ if (c1) mpd_free(c1);
+ c1 = NULL;
+ goto out;
+}
+
+
+/*
+ * Karatsuba multiplication with FNT/basemul as the base case.
+ */
+static int
+_karatsuba_rec_fnt(mpd_uint_t *c, const mpd_uint_t *a, const mpd_uint_t *b, mpd_uint_t *w,
+ size_t la, size_t lb)
+{
+ size_t m, lt;
+
+ assert (la >= lb && lb > 0);
+
+ if (la <= 3*(MPD_MAXTRANSFORM_2N/2)) {
+
+ if (lb <= 192) {
+ _mpd_basemul(c, b, a, lb, la);
+ }
+ else {
+ mpd_uint_t *result;
+ size_t dummy;
+
+ if ((result = _mpd_fntmul(a, b, la, lb, &dummy)) == NULL) {
+ return 0;
+ }
+ memcpy(c, result, (la+lb) * (sizeof *result));
+ mpd_free(result);
+ }
+ return 1;
+ }
+
+ m = (la+1)/2; // ceil(la/2)
+
+ /* lb <= m < la */
+ if (lb <= m) {
+
+ /* lb can now be larger than la-m */
+ if (lb > la-m) {
+ lt = lb + lb + 1; // space needed for result array
+ mpd_uint_zero(w, lt); // clear result array
+ if (!_karatsuba_rec_fnt(w, b, a+m, w+lt, lb, la-m)) { // b*ah
+ return 0;
+ }
+ }
+ else {
+ lt = (la-m) + (la-m) + 1; // space needed for result array
+ mpd_uint_zero(w, lt); // clear result array
+ if (!_karatsuba_rec_fnt(w, a+m, b, w+lt, la-m, lb)) { // ah*b
+ return 0;
+ }
+ }
+ _mpd_baseaddto(c+m, w, (la-m)+lb); // add ah*b*B**m
+
+ lt = m + m + 1; // space needed for the result array
+ mpd_uint_zero(w, lt); // clear result array
+ if (!_karatsuba_rec_fnt(w, a, b, w+lt, m, lb)) { // al*b
+ return 0;
+ }
+ _mpd_baseaddto(c, w, m+lb); // add al*b
+
+ return 1;
+ }
+
+ /* la >= lb > m */
+ memcpy(w, a, m * sizeof *w);
+ w[m] = 0;
+ _mpd_baseaddto(w, a+m, la-m);
+
+ memcpy(w+(m+1), b, m * sizeof *w);
+ w[m+1+m] = 0;
+ _mpd_baseaddto(w+(m+1), b+m, lb-m);
+
+ if (!_karatsuba_rec_fnt(c+m, w, w+(m+1), w+2*(m+1), m+1, m+1)) {
+ return 0;
+ }
+
+ lt = (la-m) + (la-m) + 1;
+ mpd_uint_zero(w, lt);
+
+ if (!_karatsuba_rec_fnt(w, a+m, b+m, w+lt, la-m, lb-m)) {
+ return 0;
+ }
+
+ _mpd_baseaddto(c+2*m, w, (la-m) + (lb-m));
+ _mpd_basesubfrom(c+m, w, (la-m) + (lb-m));
+
+ lt = m + m + 1;
+ mpd_uint_zero(w, lt);
+
+ if (!_karatsuba_rec_fnt(w, a, b, w+lt, m, m)) {
+ return 0;
+ }
+ _mpd_baseaddto(c, w, m+m);
+ _mpd_basesubfrom(c+m, w, m+m);
+
+ return 1;
+}
+
+/*
+ * Multiply u and v, using Karatsuba multiplication with the FNT as the
+ * base case. Returns a pointer to the result or NULL in case of failure
+ * (malloc error). Conditions: ulen >= vlen, ulen >= 4.
+ */
+mpd_uint_t *
+_mpd_kmul_fnt(const mpd_uint_t *u, const mpd_uint_t *v, size_t ulen, size_t vlen, size_t *rsize)
+{
+ mpd_uint_t *result = NULL, *w = NULL;
+ size_t m;
+
+ assert(ulen >= 4);
+ assert(ulen >= vlen);
+
+ *rsize = _kmul_resultsize(ulen, vlen);
+ if ((result = mpd_calloc(*rsize, sizeof *result)) == NULL) {
+ return NULL;
+ }
+
+ m = _kmul_worksize(ulen, 3*(MPD_MAXTRANSFORM_2N/2));
+ if (m && ((w = mpd_calloc(m, sizeof *w)) == NULL)) {
+ mpd_free(result);
+ return NULL;
+ }
+
+ if (!_karatsuba_rec_fnt(result, u, v, w, ulen, vlen)) {
+ mpd_free(result);
+ result = NULL;
+ }
+
+
+ if (w) mpd_free(w);
+ return result;
+}
+
+
+/* Deal with the special cases of multiplying infinities. */
+static void
+_mpd_qmul_inf(mpd_t *result, const mpd_t *a, const mpd_t *b, uint32_t *status)
+{
+ if (mpd_isinfinite(a)) {
+ if (mpd_iszero(b)) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ }
+ else {
+ mpd_setspecial(result, mpd_sign(a)^mpd_sign(b), MPD_INF);
+ }
+ return;
+ }
+ assert(mpd_isinfinite(b));
+ if (mpd_iszero(a)) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ }
+ else {
+ mpd_setspecial(result, mpd_sign(a)^mpd_sign(b), MPD_INF);
+ }
+}
+
+/*
+ * Internal function: Multiply a and b. _mpd_qmul deals with specials but
+ * does NOT finalize the result. This is for use in mpd_fma().
+ */
+static inline void
+_mpd_qmul(mpd_t *result, const mpd_t *a, const mpd_t *b,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_t *big = (mpd_t *)a, *small = (mpd_t *)b;
+ mpd_uint_t *rdata = NULL;
+ mpd_uint_t rbuf[MPD_MINALLOC_MAX];
+ size_t rsize, i;
+
+
+ if (mpd_isspecial(a) || mpd_isspecial(b)) {
+ if (mpd_qcheck_nans(result, a, b, ctx, status)) {
+ return;
+ }
+ _mpd_qmul_inf(result, a, b, status);
+ return;
+ }
+
+ if (small->len > big->len) {
+ _mpd_ptrswap(&big, &small);
+ }
+
+ rsize = big->len + small->len;
+
+ if (big->len == 1) {
+ _mpd_singlemul(result->data, big->data[0], small->data[0]);
+ goto finish;
+ }
+ if (rsize <= (size_t)MPD_MINALLOC_MAX) {
+ if (big->len == 2) {
+ _mpd_mul_2_le2(rbuf, big->data, small->data, small->len);
+ }
+ else {
+ mpd_uint_zero(rbuf, rsize);
+ if (small->len == 1) {
+ _mpd_shortmul(rbuf, big->data, big->len, small->data[0]);
+ }
+ else {
+ _mpd_basemul(rbuf, small->data, big->data, small->len, big->len);
+ }
+ }
+ if (!mpd_qresize(result, rsize, status)) {
+ return;
+ }
+ for(i = 0; i < rsize; i++) {
+ result->data[i] = rbuf[i];
+ }
+ goto finish;
+ }
+
+
+ if (big->len == 2) {
+ if ((rdata = mpd_calloc(rsize, sizeof *rdata)) == NULL) {
+ mpd_seterror(result, MPD_Malloc_error, status);
+ return;
+ }
+ _mpd_mul_2_le2(rdata, big->data, small->data, small->len);
+ }
+ else if (small->len == 1) {
+ if ((rdata = mpd_calloc(rsize, sizeof *rdata)) == NULL) {
+ mpd_seterror(result, MPD_Malloc_error, status);
+ return;
+ }
+ _mpd_shortmul(rdata, big->data, big->len, small->data[0]);
+ }
+ else if (small->len <= 16 && rsize <= 64) {
+ if ((rdata = mpd_calloc(rsize, sizeof *rdata)) == NULL) {
+ mpd_seterror(result, MPD_Malloc_error, status);
+ return;
+ }
+ _mpd_basemul(rdata, small->data, big->data, small->len, big->len);
+ }
+ else if (small->len <= 256 && rsize <= 1024) {
+ rdata = _mpd_kmul(big->data, small->data, big->len, small->len, &rsize);
+ if (rdata == NULL) {
+ mpd_seterror(result, MPD_Malloc_error, status);
+ return;
+ }
+ }
+ else if (rsize <= 3*MPD_MAXTRANSFORM_2N) {
+ rdata = _mpd_fntmul(big->data, small->data, big->len, small->len, &rsize);
+ if (rdata == NULL) {
+ mpd_seterror(result, MPD_Malloc_error, status);
+ return;
+ }
+ }
+ else {
+ rdata = _mpd_kmul_fnt(big->data, small->data, big->len, small->len, &rsize);
+ if (rdata == NULL) {
+ mpd_seterror(result, MPD_Malloc_error, status);
+ return;
+ }
+ }
+
+ if (mpd_isdynamic_data(result)) {
+ mpd_free(result->data);
+ }
+ result->data = rdata;
+ result->alloc = rsize;
+ mpd_set_dynamic_data(result);
+
+
+finish:
+ mpd_set_flags(result, mpd_sign(a)^mpd_sign(b));
+ result->exp = big->exp + small->exp;
+ result->len = _mpd_real_size(result->data, rsize);
+ /* resize to smaller cannot fail */
+ mpd_qresize(result, result->len, status);
+ mpd_setdigits(result);
+}
+
+/* Multiply a and b. */
+void
+mpd_qmul(mpd_t *result, const mpd_t *a, const mpd_t *b,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ _mpd_qmul(result, a, b, ctx, status);
+ mpd_qfinalize(result, ctx, status);
+}
+
+/* Multiply decimal and mpd_ssize_t. */
+void
+mpd_qmul_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ mpd_t bb;
+ mpd_uint_t bdata[2];
+
+ bb.data = bdata;
+ bb.flags = MPD_STATIC|MPD_CONST_DATA;
+
+ mpd_qsset_ssize(&bb, b, ctx, status);
+ mpd_qmul(result, a, &bb, ctx, status);
+}
+
+/* Multiply decimal and mpd_uint_t. */
+void
+mpd_qmul_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ mpd_t bb;
+ mpd_uint_t bdata[2];
+
+ bb.data = bdata;
+ bb.flags = MPD_STATIC|MPD_CONST_DATA;
+
+ mpd_qsset_uint(&bb, b, ctx, status);
+ mpd_qmul(result, a, &bb, ctx, status);
+}
+
+void
+mpd_qmul_i32(mpd_t *result, const mpd_t *a, int32_t b, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ mpd_qmul_ssize(result, a, b, ctx, status);
+}
+
+void
+mpd_qmul_u32(mpd_t *result, const mpd_t *a, uint32_t b, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ mpd_qmul_uint(result, a, b, ctx, status);
+}
+
+#ifdef CONFIG_64
+void
+mpd_qmul_i64(mpd_t *result, const mpd_t *a, int64_t b, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ mpd_qmul_ssize(result, a, b, ctx, status);
+}
+
+void
+mpd_qmul_u64(mpd_t *result, const mpd_t *a, uint64_t b, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ mpd_qmul_uint(result, a, b, ctx, status);
+}
+#endif
+
+/* Like the minus operator. */
+void
+mpd_qminus(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status)
+{
+ if (mpd_isspecial(a)) {
+ if (mpd_qcheck_nan(result, a, ctx, status)) {
+ return;
+ }
+ }
+
+ if (mpd_iszero(a)) {
+ mpd_qcopy_abs(result, a, status);
+ }
+ else {
+ mpd_qcopy_negate(result, a, status);
+ }
+
+ mpd_qfinalize(result, ctx, status);
+}
+
+/* Like the plus operator. */
+void
+mpd_qplus(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status)
+{
+ if (mpd_isspecial(a)) {
+ if (mpd_qcheck_nan(result, a, ctx, status)) {
+ return;
+ }
+ }
+
+ if (mpd_iszero(a)) {
+ mpd_qcopy_abs(result, a, status);
+ }
+ else {
+ mpd_qcopy(result, a, status);
+ }
+
+ mpd_qfinalize(result, ctx, status);
+}
+
+/* The largest representable number that is smaller than the operand. */
+void
+mpd_qnext_minus(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ mpd_context_t workctx; /* function context */
+ MPD_NEW_CONST(tiny,MPD_POS,mpd_etiny(ctx)-1,1,1,1,1);
+
+ if (mpd_isspecial(a)) {
+ if (mpd_qcheck_nan(result, a, ctx, status)) {
+ return;
+ }
+ if (mpd_isinfinite(a)) {
+ if (mpd_isnegative(a)) {
+ mpd_qcopy(result, a, status);
+ return;
+ }
+ else {
+ mpd_qmaxcoeff(result, ctx, status);
+ if (mpd_isnan(result)) {
+ return;
+ }
+ mpd_clear_flags(result);
+ result->exp = ctx->emax - ctx->prec + 1;
+ return;
+ }
+ }
+ /* should not be reached */
+ abort();
+ }
+
+ mpd_workcontext(&workctx, ctx);
+ workctx.round = MPD_ROUND_FLOOR;
+
+ if (!mpd_qcopy(result, a, status)) {
+ return;
+ }
+
+ mpd_qfinalize(result, &workctx, &workctx.status);
+ if (workctx.status&(MPD_Inexact|MPD_Errors)) {
+ return;
+ }
+
+ workctx.status = 0;
+ mpd_qsub(result, a, &tiny, &workctx, &workctx.status);
+ *status |= (workctx.status&MPD_Errors);
+}
+
+/* The smallest representable number that is larger than the operand. */
+void
+mpd_qnext_plus(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ mpd_context_t workctx;
+ MPD_NEW_CONST(tiny,MPD_POS,mpd_etiny(ctx)-1,1,1,1,1);
+
+ if (mpd_isspecial(a)) {
+ if (mpd_qcheck_nan(result, a, ctx, status)) {
+ return;
+ }
+ if (mpd_isinfinite(a)) {
+ if (mpd_ispositive(a)) {
+ mpd_qcopy(result, a, status);
+ }
+ else {
+ mpd_qmaxcoeff(result, ctx, status);
+ if (mpd_isnan(result)) {
+ return;
+ }
+ mpd_set_flags(result, MPD_NEG);
+ result->exp = mpd_etop(ctx);
+ }
+ return;
+ }
+ }
+
+ mpd_workcontext(&workctx, ctx);
+ workctx.round = MPD_ROUND_CEILING;
+
+ if (!mpd_qcopy(result, a, &workctx.status)) {
+ return;
+ }
+
+ mpd_qfinalize(result, &workctx, &workctx.status);
+ if (workctx.status & (MPD_Inexact|MPD_Errors)) {
+ return;
+ }
+
+ workctx.status = 0;
+ mpd_qadd(result, a, &tiny, &workctx, &workctx.status);
+ *status |= (workctx.status&MPD_Errors);
+}
+
+/*
+ * The number closest to the first operand that is in the direction towards
+ * the second operand.
+ */
+void
+mpd_qnext_toward(mpd_t *result, const mpd_t *a, const mpd_t *b,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ int c;
+
+ if (mpd_isnan(a) || mpd_isnan(b)) {
+ if (mpd_qcheck_nans(result, a, b, ctx, status))
+ return;
+ }
+
+ c = _mpd_cmp(a, b);
+ if (c == 0) {
+ mpd_qcopy_sign(result, a, b, status);
+ return;
+ }
+
+ if (c < 0) {
+ mpd_qnext_plus(result, a, ctx, status);
+ }
+ else {
+ mpd_qnext_minus(result, a, ctx, status);
+ }
+
+ if (mpd_isinfinite(result)) {
+ *status |= (MPD_Overflow|MPD_Rounded|MPD_Inexact);
+ }
+ else if (mpd_adjexp(result) < ctx->emin) {
+ *status |= (MPD_Underflow|MPD_Subnormal|MPD_Rounded|MPD_Inexact);
+ if (mpd_iszero(result)) {
+ *status |= MPD_Clamped;
+ }
+ }
+}
+
+/*
+ * Internal function: Integer power with mpd_uint_t exponent, base is modified!
+ * Function can fail with MPD_Malloc_error.
+ */
+static inline void
+_mpd_qpow_uint(mpd_t *result, mpd_t *base, mpd_uint_t exp, uint8_t resultsign,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ uint32_t workstatus = 0;
+ mpd_uint_t n;
+
+ if (exp == 0) {
+ _settriple(result, resultsign, 1, 0);
+ return;
+ }
+
+ if (!mpd_qcopy(result, base, status)) {
+ return;
+ }
+
+ n = mpd_bits[BSR(exp)];
+ while (n >>= 1) {
+ mpd_qmul(result, result, result, ctx, &workstatus);
+ if (exp & n) {
+ mpd_qmul(result, result, base, ctx, &workstatus);
+ }
+ if (workstatus & (MPD_Overflow|MPD_Clamped)) {
+ break;
+ }
+ }
+
+ *status |= workstatus;
+ mpd_set_sign(result, resultsign);
+}
+
+/*
+ * Internal function: Integer power with mpd_t exponent, tbase and texp
+ * are modified!! Function can fail with MPD_Malloc_error.
+ */
+static inline void
+_mpd_qpow_mpd(mpd_t *result, mpd_t *tbase, mpd_t *texp, uint8_t resultsign,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ uint32_t workstatus = 0;
+ mpd_context_t maxctx;
+ MPD_NEW_CONST(two,0,0,1,1,1,2);
+
+
+ mpd_maxcontext(&maxctx);
+
+ if (!mpd_qcopy(result, &one, status)) {
+ return;
+ }
+
+ while (!mpd_iszero(texp)) {
+ if (mpd_isodd(texp)) {
+ mpd_qmul(result, result, tbase, ctx, &workstatus);
+ *status |= workstatus;
+ if (workstatus & (MPD_Overflow|MPD_Clamped)) {
+ break;
+ }
+ }
+ mpd_qmul(tbase, tbase, tbase, ctx, &workstatus);
+ mpd_qdivint(texp, texp, &two, &maxctx, &workstatus);
+ if (mpd_isnan(texp)) {
+ mpd_seterror(result, MPD_Division_undefined, status);
+ return;
+ }
+ }
+ mpd_set_sign(result, resultsign);
+}
+
+/*
+ * The power function for integer exponents.
+ */
+static void
+_mpd_qpow_int(mpd_t *result, const mpd_t *base, const mpd_t *exp, uint8_t resultsign,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_context_t workctx;
+ MPD_NEW_STATIC(tbase,0,0,0,0);
+ MPD_NEW_STATIC(texp,0,0,0,0);
+ mpd_ssize_t n;
+
+
+ mpd_workcontext(&workctx, ctx);
+ workctx.prec += (exp->digits + exp->exp + 2);
+ workctx.round = MPD_ROUND_HALF_EVEN;
+ if (mpd_isnegative(exp)) {
+ mpd_qdiv(&tbase, &one, base, &workctx, status);
+ if (*status&MPD_Errors) {
+ mpd_setspecial(result, MPD_POS, MPD_NAN);
+ goto finish;
+ }
+ }
+ else {
+ if (!mpd_qcopy(&tbase, base, status)) {
+ mpd_setspecial(result, MPD_POS, MPD_NAN);
+ goto finish;
+ }
+ }
+
+ n = mpd_qget_uint(exp, &workctx.status);
+ if (workctx.status&MPD_Invalid_operation) {
+ if (!mpd_qcopy(&texp, exp, status)) {
+ mpd_setspecial(result, MPD_POS, MPD_NAN);
+ goto finish;
+ }
+ _mpd_qpow_mpd(result, &tbase, &texp, resultsign, &workctx, status);
+ }
+ else {
+ _mpd_qpow_uint(result, &tbase, n, resultsign, &workctx, status);
+ }
+
+ if (mpd_isinfinite(result)) {
+ /* for ROUND_DOWN, ROUND_FLOOR, etc. */
+ _settriple(result, resultsign, 1, MPD_EXP_INF);
+ }
+
+finish:
+ mpd_del(&tbase);
+ mpd_del(&texp);
+ mpd_qfinalize(result, ctx, status);
+}
+
+/*
+ * This is an internal function that does not check for NaNs.
+ */
+static int
+_qcheck_pow_one_inf(mpd_t *result, const mpd_t *base, uint8_t resultsign,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_ssize_t shift;
+ int cmp;
+
+ if ((cmp = _mpd_cmp(base, &one)) == 0) {
+ shift = ctx->prec-1;
+ mpd_qshiftl(result, &one, shift, status);
+ result->exp = -shift;
+ mpd_set_flags(result, resultsign);
+ *status |= (MPD_Inexact|MPD_Rounded);
+ }
+
+ return cmp;
+}
+
+/*
+ * If base equals one, calculate the correct power of one result.
+ * Otherwise, result is undefined. Return the value of the comparison
+ * against 1.
+ *
+ * This is an internal function that does not check for specials.
+ */
+static int
+_qcheck_pow_one(mpd_t *result, const mpd_t *base, const mpd_t *exp, uint8_t resultsign,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ uint32_t workstatus = 0;
+ mpd_ssize_t shift;
+ int cmp;
+
+ if ((cmp = _mpd_cmp_abs(base, &one)) == 0) {
+ if (_mpd_isint(exp)) {
+ if (mpd_isnegative(exp)) {
+ _settriple(result, resultsign, 1, 0);
+ return 0;
+ }
+ /* 1.000**3 = 1.000000000 */
+ mpd_qmul_ssize(result, exp, -base->exp, ctx, &workstatus);
+ /* digits-1 after exponentiation */
+ shift = mpd_qget_ssize(result, &workstatus);
+ /* MPD_SSIZE_MAX on failure */
+ if (shift > ctx->prec-1) {
+ shift = ctx->prec-1;
+ *status |= MPD_Rounded;
+ }
+ }
+ else if (mpd_ispositive(base)) {
+ shift = ctx->prec-1;
+ *status |= (MPD_Inexact|MPD_Rounded);
+ }
+ else {
+ return -2;
+ }
+ mpd_qshiftl(result, &one, shift, status);
+ result->exp = -shift;
+ mpd_set_flags(result, resultsign);
+ }
+
+ return cmp;
+}
+
+static mpd_ssize_t
+_qlog10_exp_bound(const mpd_t *x, uint32_t *status)
+{
+ mpd_context_t maxctx;
+ MPD_NEW_STATIC(scratch,0,0,0,0);
+ MPD_NEW_CONST(tmp,0,0,1,1,1,1);
+ mpd_ssize_t t, numdigits, dendigits;
+
+ /*
+ * This function is designed to weed out cases where x**y will clearly
+ * over/underflow. The chain of implications is written as a stack, i.e.
+ * each line implies the line above it.
+ *
+ * (1) x**y > 10**(emax+1) /\ x**y < 10**(etiny-1)
+ *
+ * (2) log10(x) * y > emax+1 /\ log10(x) * y < etiny-1
+ *
+ * The lhs of the conjunction can only be true if the factors have the
+ * same sign, the rhs only if the factors differ. These two hypotheses
+ * are implied from now on.
+ *
+ * (3) |log10(x)| * |y| > emax+1 /\ |log10(x)| * |y| > |etiny-1|
+ *
+ * (4) log10(|log10(x)|) + log10(|y|) > log10(emax+1)
+ * /\ log10(|log10(x)|) + log10(|y|) > log10(|etiny-1|)
+ *
+ * Now, (4) clearly must be true if it is true for the following estimates
+ * for the terms:
+ *
+ * est(log10(emax+1)| >= log10(emax+1)
+ * est(log10(|etiny-1|)| >= log10(|etiny-1|)
+ *
+ * est(log10(|y|)) <= log10(|y|)
+ *
+ * 0 < est(log10(x)) <= log10(x), if x > 1
+ * log10(x) <= est(log10(x)) < 0, if x < 1
+ *
+ *
+ * Estimate for log10(x):
+ *
+ * log10(x) = log10(v * 10**t) = log10(v) + t, where 1 <= v < 10.
+ * Thus, t is adjexp(x).
+ *
+ * If t > 0, 0 < t <= log10(x), so we are done.
+ *
+ * If t < -1, log10(x) <= t+1 < 0, so we are done.
+ *
+ * If t == -1 or t == 0, then 0.1 <= base < 10. We assume x != 1 and
+ * use:
+ *
+ * 1-1/x < ln(x) < x-1 (Abramowitz&Stegun, 4.1.33)
+ *
+ * Then, if 1 < x < 10:
+ *
+ * 0 < (1-1/x) / 2.31 < log10(x)
+ * 0 < (1-1/x) / 10 < log10(x)
+ * 0 < (x-1) / (10*x) < log10(x)
+ * Multiply by (10**-x->exp), c is the coefficient:
+ * 0 < (c - 10**(-x->exp)) / (10*c) < log10(x)
+ *
+ * Then, if 0.1 <= x < 1:
+ *
+ * log10(x) <= (1-x) / 2.31 < 0
+ * log10(x) <= (1-x) / 10 < 0
+ * Multiply by (10**-x->exp), c is the coefficient:
+ * log10(x) < (10**(-x->exp) - c) / 10**(-x->exp+1) < 0
+ *
+ */
+ t = mpd_adjexp(x);
+ if (t > 0) {
+ return mpd_exp_digits(t) - 1;
+ }
+ else if (t < -1) {
+ return mpd_exp_digits(t+1) - 1;
+ }
+ else {
+ mpd_maxcontext(&maxctx);
+ tmp.exp = -x->exp;
+ if (!mpd_qcopy_abs(&scratch, x, status)) {
+ *status |= MPD_Malloc_error;
+ return MPD_SSIZE_MAX;
+ }
+ scratch.exp = 0;
+ if (t == 0) {
+ mpd_qsub(&scratch, &scratch, &tmp, &maxctx, status);
+ numdigits = scratch.digits;
+ dendigits = x->digits + 1;
+ }
+ else {
+ mpd_qsub(&scratch, &tmp, &scratch, &maxctx, status);
+ numdigits = scratch.digits;
+ if (-x->exp+1 < 0) {
+ numdigits += (-x->exp+1);
+ dendigits = 1;
+ }
+ else {
+ dendigits = -x->exp+1;
+ }
+ }
+ mpd_del(&scratch);
+ return numdigits-dendigits-(numdigits<dendigits) - 1;
+ }
+}
+
+/* Detect cases of certain overflow/underflow in the power function. */
+static int
+_qcheck_pow_bounds(mpd_t *result, const mpd_t *base, const mpd_t *exp, uint8_t resultsign,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_ssize_t bound;
+ uint8_t sign;
+
+ bound = _qlog10_exp_bound(base, status) + mpd_adjexp(exp);
+
+ sign = (mpd_adjexp(base) < 0) ^ mpd_sign(exp);
+ if (sign == 0) {
+ if (bound >= mpd_exp_digits(ctx->emax)) {
+ _settriple(result, resultsign, 1, MPD_EXP_INF);
+ mpd_qfinalize(result, ctx, status);
+ return 1;
+ }
+ }
+ else {
+ if (bound >= mpd_exp_digits(mpd_etiny(ctx))) {
+ _settriple(result, resultsign, 1, mpd_etiny(ctx)-1);
+ mpd_qfinalize(result, ctx, status);
+ return 1;
+ }
+ }
+
+ return 0;
+}
+
+/*
+ * TODO: Implement algorithm for computing exact powers from decimal.py.
+ * In order to prevent infinite loops, this has to be called before
+ * using Ziv's strategy for correct rounding.
+ */
+/*
+static int
+_mpd_qpow_exact(mpd_t *result, const mpd_t *base, const mpd_t *exp,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ return 0;
+}
+*/
+
+/* The power function for real exponents */
+static void
+_mpd_qpow_real(mpd_t *result, const mpd_t *base, const mpd_t *exp,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_context_t workctx;
+ MPD_NEW_STATIC(texp,0,0,0,0);
+
+ if (!mpd_qcopy(&texp, exp, status)) {
+ mpd_seterror(result, MPD_Malloc_error, status);
+ return;
+ }
+
+ mpd_maxcontext(&workctx);
+ workctx.prec = (base->digits > ctx->prec) ? base->digits : ctx->prec;
+ workctx.prec += (4 + MPD_EXPDIGITS);
+ workctx.round = MPD_ROUND_HALF_EVEN;
+
+ mpd_qln(result, base, &workctx, &workctx.status);
+ mpd_qmul(result, result, &texp, &workctx, &workctx.status);
+ mpd_qexp(result, result, &workctx, status);
+
+ mpd_del(&texp);
+ *status |= (workctx.status&MPD_Errors);
+ *status |= (MPD_Inexact|MPD_Rounded);
+}
+
+/* The power function: base**exp */
+void
+mpd_qpow(mpd_t *result, const mpd_t *base, const mpd_t *exp,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ uint8_t resultsign = 0;
+ int intexp = 0;
+ int cmp;
+
+ if (mpd_isspecial(base) || mpd_isspecial(exp)) {
+ if (mpd_qcheck_nans(result, base, exp, ctx, status)) {
+ return;
+ }
+ }
+ if (mpd_isinteger(exp)) {
+ intexp = 1;
+ resultsign = mpd_isnegative(base) && mpd_isodd(exp);
+ }
+
+ if (mpd_iszero(base)) {
+ if (mpd_iszero(exp)) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ }
+ else if (mpd_isnegative(exp)) {
+ mpd_setspecial(result, resultsign, MPD_INF);
+ }
+ else {
+ _settriple(result, resultsign, 0, 0);
+ }
+ return;
+ }
+ if (mpd_isnegative(base)) {
+ if (!intexp || mpd_isinfinite(exp)) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+ }
+ if (mpd_isinfinite(exp)) {
+ /* power of one */
+ if ((cmp = _qcheck_pow_one_inf(result, base, resultsign, ctx, status)) == 0) {
+ return;
+ }
+ else {
+ cmp *= mpd_arith_sign(exp);
+ if (cmp < 0) {
+ _settriple(result, resultsign, 0, 0);
+ }
+ else {
+ mpd_setspecial(result, resultsign, MPD_INF);
+ }
+ }
+ return;
+ }
+ if (mpd_isinfinite(base)) {
+ if (mpd_iszero(exp)) {
+ _settriple(result, resultsign, 1, 0);
+ }
+ else if (mpd_isnegative(exp)) {
+ _settriple(result, resultsign, 0, 0);
+ }
+ else {
+ mpd_setspecial(result, resultsign, MPD_INF);
+ }
+ return;
+ }
+ if (mpd_iszero(exp)) {
+ _settriple(result, resultsign, 1, 0);
+ return;
+ }
+ if (_qcheck_pow_one(result, base, exp, resultsign, ctx, status) == 0) {
+ return;
+ }
+ if (_qcheck_pow_bounds(result, base, exp, resultsign, ctx, status)) {
+ return;
+ }
+
+ if (intexp) {
+ _mpd_qpow_int(result, base, exp, resultsign, ctx, status);
+ }
+ else {
+ _mpd_qpow_real(result, base, exp, ctx, status);
+ if (_mpd_cmp(result, &one) == 0) {
+ mpd_ssize_t shift = ctx->prec-1;
+ mpd_qshiftl(result, &one, shift, status);
+ result->exp = -shift;
+ }
+ if (mpd_isinfinite(result)) {
+ /* for ROUND_DOWN, ROUND_FLOOR, etc. */
+ _settriple(result, MPD_POS, 1, MPD_EXP_INF);
+ }
+ mpd_qfinalize(result, ctx, status);
+ }
+}
+
+/*
+ * Internal function: Integer powmod with mpd_uint_t exponent, base is modified!
+ * Function can fail with MPD_Malloc_error.
+ */
+static inline void
+_mpd_qpowmod_uint(mpd_t *result, mpd_t *base, mpd_uint_t exp, mpd_t *mod, uint32_t *status)
+{
+ mpd_context_t maxcontext;
+
+ mpd_maxcontext(&maxcontext);
+
+ if (!mpd_qcopy(result, &one, status)) {
+ return;
+ }
+
+ while (exp > 0) {
+ if (exp & 1) {
+ mpd_qmul(result, result, base, &maxcontext, status);
+ mpd_qrem(result, result, mod, &maxcontext, status);
+ }
+ mpd_qmul(base, base, base, &maxcontext, status);
+ mpd_qrem(base, base, mod, &maxcontext, status);
+ exp >>= 1;
+ }
+}
+
+/* The powmod function: (base**exp) % mod */
+void
+mpd_qpowmod(mpd_t *result, const mpd_t *base, const mpd_t *exp, const mpd_t *mod,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_context_t maxcontext;
+ MPD_NEW_STATIC(tbase,0,0,0,0);
+ MPD_NEW_STATIC(texp,0,0,0,0);
+ MPD_NEW_STATIC(tmod,0,0,0,0);
+ MPD_NEW_STATIC(tmp,0,0,0,0);
+ MPD_NEW_CONST(two,0,0,1,1,1,2);
+ mpd_ssize_t tbase_exp, texp_exp;
+ mpd_ssize_t i;
+ mpd_t t;
+ mpd_uint_t r;
+ uint8_t sign;
+
+
+ if (mpd_isspecial(base) || mpd_isspecial(exp) || mpd_isspecial(mod)) {
+ if (mpd_qcheck_3nans(result, base, exp, mod, ctx, status)) {
+ return;
+ }
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+
+
+ if (!_mpd_isint(base) || !_mpd_isint(exp) || !_mpd_isint(mod)) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+ if (mpd_iszerocoeff(mod)) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+ sign = (mpd_isnegative(base)) && (mpd_isodd(exp));
+ if (mpd_iszerocoeff(exp)) {
+ if (mpd_iszerocoeff(base)) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+ r = (_mpd_cmp_abs(mod, &one)==0) ? 0 : 1;
+ _settriple(result, sign, r, 0);
+ return;
+ }
+ if (mpd_isnegative(exp)) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+ if (mpd_iszerocoeff(base)) {
+ _settriple(result, sign, 0, 0);
+ return;
+ }
+ if (mod->digits+mod->exp > ctx->prec) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+
+ if (!mpd_qcopy(&tmod, mod, status)) {
+ mpd_seterror(result, MPD_Malloc_error, status);
+ goto finish;
+ }
+ mpd_set_positive(&tmod);
+
+ mpd_maxcontext(&maxcontext);
+
+ mpd_qround_to_int(&tbase, base, &maxcontext, status);
+ mpd_qround_to_int(&texp, exp, &maxcontext, status);
+ mpd_qround_to_int(&tmod, &tmod, &maxcontext, status);
+
+ tbase_exp = tbase.exp;
+ tbase.exp = 0;
+ texp_exp = texp.exp;
+ texp.exp = 0;
+
+ /* base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo */
+ mpd_qrem(&tbase, &tbase, &tmod, &maxcontext, status);
+ _settriple(result, MPD_POS, 1, tbase_exp);
+ mpd_qrem(result, result, &tmod, &maxcontext, status);
+ mpd_qmul(&tbase, &tbase, result, &maxcontext, status);
+ mpd_qrem(&tbase, &tbase, &tmod, &maxcontext, status);
+
+ for (i = 0; i < texp_exp; i++) {
+ _mpd_qpowmod_uint(&tmp, &tbase, 10, &tmod, status);
+ t = tmp;
+ tmp = tbase;
+ tbase = t;
+ }
+
+ /* possible resize will be to smaller */
+ mpd_qcopy(result, &one, status);
+ while (!mpd_iszero(&texp)) {
+ if (mpd_isodd(&texp)) {
+ mpd_qmul(result, result, &tbase, &maxcontext, status);
+ mpd_qrem(result, result, &tmod, &maxcontext, status);
+ }
+ mpd_qmul(&tbase, &tbase, &tbase, &maxcontext, status);
+ mpd_qrem(&tbase, &tbase, &tmod, &maxcontext, status);
+ mpd_qdivint(&texp, &texp, &two, &maxcontext, status);
+ if (mpd_isnan(&texp)) {
+ mpd_setspecial(result, MPD_POS, MPD_NAN);
+ goto finish;
+ }
+ }
+
+
+finish:
+ mpd_del(&tbase);
+ mpd_del(&texp);
+ mpd_del(&tmod);
+ mpd_del(&tmp);
+ mpd_set_flags(result, sign);
+ mpd_qfinalize(result, ctx, status);
+}
+
+void
+mpd_qquantize(mpd_t *result, const mpd_t *a, const mpd_t *b,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ uint32_t workstatus = 0;
+ mpd_ssize_t b_exp = b->exp;
+ mpd_ssize_t expdiff, shift;
+ mpd_uint_t rnd;
+
+ if (mpd_isspecial(a) || mpd_isspecial(b)) {
+ if (mpd_qcheck_nans(result, a, b, ctx, status)) {
+ return;
+ }
+ if (mpd_isinfinite(a) && mpd_isinfinite(b)) {
+ mpd_qcopy(result, a, status);
+ return;
+ }
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+
+ if (b->exp > ctx->emax || b->exp < mpd_etiny(ctx)) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+
+ if (mpd_iszero(a)) {
+ _settriple(result, mpd_sign(a), 0, b->exp);
+ mpd_qfinalize(result, ctx, status);
+ return;
+ }
+
+
+ expdiff = a->exp - b->exp;
+ if (a->digits + expdiff > ctx->prec) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+
+ if (expdiff >= 0) {
+ shift = expdiff;
+ if (!mpd_qshiftl(result, a, shift, status)) {
+ return;
+ }
+ result->exp = b_exp;
+ }
+ else {
+ /* At this point expdiff < 0 and a->digits+expdiff <= prec,
+ * so the shift before an increment will fit in prec. */
+ shift = -expdiff;
+ rnd = mpd_qshiftr(result, a, shift, status);
+ result->exp = b_exp;
+ if (!_mpd_apply_round_fit(result, rnd, ctx, status)) {
+ return;
+ }
+ workstatus |= MPD_Rounded;
+ if (rnd) {
+ workstatus |= MPD_Inexact;
+ }
+ }
+
+ if (mpd_adjexp(result) > ctx->emax || mpd_adjexp(result) < mpd_etiny(ctx)) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+
+ if (mpd_issubnormal(result, ctx)) {
+ *status |= MPD_Subnormal;
+ }
+ *status |= workstatus;
+}
+
+void
+mpd_qreduce(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_ssize_t shift, maxexp, maxshift;
+ uint8_t sign_a = mpd_sign(a);
+
+ if (mpd_isspecial(a)) {
+ if (mpd_qcheck_nan(result, a, ctx, status)) {
+ return;
+ }
+ mpd_qcopy(result, a, status);
+ return;
+ }
+
+ if (!mpd_qcopy(result, a, status)) {
+ return;
+ }
+ mpd_qfinalize(result, ctx, status);
+ if (mpd_isspecial(result)) {
+ return;
+ }
+ if (mpd_iszero(result)) {
+ _settriple(result, sign_a, 0, 0);
+ return;
+ }
+
+ shift = mpd_trail_zeros(result);
+ maxexp = (ctx->clamp) ? mpd_etop(ctx) : ctx->emax;
+ /* After the finalizing above result->exp <= maxexp. */
+ maxshift = maxexp - result->exp;
+ shift = (shift > maxshift) ? maxshift : shift;
+
+ mpd_qshiftr_inplace(result, shift);
+ result->exp += shift;
+}
+
+void
+mpd_qrem(mpd_t *r, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ MPD_NEW_STATIC(q,0,0,0,0);
+
+ if (mpd_isspecial(a) || mpd_isspecial(b)) {
+ if (mpd_qcheck_nans(r, a, b, ctx, status)) {
+ return;
+ }
+ if (mpd_isinfinite(a)) {
+ mpd_seterror(r, MPD_Invalid_operation, status);
+ return;
+ }
+ if (mpd_isinfinite(b)) {
+ mpd_qcopy(r, a, status);
+ mpd_qfinalize(r, ctx, status);
+ return;
+ }
+ /* debug */
+ abort();
+ }
+ if (mpd_iszerocoeff(b)) {
+ if (mpd_iszerocoeff(a)) {
+ mpd_seterror(r, MPD_Division_undefined, status);
+ }
+ else {
+ mpd_seterror(r, MPD_Invalid_operation, status);
+ }
+ return;
+ }
+
+ _mpd_qdivmod(&q, r, a, b, ctx, status);
+ mpd_del(&q);
+ mpd_qfinalize(r, ctx, status);
+}
+
+void
+mpd_qrem_near(mpd_t *r, const mpd_t *a, const mpd_t *b,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_context_t workctx;
+ MPD_NEW_STATIC(btmp,0,0,0,0);
+ MPD_NEW_STATIC(q,0,0,0,0);
+ mpd_ssize_t expdiff, floordigits;
+ int cmp, isodd, allnine;
+
+ if (mpd_isspecial(a) || mpd_isspecial(b)) {
+ if (mpd_qcheck_nans(r, a, b, ctx, status)) {
+ return;
+ }
+ if (mpd_isinfinite(a)) {
+ mpd_seterror(r, MPD_Invalid_operation, status);
+ return;
+ }
+ if (mpd_isinfinite(b)) {
+ mpd_qcopy(r, a, status);
+ mpd_qfinalize(r, ctx, status);
+ return;
+ }
+ /* debug */
+ abort();
+ }
+ if (mpd_iszerocoeff(b)) {
+ if (mpd_iszerocoeff(a)) {
+ mpd_seterror(r, MPD_Division_undefined, status);
+ }
+ else {
+ mpd_seterror(r, MPD_Invalid_operation, status);
+ }
+ return;
+ }
+
+ if (r == b) {
+ if (!mpd_qcopy(&btmp, b, status)) {
+ mpd_seterror(r, MPD_Malloc_error, status);
+ return;
+ }
+ b = &btmp;
+ }
+
+ workctx = *ctx;
+ workctx.prec = a->digits;
+ workctx.prec = (workctx.prec > ctx->prec) ? workctx.prec : ctx->prec;
+
+ _mpd_qdivmod(&q, r, a, b, &workctx, status);
+ if (mpd_isnan(&q) || mpd_isnan(r) || q.digits > ctx->prec) {
+ mpd_seterror(r, MPD_Division_impossible, status);
+ goto finish;
+ }
+ if (mpd_iszerocoeff(r)) {
+ goto finish;
+ }
+
+ /* Deal with cases like rmnx078:
+ * remaindernear 999999999.5 1 -> NaN Division_impossible */
+ expdiff = mpd_adjexp(b) - mpd_adjexp(r);
+ if (-1 <= expdiff && expdiff <= 1) {
+
+ mpd_qfloor(&q, &q, &workctx, &workctx.status);
+ allnine = mpd_coeff_isallnine(&q);
+ floordigits = q.digits;
+ isodd = mpd_isodd(&q);
+
+ mpd_maxcontext(&workctx);
+ if (mpd_sign(a) == mpd_sign(b)) {
+ _mpd_qsub(&q, r, b, &workctx, &workctx.status);
+ }
+ else {
+ _mpd_qadd(&q, r, b, &workctx, &workctx.status);
+ }
+
+ cmp = mpd_cmp_total_mag(&q, r);
+ if (cmp < 0 || (cmp == 0 && isodd)) {
+ if (allnine && floordigits == ctx->prec) {
+ mpd_seterror(r, MPD_Division_impossible, status);
+ goto finish;
+ }
+ mpd_qcopy(r, &q, status);
+ *status &= ~MPD_Rounded;
+ }
+ }
+
+
+finish:
+ mpd_del(&btmp);
+ mpd_del(&q);
+ mpd_qfinalize(r, ctx, status);
+}
+
+/*
+ * Rescale a number so that it has exponent 'exp'. Does not regard
+ * context precision, emax, emin, but uses the rounding mode.
+ * Special numbers are quietly copied.
+ */
+void
+mpd_qrescale(mpd_t *result, const mpd_t *a, mpd_ssize_t exp,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_ssize_t expdiff, shift;
+ mpd_uint_t rnd;
+
+ if (mpd_isspecial(a)) {
+ mpd_qcopy(result, a, status);
+ return;
+ }
+
+ if (exp > MPD_MAX_EMAX || exp < MPD_MIN_ETINY) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+
+ if (mpd_iszero(a)) {
+ _settriple(result, mpd_sign(a), 0, exp);
+ return;
+ }
+
+ expdiff = a->exp - exp;
+ if (expdiff >= 0) {
+ shift = expdiff;
+ if (!mpd_qshiftl(result, a, shift, status)) {
+ return;
+ }
+ result->exp = exp;
+ }
+ else {
+ shift = -expdiff;
+ rnd = mpd_qshiftr(result, a, shift, status);
+ result->exp = exp;
+ _mpd_apply_round_excess(result, rnd, ctx, status);
+ *status |= MPD_Rounded;
+ if (rnd) {
+ *status |= MPD_Inexact;
+ }
+ }
+
+ if (mpd_issubnormal(result, ctx)) {
+ *status |= MPD_Subnormal;
+ }
+}
+
+/* Round to an integer according to 'action' and ctx->round. */
+enum {TO_INT_EXACT, TO_INT_SILENT, TO_INT_FLOOR, TO_INT_CEIL};
+static void
+_mpd_qround_to_integral(int action, mpd_t *result, const mpd_t *a,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_uint_t rnd;
+
+ if (mpd_isspecial(a)) {
+ if (mpd_qcheck_nan(result, a, ctx, status)) {
+ return;
+ }
+ mpd_qcopy(result, a, status);
+ return;
+ }
+ if (a->exp >= 0) {
+ mpd_qcopy(result, a, status);
+ return;
+ }
+ if (mpd_iszerocoeff(a)) {
+ _settriple(result, mpd_sign(a), 0, 0);
+ return;
+ }
+
+ rnd = mpd_qshiftr(result, a, -a->exp, status);
+ result->exp = 0;
+
+ if (action == TO_INT_EXACT || action == TO_INT_SILENT) {
+ _mpd_apply_round(result, rnd, ctx, status);
+ if (action == TO_INT_EXACT) {
+ *status |= MPD_Rounded;
+ if (rnd) {
+ *status |= MPD_Inexact;
+ }
+ }
+ }
+ else if (action == TO_INT_CEIL) {
+ if (rnd) {
+ mpd_qadd(result, result, &one, ctx, status);
+ }
+ }
+}
+
+void
+mpd_qround_to_intx(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ (void)_mpd_qround_to_integral(TO_INT_EXACT, result, a, ctx, status);
+}
+
+void
+mpd_qround_to_int(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ (void)_mpd_qround_to_integral(TO_INT_SILENT, result, a, ctx, status);
+}
+
+void
+mpd_qfloor(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ (void)_mpd_qround_to_integral(TO_INT_FLOOR, result, a, ctx, status);
+}
+
+void
+mpd_qceil(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ (void)_mpd_qround_to_integral(TO_INT_CEIL, result, a, ctx, status);
+}
+
+int
+mpd_same_quantum(const mpd_t *a, const mpd_t *b)
+{
+ if (mpd_isspecial(a) || mpd_isspecial(b)) {
+ return ((mpd_isnan(a) && mpd_isnan(b)) ||
+ (mpd_isinfinite(a) && mpd_isinfinite(b)));
+ }
+
+ return a->exp == b->exp;
+}
+
+/* Schedule the increase in precision for the Newton iteration. */
+static inline int
+recpr_schedule_prec(mpd_ssize_t klist[MPD_MAX_PREC_LOG2], mpd_ssize_t maxprec, mpd_ssize_t initprec)
+{
+ mpd_ssize_t k;
+ int i;
+
+ assert(maxprec > 0 && initprec > 0);
+ if (maxprec <= initprec) return -1;
+
+ i = 0; k = maxprec;
+ do {
+ k = (k+1) / 2;
+ klist[i++] = k;
+ } while (k > initprec);
+
+ return i-1;
+}
+
+/*
+ * Initial approximation for the reciprocal. Result has MPD_RDIGITS-2 significant
+ * digits.
+ */
+static void
+_mpd_qreciprocal_approx(mpd_t *z, const mpd_t *v, uint32_t *status)
+{
+ mpd_uint_t p10data[2] = {0, mpd_pow10[MPD_RDIGITS-2]}; /* 10**(2*MPD_RDIGITS-2) */
+ mpd_uint_t dummy, word;
+ int n;
+
+ _mpd_get_msdigits(&dummy, &word, v, MPD_RDIGITS);
+ n = mpd_word_digits(word);
+ word *= mpd_pow10[MPD_RDIGITS-n];
+
+ mpd_qresize(z, 2, status);
+ (void)_mpd_shortdiv(z->data, p10data, 2, word);
+
+ mpd_clear_flags(z);
+ z->exp = -(v->exp + v->digits) - (MPD_RDIGITS-2);
+ z->len = (z->data[1] == 0) ? 1 : 2;
+ mpd_setdigits(z);
+}
+
+/* Reciprocal, calculated with Newton's Method */
+static void
+_mpd_qreciprocal(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ mpd_context_t varcontext, maxcontext;
+ mpd_t *z = result; /* current approximation */
+ mpd_t *v; /* a, normalized to a number between 0.1 and 1 */
+ MPD_NEW_SHARED(vtmp, a); /* by default v will share data with a */
+ MPD_NEW_STATIC(s,0,0,0,0); /* temporary variable */
+ MPD_NEW_STATIC(t,0,0,0,0); /* temporary variable */
+ MPD_NEW_CONST(two,0,0,1,1,1,2); /* const 2 */
+ mpd_ssize_t klist[MPD_MAX_PREC_LOG2];
+ mpd_ssize_t adj, maxprec, initprec;
+ uint8_t sign = mpd_sign(a);
+ int i;
+
+ v = &vtmp;
+ if (result == a) {
+ if ((v = mpd_qncopy(a)) == NULL) {
+ goto finish;
+ }
+ }
+
+ mpd_clear_flags(v);
+ adj = v->digits + v->exp;
+ v->exp = -v->digits;
+
+ /* initial approximation */
+ _mpd_qreciprocal_approx(z, v, status);
+
+ mpd_maxcontext(&varcontext);
+ mpd_maxcontext(&maxcontext);
+ varcontext.round = MPD_ROUND_TRUNC;
+ maxcontext.round = MPD_ROUND_TRUNC;
+
+ maxprec = (v->digits > ctx->prec) ? v->digits : ctx->prec;
+ maxprec += 2;
+ initprec = MPD_RDIGITS-3;
+
+ i = recpr_schedule_prec(klist, maxprec, initprec);
+ for (; i >= 0; i--) {
+ mpd_qmul(&s, z, z, &maxcontext, status);
+ varcontext.prec = 2*klist[i] + 5;
+ if (v->digits > varcontext.prec) {
+ mpd_qshiftr(&t, v, v->digits-varcontext.prec, status);
+ t.exp = -varcontext.prec;
+ mpd_qmul(&t, &t, &s, &varcontext, status);
+ }
+ else {
+ mpd_qmul(&t, v, &s, &varcontext, status);
+ }
+ mpd_qmul(&s, z, &two, &maxcontext, status);
+ mpd_qsub(z, &s, &t, &maxcontext, status);
+ }
+
+ z->exp -= adj;
+ mpd_set_flags(z, sign);
+
+
+finish:
+ mpd_del(&s);
+ mpd_del(&t);
+ if (v != &vtmp) mpd_del(v);
+ mpd_qfinalize(z, ctx, status);
+}
+
+/*
+ * Integer division with remainder of the coefficients: coeff(a) / coeff(b).
+ * This function is for large numbers where it is faster to divide by
+ * multiplying the dividend by the reciprocal of the divisor. The inexact
+ * result is fixed by a small loop, which should not take more than 2 iterations.
+ */
+static void
+_mpd_qbarrett_divmod(mpd_t *q, mpd_t *r, const mpd_t *a, const mpd_t *b,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_context_t workctx;
+ mpd_t *qq = q, *rr = r;
+ mpd_t aa, bb;
+ int k;
+
+ workctx = *ctx;
+ _mpd_copy_shared(&aa, a);
+ _mpd_copy_shared(&bb, b);
+
+ mpd_set_positive(&aa);
+ mpd_set_positive(&bb);
+ aa.exp = 0;
+ bb.exp = 0;
+
+ if (q == a || q == b) {
+ if ((qq = mpd_qnew()) == NULL) {
+ goto nanresult;
+ }
+ }
+ if (r == a || r == b) {
+ if ((rr = mpd_qnew()) == NULL) {
+ goto nanresult;
+ }
+ }
+
+ /* maximum length of q + 3 digits */
+ workctx.prec = aa.digits - bb.digits + 1 + 3;
+ /* we get the reciprocal with precision maxlen(q) + 3 */
+ _mpd_qreciprocal(rr, &bb, &workctx, &workctx.status);
+
+ mpd_qmul(qq, &aa, rr, &workctx, &workctx.status);
+ mpd_qfloor(qq, qq, &workctx, &workctx.status);
+
+ workctx.prec = aa.digits + 3;
+ /* get the remainder */
+ mpd_qmul(rr, &bb, qq, &workctx, &workctx.status);
+ mpd_qsub(rr, &aa, rr, &workctx, &workctx.status);
+
+ /* Fix the result. Algorithm from: Karl Hasselstrom, Fast Division of Large Integers */
+ for (k = 0;; k++) {
+ if (k > 2) {
+ mpd_err_warn("_mpd_barrett_divmod: k > 2 in correcting loop");
+ abort(); /* debug */
+ }
+ else if (_mpd_cmp(&zero, rr) == 1) {
+ mpd_qadd(rr, rr, &bb, &workctx, &workctx.status);
+ mpd_qadd(qq, qq, &minus_one, &workctx, &workctx.status);
+ }
+ else if (_mpd_cmp(rr, &bb) == -1) {
+ break;
+ }
+ else {
+ mpd_qsub(rr, rr, &bb, &workctx, &workctx.status);
+ mpd_qadd(qq, qq, &one, &workctx, &workctx.status);
+ }
+ }
+
+ if (qq != q) {
+ mpd_qcopy(q, qq, status);
+ mpd_del(qq);
+ }
+ if (rr != r) {
+ mpd_qcopy(r, rr, status);
+ mpd_del(rr);
+ }
+
+ *status |= (workctx.status&MPD_Errors);
+ return;
+
+
+nanresult:
+ if (qq) mpd_del(qq);
+ if (rr) mpd_del(rr);
+ mpd_seterror(q, MPD_Malloc_error, status);
+ mpd_setspecial(r, MPD_POS, MPD_NAN);
+}
+
+static inline int
+invroot_schedule_prec(mpd_ssize_t klist[MPD_MAX_PREC_LOG2], mpd_ssize_t maxprec, mpd_ssize_t initprec)
+{
+ mpd_ssize_t k;
+ int i;
+
+ assert(maxprec >= 3 && initprec >= 3);
+ if (maxprec <= initprec) return -1;
+
+ i = 0; k = maxprec;
+ do {
+ k = (k+3) / 2;
+ klist[i++] = k;
+ } while (k > initprec);
+
+ return i-1;
+}
+
+/*
+ * Initial approximation for the inverse square root.
+ *
+ * Input:
+ * v := 7 or 8 decimal digits with an implicit exponent of 10**-6,
+ * representing a number 1 <= x < 100.
+ *
+ * Output:
+ * An approximation to 1/sqrt(v)
+ */
+static inline void
+_invroot_init_approx(mpd_t *z, mpd_uint_t v)
+{
+ mpd_uint_t lo = 1000;
+ mpd_uint_t hi = 10000;
+ mpd_uint_t a, sq;
+
+ assert(v >= lo*lo && v < (hi+1)*(hi+1));
+
+ for(;;) {
+ a = (lo + hi) / 2;
+ sq = a * a;
+ if (v >= sq) {
+ if (v < sq + 2*a + 1) {
+ break;
+ }
+ lo = a + 1;
+ }
+ else {
+ hi = a - 1;
+ }
+ }
+
+ /* At this point a/1000 is an approximation to sqrt(v). */
+ mpd_minalloc(z);
+ mpd_clear_flags(z);
+ z->data[0] = 1000000000UL / a;
+ z->len = 1;
+ z->exp = -6;
+ mpd_setdigits(z);
+}
+
+static void
+_mpd_qinvroot(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+ uint32_t workstatus = 0;
+ mpd_context_t varcontext, maxcontext;
+ mpd_t *z = result; /* z: current approximation */
+ mpd_t *v; /* v: a, normalized to a number between 1 and 100 */
+ MPD_NEW_SHARED(vtmp, a); /* by default v will share data with a */
+ MPD_NEW_STATIC(s,0,0,0,0); /* temporary variable */
+ MPD_NEW_STATIC(t,0,0,0,0); /* temporary variable */
+ MPD_NEW_CONST(one_half,0,-1,1,1,1,5);
+ MPD_NEW_CONST(three,0,0,1,1,1,3);
+ mpd_ssize_t klist[MPD_MAX_PREC_LOG2];
+ mpd_ssize_t ideal_exp, shift;
+ mpd_ssize_t adj, tz;
+ mpd_ssize_t maxprec, fracdigits;
+ mpd_uint_t x, dummy;
+ int i, n;
+
+
+ ideal_exp = -(a->exp - (a->exp & 1)) / 2;
+
+ v = &vtmp;
+ if (result == a) {
+ if ((v = mpd_qncopy(a)) == NULL) {
+ goto finish;
+ }
+ }
+
+ /* normalize a to 1 <= v < 100 */
+ if ((v->digits+v->exp) & 1) {
+ fracdigits = v->digits - 1;
+ v->exp = -fracdigits;
+ n = (v->digits > 7) ? 7 : (int)v->digits;
+ _mpd_get_msdigits(&dummy, &x, v, n);
+ if (n < 7) {
+ x *= mpd_pow10[7-n];
+ }
+ }
+ else {
+ fracdigits = v->digits - 2;
+ v->exp = -fracdigits;
+ n = (v->digits > 8) ? 8 : (int)v->digits;
+ _mpd_get_msdigits(&dummy, &x, v, n);
+ if (n < 8) {
+ x *= mpd_pow10[8-n];
+ }
+ }
+ adj = (a->exp-v->exp) / 2;
+
+ /* initial approximation */
+ _invroot_init_approx(z, x);
+
+ mpd_maxcontext(&maxcontext);
+ mpd_maxcontext(&varcontext);
+ varcontext.round = MPD_ROUND_TRUNC;
+ maxprec = ctx->prec + 2;
+
+ i = invroot_schedule_prec(klist, maxprec, 3);
+ for (; i >= 0; i--) {
+ varcontext.prec = 2*klist[i]+2;
+ mpd_qmul(&s, z, z, &maxcontext, &workstatus);
+ if (v->digits > varcontext.prec) {
+ shift = v->digits - varcontext.prec;
+ mpd_qshiftr(&t, v, shift, &workstatus);
+ t.exp += shift;
+ mpd_qmul(&t, &t, &s, &varcontext, &workstatus);
+ }
+ else {
+ mpd_qmul(&t, v, &s, &varcontext, &workstatus);
+ }
+ mpd_qsub(&t, &three, &t, &maxcontext, &workstatus);
+ mpd_qmul(z, z, &t, &varcontext, &workstatus);
+ mpd_qmul(z, z, &one_half, &maxcontext, &workstatus);
+ }
+
+ z->exp -= adj;
+
+ tz = mpd_trail_zeros(result);
+ shift = ideal_exp - result->exp;
+ shift = (tz > shift) ? shift : tz;
+ if (shift > 0) {
+ mpd_qshiftr_inplace(result, shift);
+ result->exp += shift;
+ }
+
+
+finish:
+ mpd_del(&s);
+ mpd_del(&t);
+ if (v != &vtmp) mpd_del(v);
+ *status |= (workstatus&MPD_Errors);
+ varcontext = *ctx;
+ varcontext.round = MPD_ROUND_HALF_EVEN;
+ mpd_qfinalize(result, &varcontext, status);
+}
+
+void
+mpd_qinvroot(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
+ uint32_t *status)
+{
+
+ if (mpd_isspecial(a)) {
+ if (mpd_qcheck_nan(result, a, ctx, status)) {
+ return;
+ }
+ if (mpd_isnegative(a)) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+ /* positive infinity */
+ _settriple(result, MPD_POS, 0, mpd_etiny(ctx));
+ *status |= MPD_Clamped;
+ return;
+ }
+ if (mpd_iszero(a)) {
+ mpd_setspecial(result, mpd_sign(a), MPD_INF);
+ *status |= MPD_Division_by_zero;
+ return;
+ }
+ if (mpd_isnegative(a)) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+
+ _mpd_qinvroot(result, a, ctx, status);
+}
+
+/*
+ * Ensure correct rounding. Algorithm after Hull & Abrham, "Properly Rounded
+ * Variable Precision Square Root", ACM Transactions on Mathematical Software,
+ * Vol. 11, No. 3.
+ */
+static void
+_mpd_fix_sqrt(mpd_t *result, const mpd_t *a, mpd_t *tmp,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_context_t maxctx;
+ MPD_NEW_CONST(u,0,0,1,1,1,5);
+
+ mpd_maxcontext(&maxctx);
+ u.exp = u.digits - ctx->prec + result->exp - 1;
+
+ _mpd_qsub(tmp, result, &u, &maxctx, status);
+ _mpd_qmul(tmp, tmp, tmp, &maxctx, status);
+ if (_mpd_cmp(tmp, a) == 1) {
+ u.exp += 1;
+ u.data[0] = 1;
+ _mpd_qsub(result, result, &u, &maxctx, status);
+ }
+ else {
+ _mpd_qadd(tmp, result, &u, &maxctx, status);
+ _mpd_qmul(tmp, tmp, tmp, &maxctx, status);
+ if (_mpd_cmp(tmp, a) == -1) {
+ u.exp += 1;
+ u.data[0] = 1;
+ _mpd_qadd(result, result, &u, &maxctx, status);
+ }
+ }
+}
+
+void
+mpd_qsqrt(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status)
+{
+ uint32_t workstatus = 0;
+ mpd_context_t varcontext;
+ mpd_t *z = result; /* z: current approximation */
+ MPD_NEW_STATIC(v,0,0,0,0); /* v: a, normalized to a number between 1 and 10 */
+ MPD_NEW_STATIC(vtmp,0,0,0,0);
+ MPD_NEW_STATIC(tmp,0,0,0,0);
+ MPD_NEW_STATIC(aa,0,0,0,0);
+ mpd_ssize_t ideal_exp, shift;
+ mpd_ssize_t target_prec, fracdigits;
+ mpd_ssize_t adj, tz;
+ mpd_uint_t dummy, t;
+ int exact = 0;
+
+
+ varcontext = *ctx;
+ varcontext.round = MPD_ROUND_HALF_EVEN;
+ ideal_exp = (a->exp - (a->exp & 1)) / 2;
+
+ if (mpd_isspecial(a)) {
+ if (mpd_qcheck_nan(result, a, ctx, status)) {
+ return;
+ }
+ if (mpd_isnegative(a)) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+ mpd_setspecial(result, MPD_POS, MPD_INF);
+ return;
+ }
+ if (mpd_iszero(a)) {
+ _settriple(result, mpd_sign(a), 0, ideal_exp);
+ mpd_qfinalize(result, ctx, status);
+ return;
+ }
+ if (mpd_isnegative(a)) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ return;
+ }
+
+ if (!mpd_qcopy(&v, a, status)) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ goto finish;
+ }
+ if (result == a) {
+ if (!mpd_qcopy(&aa, a, status)) {
+ mpd_seterror(result, MPD_Invalid_operation, status);
+ goto finish;
+ }
+ a = &aa;
+ }
+
+ /* normalize a to 1 <= v < 100 */
+ if ((v.digits+v.exp) & 1) {
+ fracdigits = v.digits - 1;
+ v.exp = -fracdigits;
+ _mpd_get_msdigits(&dummy, &t, &v, 3);
+ t = t < 100 ? t*10 : t;
+ t = t < 100 ? t*10 : t;
+ }
+ else {
+ fracdigits = v.digits - 2;
+ v.exp = -fracdigits;
+ _mpd_get_msdigits(&dummy, &t, &v, 4);
+ t = t < 1000 ? t*10 : t;
+ t = t < 1000 ? t*10 : t;
+ t = t < 1000 ? t*10 : t;
+ }
+ adj = (a->exp-v.exp) / 2;
+
+
+ /* use excess digits */
+ target_prec = (a->digits > ctx->prec) ? a->digits : ctx->prec;
+ target_prec += 2;
+ varcontext.prec = target_prec + 3;
+
+ /* invroot is much faster for large numbers */
+ _mpd_qinvroot(&tmp, &v, &varcontext, &workstatus);
+
+ varcontext.prec = target_prec;
+ _mpd_qdiv(NO_IDEAL_EXP, z, &one, &tmp, &varcontext, &workstatus);
+
+
+ tz = mpd_trail_zeros(result);
+ if ((result->digits-tz)*2-1 <= v.digits) {
+ _mpd_qmul(&tmp, result, result, &varcontext, &workstatus);
+ exact = (_mpd_cmp(&tmp, &v) == 0);
+ }
+ *status |= (workstatus&MPD_Errors);
+
+ if (!exact && !mpd_isspecial(result) && !mpd_iszero(result)) {
+ _mpd_fix_sqrt(result, &v, &tmp, &varcontext, status);
+ *status |= (MPD_Rounded|MPD_Inexact);
+ }
+
+ result->exp += adj;
+ if (exact) {
+ shift = ideal_exp - result->exp;
+ shift = (tz > shift) ? shift : tz;
+ if (shift > 0) {
+ mpd_qshiftr_inplace(result, shift);
+ result->exp += shift;
+ }
+ }
+
+
+finish:
+ mpd_del(&v);
+ mpd_del(&vtmp);
+ mpd_del(&tmp);
+ varcontext.prec = ctx->prec;
+ mpd_qfinalize(result, &varcontext, status);
+}
+
+
+/******************************************************************************/
+/* Base conversions */
+/******************************************************************************/
+
+/*
+ * Returns the space needed to represent an integer mpd_t in base 'base'.
+ * The result is undefined for non-integers.
+ *
+ * Max space needed:
+ *
+ * base^n >= 10^(digits+exp)
+ * n >= log10(10^(digits+exp))/log10(base) = (digits+exp) / log10(base)
+ */
+size_t
+mpd_sizeinbase(mpd_t *a, uint32_t base)
+{
+ size_t x;
+
+ assert(mpd_isinteger(a));
+ if (mpd_iszero(a)) {
+ return 1;
+ }
+
+ x = a->digits+a->exp;
+
+#ifdef CONFIG_64
+ #if defined(__x86_64__) && defined(HAVE_80BIT_LONG_DOUBLE)
+ return (long double)x / log10(base) + 3;
+ #else
+ /* x > floor(((1ULL<<53)-3) * log10(2)) */
+ if (x > 2711437152599294ULL) {
+ return SIZE_MAX;
+ }
+ return (double)x / log10(base) + 3;
+ #endif
+#else /* CONFIG_32 */
+{
+ double y = x / log10(base) + 3;
+ return (y > SIZE_MAX) ? SIZE_MAX : y;
+}
+#endif
+}
+
+/*
+ * Returns the space needed to import a base 'base' integer of length 'srclen'.
+ */
+static inline size_t
+_mpd_importsize(size_t srclen, uint32_t base)
+{
+#ifdef CONFIG_64
+ #if defined(__x86_64__) && defined(HAVE_80BIT_LONG_DOUBLE)
+ return (long double)srclen * (log10(base)/MPD_RDIGITS) + 3;
+ #else
+ if (srclen > (1ULL<<53)) {
+ return SIZE_MAX;
+ }
+ return (double)srclen * (log10(base)/MPD_RDIGITS) + 3;
+ #endif
+#else /* CONFIG_32 */
+{
+ double x = srclen * (log10(base) / MPD_RDIGITS) + 3;
+ return (x > SIZE_MAX) ? SIZE_MAX : x;
+}
+#endif
+}
+
+
+static inline size_t
+_to_base_u16(uint16_t *w, size_t wlen, mpd_uint_t base, mpd_uint_t *u, mpd_ssize_t ulen)
+{
+ size_t n = 0;
+
+ assert(wlen > 0 && ulen > 0);
+
+ do {
+ w[n++] = (uint16_t)_mpd_shortdiv(u, u, ulen, base);
+ /* ulen will be at least 1. u[ulen-1] can only be zero if ulen == 1 */
+ ulen = _mpd_real_size(u, ulen);
+
+ } while (u[ulen-1] != 0 && n < wlen);
+
+ /* proper termination condition */
+ assert(u[ulen-1] == 0);
+
+ return n;
+}
+
+static inline void
+_from_base_u16(mpd_uint_t *w, size_t wlen, const mpd_uint_t *u, size_t ulen, uint16_t base)
+{
+ size_t m = 1;
+ mpd_uint_t carry;
+
+ assert(wlen > 0 && ulen > 0);
+
+ w[0] = u[--ulen];
+ while (--ulen != SIZE_MAX && m < wlen) {
+ _mpd_shortmul(w, w, m, base);
+ m = _mpd_real_size(w, m+1);
+ carry = _mpd_shortadd(w, m, u[ulen]);
+ if (carry) w[m++] = carry;
+ }
+
+ /* proper termination condition */
+ assert(ulen == SIZE_MAX);
+}
+
+/* target base wbase <= source base ubase */
+static inline size_t
+_baseconv_to_smaller(uint32_t *w, size_t wlen, mpd_uint_t wbase,
+ mpd_uint_t *u, size_t ulen, mpd_uint_t ubase)
+{
+ size_t n = 0;
+
+ assert(wlen > 0 && ulen > 0);
+
+ do {
+ w[n++] = (uint32_t)_mpd_shortdiv_b(u, u, ulen, wbase, ubase);
+ /* ulen will be at least 1. u[ulen-1] can only be zero if ulen == 1 */
+ ulen = _mpd_real_size(u, ulen);
+
+ } while (u[ulen-1] != 0 && n < wlen);
+
+ /* proper termination condition */
+ assert(u[ulen-1] == 0);
+
+ return n;
+}
+
+/* target base wbase >= source base ubase */
+static inline void
+_baseconv_to_larger(mpd_uint_t *w, size_t wlen, mpd_uint_t wbase,
+ const mpd_uint_t *u, size_t ulen, mpd_uint_t ubase)
+{
+ size_t m = 1;
+ mpd_uint_t carry;
+
+ assert(wlen > 0 && ulen > 0);
+
+ w[0] = u[--ulen];
+ while (--ulen != SIZE_MAX && m < wlen) {
+ _mpd_shortmul_b(w, w, m, ubase, wbase);
+ m = _mpd_real_size(w, m+1);
+ carry = _mpd_shortadd_b(w, m, u[ulen], wbase);
+ if (carry) w[m++] = carry;
+ }
+
+ /* proper termination condition */
+ assert(ulen == SIZE_MAX);
+}
+
+
+/*
+ * Converts an integer mpd_t to a multiprecision integer with base <= UINT16_MAX+1.
+ * The least significant word of the result is rdata[0].
+ */
+size_t
+mpd_qexport_u16(uint16_t *rdata, size_t rlen, uint32_t base, const mpd_t *src,
+ uint32_t *status)
+{
+ mpd_t *tsrc;
+ size_t n;
+
+ assert(base <= (1U<<16));
+
+ if (mpd_isspecial(src) || !_mpd_isint(src)) {
+ *status |= MPD_Invalid_operation;
+ return SIZE_MAX;
+ }
+
+ memset(rdata, 0, mul_size_t(rlen, sizeof *rdata));
+
+ if (mpd_iszero(src)) {
+ return 1;
+ }
+
+ if ((tsrc = mpd_qnew()) == NULL) {
+ *status |= MPD_Malloc_error;
+ return SIZE_MAX;
+ }
+
+ if (src->exp >= 0) {
+ if (!mpd_qshiftl(tsrc, src, src->exp, status)) {
+ return SIZE_MAX;
+ }
+ }
+ else {
+ if (mpd_qshiftr(tsrc, src, -src->exp, status) == MPD_UINT_MAX) {
+ return SIZE_MAX;
+ }
+ }
+
+ n = _to_base_u16(rdata, rlen, base, tsrc->data, tsrc->len);
+
+ mpd_del(tsrc);
+ return n;
+}
+
+/*
+ * Converts an integer mpd_t to a multiprecision integer with base <= UINT32_MAX.
+ * The least significant word of the result is rdata[0].
+ */
+size_t
+mpd_qexport_u32(uint32_t *rdata, size_t rlen, uint32_t base, const mpd_t *src,
+ uint32_t *status)
+{
+ mpd_t *tsrc;
+ size_t n;
+
+ if (mpd_isspecial(src) || !_mpd_isint(src)) {
+ *status |= MPD_Invalid_operation;
+ return SIZE_MAX;
+ }
+
+ memset(rdata, 0, mul_size_t(rlen, sizeof *rdata));
+
+ if (mpd_iszero(src)) {
+ return 1;
+ }
+
+ if ((tsrc = mpd_qnew()) == NULL) {
+ *status |= MPD_Malloc_error;
+ return SIZE_MAX;
+ }
+
+ if (src->exp >= 0) {
+ if (!mpd_qshiftl(tsrc, src, src->exp, status)) {
+ return SIZE_MAX;
+ }
+ }
+ else {
+ if (mpd_qshiftr(tsrc, src, -src->exp, status) == MPD_UINT_MAX) {
+ return SIZE_MAX;
+ }
+ }
+
+#ifdef CONFIG_64
+ n = _baseconv_to_smaller(rdata, rlen, base, tsrc->data, tsrc->len, MPD_RADIX);
+#else
+ if (base <= MPD_RADIX) {
+ n = _baseconv_to_smaller(rdata, rlen, base, tsrc->data, tsrc->len, MPD_RADIX);
+ }
+ else {
+ _baseconv_to_larger(rdata, rlen, base, tsrc->data, tsrc->len, MPD_RADIX);
+ n = _mpd_real_size(rdata, rlen);
+ }
+#endif
+
+ mpd_del(tsrc);
+ return n;
+}
+
+
+/*
+ * Converts a multiprecision integer with base <= UINT16_MAX+1 to an mpd_t.
+ * The least significant word of the source is srcdata[0].
+ */
+int
+mpd_qimport_u16(mpd_t *result, const uint16_t *srcdata, size_t srclen,
+ uint8_t srcsign, uint32_t base,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_uint_t *usrc; /* uint16_t src copied to an mpd_uint_t array */
+ size_t rlen; /* length of the result */
+ size_t n = 0;
+
+ assert(srclen > 0);
+ assert(base <= (1U<<16));
+
+ if ((rlen = _mpd_importsize(srclen, base)) == SIZE_MAX) {
+ mpd_seterror(result, MPD_Malloc_error, status);
+ return 0;
+ }
+
+ if ((usrc = mpd_alloc(srclen, sizeof *usrc)) == NULL) {
+ mpd_seterror(result, MPD_Malloc_error, status);
+ return 0;
+ }
+ for (n = 0; n < srclen; n++) {
+ usrc[n] = srcdata[n];
+ }
+
+ /* result->data is initialized to zero */
+ if (!mpd_qresize_zero(result, rlen, status)) {
+ goto finish;
+ }
+
+ _from_base_u16(result->data, rlen, usrc, srclen, base);
+
+ mpd_set_flags(result, srcsign);
+ result->exp = 0;
+ result->len = _mpd_real_size(result->data, rlen);
+ mpd_setdigits(result);
+
+ mpd_qresize(result, result->len, status);
+ mpd_qfinalize(result, ctx, status);
+
+finish:
+ mpd_free(usrc);
+ return 1;
+}
+
+/*
+ * Converts a multiprecision integer with base <= UINT32_MAX to an mpd_t.
+ * The least significant word of the source is srcdata[0].
+ */
+int
+mpd_qimport_u32(mpd_t *result, const uint32_t *srcdata, size_t srclen,
+ uint8_t srcsign, uint32_t base,
+ const mpd_context_t *ctx, uint32_t *status)
+{
+ mpd_uint_t *usrc; /* uint32_t src copied to an mpd_uint_t array */
+ size_t rlen; /* length of the result */
+ size_t n = 0;
+
+ assert(srclen > 0);
+
+ if ((rlen = _mpd_importsize(srclen, base)) == SIZE_MAX) {
+ mpd_seterror(result, MPD_Malloc_error, status);
+ return 0;
+ }
+
+ if ((usrc = mpd_alloc(srclen, sizeof *usrc)) == NULL) {
+ mpd_seterror(result, MPD_Malloc_error, status);
+ return 0;
+ }
+ for (n = 0; n < srclen; n++) {
+ usrc[n] = srcdata[n];
+ }
+
+ /* result->data is initialized to zero */
+ if (!mpd_qresize_zero(result, rlen, status)) {
+ goto finish;
+ }
+
+#ifdef CONFIG_64
+ _baseconv_to_larger(result->data, rlen, MPD_RADIX, usrc, srclen, base);
+#else
+ if (base <= MPD_RADIX) {
+ _baseconv_to_larger(result->data, rlen, MPD_RADIX, usrc, srclen, base);
+ }
+ else {
+ _baseconv_to_smaller(result->data, rlen, MPD_RADIX, usrc, srclen, base);
+ }
+#endif
+
+ mpd_set_flags(result, srcsign);
+ result->exp = 0;
+ result->len = _mpd_real_size(result->data, rlen);
+ mpd_setdigits(result);
+
+ mpd_qresize(result, result->len, status);
+ mpd_qfinalize(result, ctx, status);
+
+finish:
+ mpd_free(usrc);
+ return 1;
+}
+
+
+
Added: python/branches/py3k-cdecimal/Modules/cdecimal/mpdecimal.h
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/mpdecimal.h Thu Jan 7 13:02:51 2010
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#ifndef MPDECIMAL_H
+#define MPDECIMAL_H
+
+#if defined(CONFIG_64)
+ #include "mpdecimal64.h"
+#elif defined(CONFIG_32)
+ #include "mpdecimal32.h"
+#else
+ #error "define CONFIG_64 or CONFIG_32"
+#endif
+
+
+#endif
Added: python/branches/py3k-cdecimal/Modules/cdecimal/mpdecimal32.h
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/mpdecimal32.h Thu Jan 7 13:02:51 2010
@@ -0,0 +1,522 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#ifndef MPDECIMAL32_H
+#define MPDECIMAL32_H
+
+
+#ifdef __cplusplus
+extern "C" {
+#define __STDC_LIMIT_MACROS
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <limits.h>
+#include <assert.h>
+
+
+#define EXTINLINE
+#ifdef _MSC_VER
+ #include "vccompat.h"
+ #ifndef UNUSED
+ #define UNUSED
+ #endif
+ #undef EXTINLINE
+ #define EXTINLINE extern inline
+#else
+ #include <stdint.h>
+ #define __GNUC_STDC_INLINE__
+ #define UNUSED __attribute__((unused))
+#endif
+
+
+/******************************************************************************/
+/* Types for 32 bit architectures */
+/******************************************************************************/
+
+/* types for modular and base arithmetic */
+#define MPD_UINT_MAX UINT32_MAX
+#define MPD_UUINT_MAX UINT64_MAX
+#define MPD_BITS_PER_UINT 32
+typedef uint32_t mpd_uint_t; /* unsigned mod type */
+typedef uint64_t mpd_uuint_t; /* double width unsigned mod type */
+
+/* type for dec->len, dec->exp, ctx->prec */
+#define MPD_SSIZE_MAX INT32_MAX
+#define MPD_SSIZE_MIN INT32_MIN
+typedef int32_t mpd_ssize_t;
+#define mpd_strtossize strtol
+
+/* decimal arithmetic */
+#define MPD_RADIX 1000000000UL /* 10**9 */
+#define MPD_RDIGITS 9
+#define MPD_MAX_POW10 9
+#define MPD_EXPDIGITS 10 /* MPD_EXPDIGITS <= MPD_RDIGITS+1 */
+
+#define MPD_MAXTRANSFORM_2N 33554432UL /* 2**25 */
+#define MPD_MAX_PREC 425000000L
+#define MPD_MAX_PREC_LOG2 32
+#define MPD_ELIMIT 425000001L
+#define MPD_MAX_EMAX 425000000L /* ELIMIT-1 */
+#define MPD_MIN_EMIN (-425000000L) /* -EMAX */
+#define MPD_MIN_ETINY (MPD_MIN_EMIN-(MPD_MAX_PREC-1))
+#define MPD_EXP_INF 1000000001L /* allows for emax=999999999 in the tests */
+#define MPD_EXP_CLAMP (-2000000001L) /* allows for emin=-999999999 in the tests */
+
+
+#if SIZE_MAX < MPD_SSIZE_MAX
+ #error "unsupported platform: need size_t >= mpd_ssize_t"
+#endif
+#if MPD_SSIZE_MAX > MPD_UINT_MAX
+ #error "unsupported platform: need mpd_ssize_t <= mpd_uint_t"
+#endif
+
+
+/******************************************************************************/
+/* Context */
+/******************************************************************************/
+
+enum {
+ MPD_ROUND_UP, /* round away from 0 */
+ MPD_ROUND_DOWN, /* round toward 0 (truncate) */
+ MPD_ROUND_CEILING, /* round toward +infinity */
+ MPD_ROUND_FLOOR, /* round toward -infinity */
+ MPD_ROUND_HALF_UP, /* 0.5 is rounded up */
+ MPD_ROUND_HALF_DOWN, /* 0.5 is rounded down */
+ MPD_ROUND_HALF_EVEN, /* 0.5 is rounded to even */
+ MPD_ROUND_05UP, /* round zero or five away from 0 */
+ MPD_ROUND_TRUNC, /* truncate, but set infinity */
+ MPD_ROUND_GUARD
+};
+
+enum { MPD_CLAMP_DEFAULT, MPD_CLAMP_IEEE_754, MPD_CLAMP_GUARD };
+
+extern const char *mpd_round_string[MPD_ROUND_GUARD];
+extern const char *mpd_clamp_string[MPD_CLAMP_GUARD];
+
+
+typedef struct {
+ mpd_ssize_t prec; /* precision */
+ mpd_ssize_t emax; /* max positive exp */
+ mpd_ssize_t emin; /* min negative exp */
+ uint32_t traps; /* status events that should be trapped */
+ uint32_t status; /* status flags */
+ uint32_t newtrap; /* set by mpd_addstatus_raise() */
+ int round; /* rounding mode */
+ int clamp; /* clamp mode */
+ int allcr; /* all functions correctly rounded */
+} mpd_context_t;
+
+
+/* Status flags */
+#define MPD_Clamped 0x00000001U
+#define MPD_Conversion_syntax 0x00000002U
+#define MPD_Division_by_zero 0x00000004U
+#define MPD_Division_impossible 0x00000008U
+#define MPD_Division_undefined 0x00000010U
+#define MPD_Fpu_error 0x00000020U
+#define MPD_Inexact 0x00000040U
+#define MPD_Invalid_context 0x00000080U
+#define MPD_Invalid_operation 0x00000100U
+#define MPD_Malloc_error 0x00000200U
+#define MPD_Not_implemented 0x00000400U
+#define MPD_Overflow 0x00000800U
+#define MPD_Rounded 0x00001000U
+#define MPD_Subnormal 0x00002000U
+#define MPD_Underflow 0x00004000U
+#define MPD_Max_status (0x00008000U-1U)
+
+/* Conditions that result in an IEEE 754 exception */
+#define MPD_IEEE_Invalid_operation (MPD_Conversion_syntax | \
+ MPD_Division_impossible | \
+ MPD_Division_undefined | \
+ MPD_Fpu_error | \
+ MPD_Invalid_context | \
+ MPD_Invalid_operation | \
+ MPD_Malloc_error) \
+
+/* Errors that require the result of an operation to be set to NaN */
+#define MPD_Errors (MPD_IEEE_Invalid_operation | \
+ MPD_Division_by_zero)
+
+/* Default traps */
+#define MPD_Traps (MPD_IEEE_Invalid_operation | \
+ MPD_Division_by_zero | \
+ MPD_Overflow | \
+ MPD_Underflow)
+
+/* Official name */
+#define MPD_Insufficient_storage MPD_Malloc_error
+
+
+#define MPD_MINALLOC_MIN 2
+#define MPD_MINALLOC_MAX 64
+extern mpd_ssize_t MPD_MINALLOC;
+extern void (* mpd_traphandler)(mpd_context_t *);
+
+void mpd_init(mpd_context_t *ctx, mpd_ssize_t prec);
+
+void mpd_maxcontext(mpd_context_t *ctx);
+void mpd_defaultcontext(mpd_context_t *ctx);
+void mpd_basiccontext(mpd_context_t *ctx);
+void mpd_extcontext(mpd_context_t *ctx);
+
+mpd_ssize_t mpd_getprec(const mpd_context_t *ctx);
+mpd_ssize_t mpd_getemax(const mpd_context_t *ctx);
+mpd_ssize_t mpd_getemin(const mpd_context_t *ctx);
+int mpd_getround(const mpd_context_t *ctx);
+uint32_t mpd_gettraps(const mpd_context_t *ctx);
+uint32_t mpd_getstatus(const mpd_context_t *ctx);
+int mpd_getclamp(const mpd_context_t *ctx);
+int mpd_getcr(const mpd_context_t *ctx);
+
+int mpd_qsetprec(mpd_context_t *ctx, mpd_ssize_t prec);
+int mpd_qsetemax(mpd_context_t *ctx, mpd_ssize_t emax);
+int mpd_qsetemin(mpd_context_t *ctx, mpd_ssize_t emin);
+int mpd_qsetround(mpd_context_t *ctx, int newround);
+int mpd_qsettraps(mpd_context_t *ctx, uint32_t flags);
+int mpd_qsetstatus(mpd_context_t *ctx, uint32_t flags);
+int mpd_qsetclamp(mpd_context_t *ctx, int c);
+int mpd_qsetcr(mpd_context_t *ctx, int c);
+void mpd_addstatus_raise(mpd_context_t *ctx, uint32_t flags);
+
+
+/******************************************************************************/
+/* Decimal Arithmetic */
+/******************************************************************************/
+
+/* mpd_t flags */
+#define MPD_POS ((uint8_t)0)
+#define MPD_NEG ((uint8_t)1)
+#define MPD_INF ((uint8_t)2)
+#define MPD_NAN ((uint8_t)4)
+#define MPD_SNAN ((uint8_t)8)
+#define MPD_SPECIAL (MPD_INF|MPD_NAN|MPD_SNAN)
+#define MPD_STATIC ((uint8_t)16)
+#define MPD_STATIC_DATA ((uint8_t)32)
+#define MPD_SHARED_DATA ((uint8_t)64)
+#define MPD_CONST_DATA ((uint8_t)128)
+#define MPD_DATAFLAGS (MPD_STATIC_DATA|MPD_SHARED_DATA|MPD_CONST_DATA)
+
+/* mpd_t */
+typedef struct {
+ uint8_t flags;
+ mpd_ssize_t exp;
+ mpd_ssize_t digits;
+ mpd_ssize_t len;
+ mpd_ssize_t alloc;
+ mpd_uint_t *data;
+} mpd_t;
+
+
+typedef unsigned char uchar;
+extern mpd_t mpd_ln10;
+
+
+/******************************************************************************/
+/* Quiet, thread-safe functions */
+/******************************************************************************/
+
+/* format specification */
+typedef struct {
+ mpd_ssize_t min_width; /* minimum field width */
+ mpd_ssize_t prec; /* fraction digits or significant digits */
+ char type; /* conversion specifier */
+ char align; /* alignment */
+ char sign; /* sign printing/alignment */
+ char fill[5]; /* fill character */
+ const char *dot; /* decimal point */
+ const char *sep; /* thousands separator */
+ const char *grouping; /* grouping of digits */
+} mpd_spec_t;
+
+/* output to a string */
+char *mpd_to_sci(const mpd_t *dec, int fmt);
+char *mpd_to_eng(const mpd_t *dec, int fmt);
+int mpd_parse_fmt_str(mpd_spec_t *spec, const char *fmt);
+char * mpd_qformat_spec(const mpd_t *dec, mpd_spec_t *spec, const mpd_context_t *ctx, uint32_t *status);
+char *mpd_qformat(const mpd_t *dec, const char *fmt, const mpd_context_t *ctx, uint32_t *status);
+
+#define MPD_NUM_FLAGS 15
+#define MPD_MAX_FLAG_STRING 208
+#define MPD_MAX_FLAG_LIST (MPD_MAX_FLAG_STRING+18)
+#define MPD_MAX_SIGNAL_LIST 121
+int mpd_snprint_flags(char *dest, int nmemb, uint32_t flags);
+int mpd_lsnprint_flags(char *dest, int nmemb, uint32_t flags, const char *flag_string[]);
+int mpd_lsnprint_signals(char *dest, int nmemb, uint32_t flags, const char *signal_string[]);
+
+/* output to a file */
+void mpd_fprint(FILE *file, const mpd_t *dec);
+void mpd_print(const mpd_t *dec);
+
+/* assignment from a string */
+void mpd_qset_string(mpd_t *dec, const char *s, const mpd_context_t *ctx, uint32_t *status);
+
+/* set to NaN with error flags */
+void mpd_seterror(mpd_t *result, uint32_t flags, uint32_t *status);
+/* set a special with sign and type */
+void mpd_setspecial(mpd_t *dec, uint8_t sign, uint8_t type);
+/* set coefficient to zero or all nines */
+void mpd_zerocoeff(mpd_t *result);
+void mpd_qmaxcoeff(mpd_t *result, const mpd_context_t *ctx, uint32_t *status);
+
+/* quietly assign a C integer type to an mpd_t */
+void mpd_qset_ssize(mpd_t *result, mpd_ssize_t a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qset_i32(mpd_t *result, int32_t a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qset_uint(mpd_t *result, mpd_uint_t a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qset_u32(mpd_t *result, uint32_t a, const mpd_context_t *ctx, uint32_t *status);
+
+/* quietly assign a C integer type to an mpd_t with a static coefficient */
+void mpd_qsset_ssize(mpd_t *result, mpd_ssize_t a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qsset_i32(mpd_t *result, int32_t a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qsset_uint(mpd_t *result, mpd_uint_t a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qsset_u32(mpd_t *result, uint32_t a, const mpd_context_t *ctx, uint32_t *status);
+
+/* quietly get a C integer type from an mpd_t */
+mpd_ssize_t mpd_qget_ssize(const mpd_t *dec, uint32_t *status);
+int32_t mpd_qget_i32(const mpd_t *dec, uint32_t *status);
+mpd_uint_t mpd_qget_uint(const mpd_t *dec, uint32_t *status);
+uint32_t mpd_qget_u32(const mpd_t *dec, uint32_t *status);
+
+
+/* quiet functions */
+int mpd_qcheck_nan(mpd_t *nanresult, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+int mpd_qcheck_nans(mpd_t *nanresult, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qfinalize(mpd_t *result, const mpd_context_t *ctx, uint32_t *status);
+
+const char * mpd_class(const mpd_t *a, const mpd_context_t *ctx);
+
+int mpd_qcopy(mpd_t *result, const mpd_t *a, uint32_t *status);
+mpd_t *mpd_qncopy(const mpd_t *a);
+int mpd_qcopy_abs(mpd_t *result, const mpd_t *a, uint32_t *status);
+int mpd_qcopy_negate(mpd_t *result, const mpd_t *a, uint32_t *status);
+int mpd_qcopy_sign(mpd_t *result, const mpd_t *a, const mpd_t *b, uint32_t *status);
+
+void mpd_qand(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qinvert(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qlogb(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qor(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qscaleb(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qxor(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+int mpd_same_quantum(const mpd_t *a, const mpd_t *b);
+
+void mpd_qrotate(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+int mpd_qshiftl(mpd_t *result, const mpd_t *a, mpd_ssize_t n, uint32_t *status);
+mpd_uint_t mpd_qshiftr(mpd_t *result, const mpd_t *a, mpd_ssize_t n, uint32_t *status);
+mpd_uint_t mpd_qshiftr_inplace(mpd_t *result, mpd_ssize_t n);
+void mpd_qshift(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qshiftn(mpd_t *result, const mpd_t *a, mpd_ssize_t n, const mpd_context_t *ctx, uint32_t *status);
+
+int mpd_qcmp(const mpd_t *a, const mpd_t *b, uint32_t *status);
+int mpd_qcompare(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+int mpd_qcompare_signal(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+int mpd_cmp_total(const mpd_t *a, const mpd_t *b);
+int mpd_cmp_total_mag(const mpd_t *a, const mpd_t *b);
+int mpd_compare_total(mpd_t *result, const mpd_t *a, const mpd_t *b);
+int mpd_compare_total_mag(mpd_t *result, const mpd_t *a, const mpd_t *b);
+
+void mpd_qround_to_intx(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qround_to_int(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qfloor(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qceil(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+
+void mpd_qabs(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qmax(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qmax_mag(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qmin(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qmin_mag(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qminus(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qplus(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qnext_minus(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qnext_plus(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qnext_toward(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qquantize(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qrescale(mpd_t *result, const mpd_t *a, mpd_ssize_t exp, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qreduce(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qadd(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qadd_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qadd_i32(mpd_t *result, const mpd_t *a, int32_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qadd_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qadd_u32(mpd_t *result, const mpd_t *a, uint32_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qsub(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qsub_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qsub_i32(mpd_t *result, const mpd_t *a, int32_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qsub_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qsub_u32(mpd_t *result, const mpd_t *a, uint32_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qmul(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qmul_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qmul_i32(mpd_t *result, const mpd_t *a, int32_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qmul_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qmul_u32(mpd_t *result, const mpd_t *a, uint32_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qfma(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_t *c, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qdiv(mpd_t *q, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qdiv_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qdiv_i32(mpd_t *result, const mpd_t *a, int32_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qdiv_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qdiv_u32(mpd_t *result, const mpd_t *a, uint32_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qdivint(mpd_t *q, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qrem(mpd_t *r, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qrem_near(mpd_t *r, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qdivmod(mpd_t *q, mpd_t *r, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qpow(mpd_t *result, const mpd_t *base, const mpd_t *exp, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qpowmod(mpd_t *result, const mpd_t *base, const mpd_t *exp, const mpd_t *mod, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qexp(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_update_ln10(mpd_ssize_t prec, uint32_t *status);
+void mpd_qln(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qlog10(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qsqrt(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qinvroot(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+
+
+size_t mpd_sizeinbase(mpd_t *a, uint32_t base);
+int mpd_qimport_u16(mpd_t *result, const uint16_t *srcdata, size_t srclen,
+ uint8_t srcsign, uint32_t base,
+ const mpd_context_t *ctx, uint32_t *status);
+int mpd_qimport_u32(mpd_t *result, const uint32_t *srcdata, size_t srclen,
+ uint8_t srcsign, uint32_t base,
+ const mpd_context_t *ctx, uint32_t *status);
+size_t mpd_qexport_u16(uint16_t *rdata, size_t rlen, uint32_t base,
+ const mpd_t *src, uint32_t *status);
+size_t mpd_qexport_u32(uint32_t *rdata, size_t rlen, uint32_t base,
+ const mpd_t *src, uint32_t *status);
+
+
+/******************************************************************************/
+/* Get attributes of a decimal */
+/******************************************************************************/
+
+EXTINLINE mpd_ssize_t mpd_adjexp(const mpd_t *dec);
+EXTINLINE mpd_ssize_t mpd_etiny(const mpd_context_t *ctx);
+EXTINLINE mpd_ssize_t mpd_etop(const mpd_context_t *ctx);
+EXTINLINE mpd_uint_t mpd_msword(const mpd_t *dec);
+EXTINLINE int mpd_word_digits(mpd_uint_t word);
+/* most significant digit of a word */
+EXTINLINE mpd_uint_t mpd_msd(mpd_uint_t word);
+/* least significant digit of a word */
+EXTINLINE mpd_uint_t mpd_lsd(mpd_uint_t word);
+/* coefficient size needed to store 'digits' */
+EXTINLINE mpd_ssize_t mpd_digits_to_size(mpd_ssize_t digits);
+/* number of digits in the exponent, undefined for MPD_SSIZE_MIN */
+EXTINLINE int mpd_exp_digits(mpd_ssize_t exp);
+EXTINLINE int mpd_iscanonical(const mpd_t *dec UNUSED);
+EXTINLINE int mpd_isfinite(const mpd_t *dec);
+EXTINLINE int mpd_isinfinite(const mpd_t *dec);
+EXTINLINE int mpd_isinteger(const mpd_t *dec);
+EXTINLINE int mpd_isnan(const mpd_t *dec);
+EXTINLINE int mpd_isnegative(const mpd_t *dec);
+EXTINLINE int mpd_ispositive(const mpd_t *dec);
+EXTINLINE int mpd_isqnan(const mpd_t *dec);
+EXTINLINE int mpd_issigned(const mpd_t *dec);
+EXTINLINE int mpd_issnan(const mpd_t *dec);
+EXTINLINE int mpd_isspecial(const mpd_t *dec);
+EXTINLINE int mpd_iszero(const mpd_t *dec);
+/* undefined for special numbers */
+EXTINLINE int mpd_iszerocoeff(const mpd_t *dec);
+EXTINLINE int mpd_isnormal(const mpd_t *dec, const mpd_context_t *ctx);
+EXTINLINE int mpd_issubnormal(const mpd_t *dec, const mpd_context_t *ctx);
+/* odd word */
+EXTINLINE int mpd_isoddword(mpd_uint_t word);
+/* odd coefficient */
+EXTINLINE int mpd_isoddcoeff(const mpd_t *dec);
+/* odd decimal, only defined for integers */
+int mpd_isodd(const mpd_t *dec);
+/* even decimal, only defined for integers */
+int mpd_iseven(const mpd_t *dec);
+/* 0 if dec is positive, 1 if dec is negative */
+EXTINLINE uint8_t mpd_sign(const mpd_t *dec);
+/* 1 if dec is positive, -1 if dec is negative */
+EXTINLINE int mpd_arith_sign(const mpd_t *dec);
+EXTINLINE long mpd_radix(void);
+EXTINLINE int mpd_isdynamic(mpd_t *dec);
+EXTINLINE int mpd_isstatic(mpd_t *dec);
+EXTINLINE int mpd_isdynamic_data(mpd_t *dec);
+EXTINLINE int mpd_isstatic_data(mpd_t *dec);
+EXTINLINE int mpd_isshared_data(mpd_t *dec);
+EXTINLINE int mpd_isconst_data(mpd_t *dec);
+EXTINLINE mpd_ssize_t mpd_trail_zeros(const mpd_t *dec);
+
+
+/******************************************************************************/
+/* Set attributes of a decimal */
+/******************************************************************************/
+
+/* set number of decimal digits in the coefficient */
+EXTINLINE void mpd_setdigits(mpd_t *result);
+EXTINLINE void mpd_set_sign(mpd_t *result, uint8_t sign);
+/* copy sign from another decimal */
+EXTINLINE void mpd_signcpy(mpd_t *result, mpd_t *a);
+EXTINLINE void mpd_set_infinity(mpd_t *result);
+EXTINLINE void mpd_set_qnan(mpd_t *result);
+EXTINLINE void mpd_set_snan(mpd_t *result);
+EXTINLINE void mpd_set_negative(mpd_t *result);
+EXTINLINE void mpd_set_positive(mpd_t *result);
+EXTINLINE void mpd_set_dynamic(mpd_t *result);
+EXTINLINE void mpd_set_static(mpd_t *result);
+EXTINLINE void mpd_set_dynamic_data(mpd_t *result);
+EXTINLINE void mpd_set_static_data(mpd_t *result);
+EXTINLINE void mpd_set_shared_data(mpd_t *result);
+EXTINLINE void mpd_set_const_data(mpd_t *result);
+EXTINLINE void mpd_clear_flags(mpd_t *result);
+EXTINLINE void mpd_set_flags(mpd_t *result, uint8_t flags);
+EXTINLINE void mpd_copy_flags(mpd_t *result, const mpd_t *a);
+
+
+/******************************************************************************/
+/* Error Macros */
+/******************************************************************************/
+
+enum {MPD_ERR_EXIT, MPD_ERR_WARN};
+#define mpd_err_fatal(format, ...) \
+ mpd_err_doit(MPD_ERR_EXIT, "%s:%d: error: " format, __FILE__, __LINE__, ##__VA_ARGS__)
+#define mpd_err_warn(format, ...) \
+ mpd_err_doit(MPD_ERR_WARN, "%s:%d: error: " format, __FILE__, __LINE__, ##__VA_ARGS__)
+
+void mpd_err_doit(int action, const char *fmt, ...);
+
+
+/******************************************************************************/
+/* Memory handling */
+/******************************************************************************/
+
+extern void *(* mpd_mallocfunc)(size_t size);
+extern void *(* mpd_callocfunc)(size_t nmemb, size_t size);
+extern void *(* mpd_reallocfunc)(void *ptr, size_t size);
+extern void (* mpd_free)(void *ptr);
+
+void *mpd_callocfunc_em(size_t nmemb, size_t size);
+
+void *mpd_alloc(size_t nmemb, size_t size);
+void *mpd_calloc(size_t nmemb, size_t size);
+void *mpd_realloc(void *ptr, size_t nmemb, size_t size, uint8_t *err);
+void *mpd_sh_alloc(size_t struct_size, size_t nmemb, size_t size);
+void *mpd_sh_calloc(size_t struct_size, size_t nmemb, size_t size);
+void *mpd_sh_realloc(void *ptr, size_t struct_size, size_t nmemb, size_t size, uint8_t *err);
+
+mpd_t *mpd_qnew(void);
+mpd_t *mpd_new(mpd_context_t *ctx);
+mpd_t *mpd_qnew_size(mpd_ssize_t size);
+void mpd_del(mpd_t *dec);
+
+void mpd_uint_zero(mpd_uint_t *dest, size_t len);
+int mpd_qresize(mpd_t *result, mpd_ssize_t size, uint32_t *status);
+int mpd_qresize_zero(mpd_t *result, mpd_ssize_t size, uint32_t *status);
+void mpd_minalloc(mpd_t *result);
+
+int mpd_resize(mpd_t *result, mpd_ssize_t size, mpd_context_t *ctx);
+int mpd_resize_zero(mpd_t *result, mpd_ssize_t size, mpd_context_t *ctx);
+
+
+#ifdef __cplusplus
+} /* END extern "C" */
+#endif
+
+
+#endif /* MPDECIMAL32_H */
+
+
+
Added: python/branches/py3k-cdecimal/Modules/cdecimal/mpdecimal64.h
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/mpdecimal64.h Thu Jan 7 13:02:51 2010
@@ -0,0 +1,532 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#ifndef MPDECIMAL64_H
+#define MPDECIMAL64_H
+
+
+#ifdef __cplusplus
+extern "C" {
+#define __STDC_LIMIT_MACROS
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <limits.h>
+#include <assert.h>
+
+
+#define EXTINLINE
+#ifdef _MSC_VER
+ #include "vccompat.h"
+ #ifndef UNUSED
+ #define UNUSED
+ #endif
+ #undef EXTINLINE
+ #define EXTINLINE extern inline
+#else
+ #include <stdint.h>
+ #define __GNUC_STDC_INLINE__
+ #define UNUSED __attribute__((unused))
+#endif
+
+
+/******************************************************************************/
+/* Types for 64 bit architectures */
+/******************************************************************************/
+
+/* types for modular and base arithmetic */
+#define MPD_UINT_MAX UINT64_MAX
+#define MPD_BITS_PER_UINT 64
+typedef uint64_t mpd_uint_t; /* unsigned mod type */
+
+/* type for exp, digits, len, prec */
+#define MPD_SSIZE_MAX INT64_MAX
+#define MPD_SSIZE_MIN INT64_MIN
+typedef int64_t mpd_ssize_t;
+#define mpd_strtossize strtoll
+
+/* decimal arithmetic */
+#define MPD_RADIX 10000000000000000000ULL /* 10**19 */
+#define MPD_RDIGITS 19
+#define MPD_MAX_POW10 19
+#define MPD_EXPDIGITS 19 /* MPD_EXPDIGITS <= MPD_RDIGITS+1 */
+
+#define MPD_MAXTRANSFORM_2N 4294967296ULL /* 2**32 */
+#define MPD_MAX_PREC 999999999999999999LL
+#define MPD_MAX_PREC_LOG2 64
+#define MPD_ELIMIT 1000000000000000000LL
+#define MPD_MAX_EMAX 999999999999999999LL /* ELIMIT-1 */
+#define MPD_MIN_EMIN (-999999999999999999LL) /* -EMAX */
+#define MPD_MIN_ETINY (MPD_MIN_EMIN-(MPD_MAX_PREC-1))
+#define MPD_EXP_INF (MPD_ELIMIT+1)
+#define MPD_EXP_CLAMP (2*MPD_MIN_ETINY)
+
+
+#if SIZE_MAX < MPD_SSIZE_MAX
+ #error "unsupported platform: need size_t >= mpd_ssize_t"
+#endif
+#if MPD_SSIZE_MAX > MPD_UINT_MAX
+ #error "unsupported platform: need mpd_ssize_t <= mpd_uint_t"
+#endif
+
+
+/******************************************************************************/
+/* Context */
+/******************************************************************************/
+
+enum {
+ MPD_ROUND_UP, /* round away from 0 */
+ MPD_ROUND_DOWN, /* round toward 0 (truncate) */
+ MPD_ROUND_CEILING, /* round toward +infinity */
+ MPD_ROUND_FLOOR, /* round toward -infinity */
+ MPD_ROUND_HALF_UP, /* 0.5 is rounded up */
+ MPD_ROUND_HALF_DOWN, /* 0.5 is rounded down */
+ MPD_ROUND_HALF_EVEN, /* 0.5 is rounded to even */
+ MPD_ROUND_05UP, /* round zero or five away from 0 */
+ MPD_ROUND_TRUNC, /* truncate, but set infinity */
+ MPD_ROUND_GUARD
+};
+
+enum { MPD_CLAMP_DEFAULT, MPD_CLAMP_IEEE_754, MPD_CLAMP_GUARD };
+
+extern const char *mpd_round_string[MPD_ROUND_GUARD];
+extern const char *mpd_clamp_string[MPD_CLAMP_GUARD];
+
+
+typedef struct {
+ mpd_ssize_t prec; /* precision */
+ mpd_ssize_t emax; /* max positive exp */
+ mpd_ssize_t emin; /* min negative exp */
+ uint32_t traps; /* status events that should be trapped */
+ uint32_t status; /* status flags */
+ uint32_t newtrap; /* set by mpd_addstatus_raise() */
+ int round; /* rounding mode */
+ int clamp; /* clamp mode */
+ int allcr; /* all functions correctly rounded */
+} mpd_context_t;
+
+
+/* Status flags */
+#define MPD_Clamped 0x00000001U
+#define MPD_Conversion_syntax 0x00000002U
+#define MPD_Division_by_zero 0x00000004U
+#define MPD_Division_impossible 0x00000008U
+#define MPD_Division_undefined 0x00000010U
+#define MPD_Fpu_error 0x00000020U
+#define MPD_Inexact 0x00000040U
+#define MPD_Invalid_context 0x00000080U
+#define MPD_Invalid_operation 0x00000100U
+#define MPD_Malloc_error 0x00000200U
+#define MPD_Not_implemented 0x00000400U
+#define MPD_Overflow 0x00000800U
+#define MPD_Rounded 0x00001000U
+#define MPD_Subnormal 0x00002000U
+#define MPD_Underflow 0x00004000U
+#define MPD_Max_status (0x00008000U-1U)
+
+/* Conditions that result in an IEEE 754 exception */
+#define MPD_IEEE_Invalid_operation (MPD_Conversion_syntax | \
+ MPD_Division_impossible | \
+ MPD_Division_undefined | \
+ MPD_Fpu_error | \
+ MPD_Invalid_context | \
+ MPD_Invalid_operation | \
+ MPD_Malloc_error) \
+
+/* Errors that require the result of an operation to be set to NaN */
+#define MPD_Errors (MPD_IEEE_Invalid_operation | \
+ MPD_Division_by_zero)
+
+/* Default traps */
+#define MPD_Traps (MPD_IEEE_Invalid_operation | \
+ MPD_Division_by_zero | \
+ MPD_Overflow | \
+ MPD_Underflow)
+
+/* Official name */
+#define MPD_Insufficient_storage MPD_Malloc_error
+
+
+#define MPD_MINALLOC_MIN 2
+#define MPD_MINALLOC_MAX 64
+extern mpd_ssize_t MPD_MINALLOC;
+extern void (* mpd_traphandler)(mpd_context_t *);
+
+void mpd_init(mpd_context_t *ctx, mpd_ssize_t prec);
+
+void mpd_maxcontext(mpd_context_t *ctx);
+void mpd_defaultcontext(mpd_context_t *ctx);
+void mpd_basiccontext(mpd_context_t *ctx);
+void mpd_extcontext(mpd_context_t *ctx);
+
+mpd_ssize_t mpd_getprec(const mpd_context_t *ctx);
+mpd_ssize_t mpd_getemax(const mpd_context_t *ctx);
+mpd_ssize_t mpd_getemin(const mpd_context_t *ctx);
+int mpd_getround(const mpd_context_t *ctx);
+uint32_t mpd_gettraps(const mpd_context_t *ctx);
+uint32_t mpd_getstatus(const mpd_context_t *ctx);
+int mpd_getclamp(const mpd_context_t *ctx);
+int mpd_getcr(const mpd_context_t *ctx);
+
+int mpd_qsetprec(mpd_context_t *ctx, mpd_ssize_t prec);
+int mpd_qsetemax(mpd_context_t *ctx, mpd_ssize_t emax);
+int mpd_qsetemin(mpd_context_t *ctx, mpd_ssize_t emin);
+int mpd_qsetround(mpd_context_t *ctx, int newround);
+int mpd_qsettraps(mpd_context_t *ctx, uint32_t flags);
+int mpd_qsetstatus(mpd_context_t *ctx, uint32_t flags);
+int mpd_qsetclamp(mpd_context_t *ctx, int c);
+int mpd_qsetcr(mpd_context_t *ctx, int c);
+void mpd_addstatus_raise(mpd_context_t *ctx, uint32_t flags);
+
+
+/******************************************************************************/
+/* Decimal Arithmetic */
+/******************************************************************************/
+
+/* mpd_t flags */
+#define MPD_POS ((uint8_t)0)
+#define MPD_NEG ((uint8_t)1)
+#define MPD_INF ((uint8_t)2)
+#define MPD_NAN ((uint8_t)4)
+#define MPD_SNAN ((uint8_t)8)
+#define MPD_SPECIAL (MPD_INF|MPD_NAN|MPD_SNAN)
+#define MPD_STATIC ((uint8_t)16)
+#define MPD_STATIC_DATA ((uint8_t)32)
+#define MPD_SHARED_DATA ((uint8_t)64)
+#define MPD_CONST_DATA ((uint8_t)128)
+#define MPD_DATAFLAGS (MPD_STATIC_DATA|MPD_SHARED_DATA|MPD_CONST_DATA)
+
+/* mpd_t */
+typedef struct {
+ uint8_t flags;
+ mpd_ssize_t exp;
+ mpd_ssize_t digits;
+ mpd_ssize_t len;
+ mpd_ssize_t alloc;
+ mpd_uint_t *data;
+} mpd_t;
+
+
+typedef unsigned char uchar;
+extern mpd_t mpd_ln10;
+
+
+/******************************************************************************/
+/* Quiet, thread-safe functions */
+/******************************************************************************/
+
+/* format specification */
+typedef struct {
+ mpd_ssize_t min_width; /* minimum field width */
+ mpd_ssize_t prec; /* fraction digits or significant digits */
+ char type; /* conversion specifier */
+ char align; /* alignment */
+ char sign; /* sign printing/alignment */
+ char fill[5]; /* fill character */
+ const char *dot; /* decimal point */
+ const char *sep; /* thousands separator */
+ const char *grouping; /* grouping of digits */
+} mpd_spec_t;
+
+/* output to a string */
+char *mpd_to_sci(const mpd_t *dec, int fmt);
+char *mpd_to_eng(const mpd_t *dec, int fmt);
+int mpd_parse_fmt_str(mpd_spec_t *spec, const char *fmt);
+char * mpd_qformat_spec(const mpd_t *dec, mpd_spec_t *spec, const mpd_context_t *ctx, uint32_t *status);
+char *mpd_qformat(const mpd_t *dec, const char *fmt, const mpd_context_t *ctx, uint32_t *status);
+
+#define MPD_NUM_FLAGS 15
+#define MPD_MAX_FLAG_STRING 208
+#define MPD_MAX_FLAG_LIST (MPD_MAX_FLAG_STRING+18)
+#define MPD_MAX_SIGNAL_LIST 121
+int mpd_snprint_flags(char *dest, int nmemb, uint32_t flags);
+int mpd_lsnprint_flags(char *dest, int nmemb, uint32_t flags, const char *flag_string[]);
+int mpd_lsnprint_signals(char *dest, int nmemb, uint32_t flags, const char *signal_string[]);
+
+/* output to a file */
+void mpd_fprint(FILE *file, const mpd_t *dec);
+void mpd_print(const mpd_t *dec);
+
+/* assignment from a string */
+void mpd_qset_string(mpd_t *dec, const char *s, const mpd_context_t *ctx, uint32_t *status);
+
+/* set to NaN with error flags */
+void mpd_seterror(mpd_t *result, uint32_t flags, uint32_t *status);
+/* set a special with sign and type */
+void mpd_setspecial(mpd_t *dec, uint8_t sign, uint8_t type);
+/* set coefficient to zero or all nines */
+void mpd_zerocoeff(mpd_t *result);
+void mpd_qmaxcoeff(mpd_t *result, const mpd_context_t *ctx, uint32_t *status);
+
+/* quietly assign a C integer type to an mpd_t */
+void mpd_qset_ssize(mpd_t *result, mpd_ssize_t a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qset_i32(mpd_t *result, int32_t a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qset_i64(mpd_t *result, int64_t a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qset_uint(mpd_t *result, mpd_uint_t a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qset_u32(mpd_t *result, uint32_t a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qset_u64(mpd_t *result, uint64_t a, const mpd_context_t *ctx, uint32_t *status);
+
+/* quietly assign a C integer type to an mpd_t with a static coefficient */
+void mpd_qsset_ssize(mpd_t *result, mpd_ssize_t a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qsset_i32(mpd_t *result, int32_t a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qsset_i64(mpd_t *result, int64_t a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qsset_uint(mpd_t *result, mpd_uint_t a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qsset_u32(mpd_t *result, uint32_t a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qsset_u64(mpd_t *result, uint64_t a, const mpd_context_t *ctx, uint32_t *status);
+
+/* quietly get a C integer type from an mpd_t */
+mpd_ssize_t mpd_qget_ssize(const mpd_t *dec, uint32_t *status);
+int64_t mpd_qget_i64(const mpd_t *dec, uint32_t *status);
+mpd_uint_t mpd_qget_uint(const mpd_t *dec, uint32_t *status);
+uint64_t mpd_qget_u64(const mpd_t *dec, uint32_t *status);
+
+
+/* quiet functions */
+int mpd_qcheck_nan(mpd_t *nanresult, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+int mpd_qcheck_nans(mpd_t *nanresult, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qfinalize(mpd_t *result, const mpd_context_t *ctx, uint32_t *status);
+
+const char * mpd_class(const mpd_t *a, const mpd_context_t *ctx);
+
+int mpd_qcopy(mpd_t *result, const mpd_t *a, uint32_t *status);
+mpd_t *mpd_qncopy(const mpd_t *a);
+int mpd_qcopy_abs(mpd_t *result, const mpd_t *a, uint32_t *status);
+int mpd_qcopy_negate(mpd_t *result, const mpd_t *a, uint32_t *status);
+int mpd_qcopy_sign(mpd_t *result, const mpd_t *a, const mpd_t *b, uint32_t *status);
+
+void mpd_qand(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qinvert(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qlogb(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qor(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qscaleb(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qxor(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+int mpd_same_quantum(const mpd_t *a, const mpd_t *b);
+
+void mpd_qrotate(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+int mpd_qshiftl(mpd_t *result, const mpd_t *a, mpd_ssize_t n, uint32_t *status);
+mpd_uint_t mpd_qshiftr(mpd_t *result, const mpd_t *a, mpd_ssize_t n, uint32_t *status);
+mpd_uint_t mpd_qshiftr_inplace(mpd_t *result, mpd_ssize_t n);
+void mpd_qshift(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qshiftn(mpd_t *result, const mpd_t *a, mpd_ssize_t n, const mpd_context_t *ctx, uint32_t *status);
+
+int mpd_qcmp(const mpd_t *a, const mpd_t *b, uint32_t *status);
+int mpd_qcompare(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+int mpd_qcompare_signal(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+int mpd_cmp_total(const mpd_t *a, const mpd_t *b);
+int mpd_cmp_total_mag(const mpd_t *a, const mpd_t *b);
+int mpd_compare_total(mpd_t *result, const mpd_t *a, const mpd_t *b);
+int mpd_compare_total_mag(mpd_t *result, const mpd_t *a, const mpd_t *b);
+
+void mpd_qround_to_intx(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qround_to_int(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qfloor(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qceil(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+
+void mpd_qabs(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qmax(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qmax_mag(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qmin(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qmin_mag(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qminus(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qplus(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qnext_minus(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qnext_plus(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qnext_toward(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qquantize(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qrescale(mpd_t *result, const mpd_t *a, mpd_ssize_t exp, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qreduce(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qadd(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qadd_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qadd_i32(mpd_t *result, const mpd_t *a, int32_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qadd_i64(mpd_t *result, const mpd_t *a, int64_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qadd_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qadd_u32(mpd_t *result, const mpd_t *a, uint32_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qadd_u64(mpd_t *result, const mpd_t *a, uint64_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qsub(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qsub_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qsub_i32(mpd_t *result, const mpd_t *a, int32_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qsub_i64(mpd_t *result, const mpd_t *a, int64_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qsub_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qsub_u32(mpd_t *result, const mpd_t *a, uint32_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qsub_u64(mpd_t *result, const mpd_t *a, uint64_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qmul(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qmul_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qmul_i32(mpd_t *result, const mpd_t *a, int32_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qmul_i64(mpd_t *result, const mpd_t *a, int64_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qmul_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qmul_u32(mpd_t *result, const mpd_t *a, uint32_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qmul_u64(mpd_t *result, const mpd_t *a, uint64_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qfma(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_t *c, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qdiv(mpd_t *q, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qdiv_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qdiv_i32(mpd_t *result, const mpd_t *a, int32_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qdiv_i64(mpd_t *result, const mpd_t *a, int64_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qdiv_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qdiv_u32(mpd_t *result, const mpd_t *a, uint32_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qdiv_u64(mpd_t *result, const mpd_t *a, uint64_t b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qdivint(mpd_t *q, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qrem(mpd_t *r, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qrem_near(mpd_t *r, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qdivmod(mpd_t *q, mpd_t *r, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qpow(mpd_t *result, const mpd_t *base, const mpd_t *exp, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qpowmod(mpd_t *result, const mpd_t *base, const mpd_t *exp, const mpd_t *mod, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qexp(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_update_ln10(mpd_ssize_t prec, uint32_t *status);
+void mpd_qln(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qlog10(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qsqrt(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+void mpd_qinvroot(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status);
+
+
+size_t mpd_sizeinbase(mpd_t *a, uint32_t base);
+int mpd_qimport_u16(mpd_t *result, const uint16_t *srcdata, size_t srclen,
+ uint8_t srcsign, uint32_t base,
+ const mpd_context_t *ctx, uint32_t *status);
+int mpd_qimport_u32(mpd_t *result, const uint32_t *srcdata, size_t srclen,
+ uint8_t srcsign, uint32_t base,
+ const mpd_context_t *ctx, uint32_t *status);
+size_t mpd_qexport_u16(uint16_t *rdata, size_t rlen, uint32_t base,
+ const mpd_t *src, uint32_t *status);
+size_t mpd_qexport_u32(uint32_t *rdata, size_t rlen, uint32_t base,
+ const mpd_t *src, uint32_t *status);
+
+
+/******************************************************************************/
+/* Get attributes of a decimal */
+/******************************************************************************/
+
+EXTINLINE mpd_ssize_t mpd_adjexp(const mpd_t *dec);
+EXTINLINE mpd_ssize_t mpd_etiny(const mpd_context_t *ctx);
+EXTINLINE mpd_ssize_t mpd_etop(const mpd_context_t *ctx);
+EXTINLINE mpd_uint_t mpd_msword(const mpd_t *dec);
+EXTINLINE int mpd_word_digits(mpd_uint_t word);
+/* most significant digit of a word */
+EXTINLINE mpd_uint_t mpd_msd(mpd_uint_t word);
+/* least significant digit of a word */
+EXTINLINE mpd_uint_t mpd_lsd(mpd_uint_t word);
+/* coefficient size needed to store 'digits' */
+EXTINLINE mpd_ssize_t mpd_digits_to_size(mpd_ssize_t digits);
+/* number of digits in the exponent, undefined for MPD_SSIZE_MIN */
+EXTINLINE int mpd_exp_digits(mpd_ssize_t exp);
+EXTINLINE int mpd_iscanonical(const mpd_t *dec UNUSED);
+EXTINLINE int mpd_isfinite(const mpd_t *dec);
+EXTINLINE int mpd_isinfinite(const mpd_t *dec);
+EXTINLINE int mpd_isinteger(const mpd_t *dec);
+EXTINLINE int mpd_isnan(const mpd_t *dec);
+EXTINLINE int mpd_isnegative(const mpd_t *dec);
+EXTINLINE int mpd_ispositive(const mpd_t *dec);
+EXTINLINE int mpd_isqnan(const mpd_t *dec);
+EXTINLINE int mpd_issigned(const mpd_t *dec);
+EXTINLINE int mpd_issnan(const mpd_t *dec);
+EXTINLINE int mpd_isspecial(const mpd_t *dec);
+EXTINLINE int mpd_iszero(const mpd_t *dec);
+/* undefined for special numbers */
+EXTINLINE int mpd_iszerocoeff(const mpd_t *dec);
+EXTINLINE int mpd_isnormal(const mpd_t *dec, const mpd_context_t *ctx);
+EXTINLINE int mpd_issubnormal(const mpd_t *dec, const mpd_context_t *ctx);
+/* odd word */
+EXTINLINE int mpd_isoddword(mpd_uint_t word);
+/* odd coefficient */
+EXTINLINE int mpd_isoddcoeff(const mpd_t *dec);
+/* odd decimal, only defined for integers */
+int mpd_isodd(const mpd_t *dec);
+/* even decimal, only defined for integers */
+int mpd_iseven(const mpd_t *dec);
+/* 0 if dec is positive, 1 if dec is negative */
+EXTINLINE uint8_t mpd_sign(const mpd_t *dec);
+/* 1 if dec is positive, -1 if dec is negative */
+EXTINLINE int mpd_arith_sign(const mpd_t *dec);
+EXTINLINE long mpd_radix(void);
+EXTINLINE int mpd_isdynamic(mpd_t *dec);
+EXTINLINE int mpd_isstatic(mpd_t *dec);
+EXTINLINE int mpd_isdynamic_data(mpd_t *dec);
+EXTINLINE int mpd_isstatic_data(mpd_t *dec);
+EXTINLINE int mpd_isshared_data(mpd_t *dec);
+EXTINLINE int mpd_isconst_data(mpd_t *dec);
+EXTINLINE mpd_ssize_t mpd_trail_zeros(const mpd_t *dec);
+
+
+/******************************************************************************/
+/* Set attributes of a decimal */
+/******************************************************************************/
+
+/* set number of decimal digits in the coefficient */
+EXTINLINE void mpd_setdigits(mpd_t *result);
+EXTINLINE void mpd_set_sign(mpd_t *result, uint8_t sign);
+/* copy sign from another decimal */
+EXTINLINE void mpd_signcpy(mpd_t *result, mpd_t *a);
+EXTINLINE void mpd_set_infinity(mpd_t *result);
+EXTINLINE void mpd_set_qnan(mpd_t *result);
+EXTINLINE void mpd_set_snan(mpd_t *result);
+EXTINLINE void mpd_set_negative(mpd_t *result);
+EXTINLINE void mpd_set_positive(mpd_t *result);
+EXTINLINE void mpd_set_dynamic(mpd_t *result);
+EXTINLINE void mpd_set_static(mpd_t *result);
+EXTINLINE void mpd_set_dynamic_data(mpd_t *result);
+EXTINLINE void mpd_set_static_data(mpd_t *result);
+EXTINLINE void mpd_set_shared_data(mpd_t *result);
+EXTINLINE void mpd_set_const_data(mpd_t *result);
+EXTINLINE void mpd_clear_flags(mpd_t *result);
+EXTINLINE void mpd_set_flags(mpd_t *result, uint8_t flags);
+EXTINLINE void mpd_copy_flags(mpd_t *result, const mpd_t *a);
+
+
+/******************************************************************************/
+/* Error Macros */
+/******************************************************************************/
+
+enum {MPD_ERR_EXIT, MPD_ERR_WARN};
+#define mpd_err_fatal(format, ...) \
+ mpd_err_doit(MPD_ERR_EXIT, "%s:%d: error: " format, __FILE__, __LINE__, ##__VA_ARGS__)
+#define mpd_err_warn(format, ...) \
+ mpd_err_doit(MPD_ERR_WARN, "%s:%d: error: " format, __FILE__, __LINE__, ##__VA_ARGS__)
+
+void mpd_err_doit(int action, const char *fmt, ...);
+
+
+/******************************************************************************/
+/* Memory handling */
+/******************************************************************************/
+
+extern void *(* mpd_mallocfunc)(size_t size);
+extern void *(* mpd_callocfunc)(size_t nmemb, size_t size);
+extern void *(* mpd_reallocfunc)(void *ptr, size_t size);
+extern void (* mpd_free)(void *ptr);
+
+void *mpd_callocfunc_em(size_t nmemb, size_t size);
+
+void *mpd_alloc(size_t nmemb, size_t size);
+void *mpd_calloc(size_t nmemb, size_t size);
+void *mpd_realloc(void *ptr, size_t nmemb, size_t size, uint8_t *err);
+void *mpd_sh_alloc(size_t struct_size, size_t nmemb, size_t size);
+void *mpd_sh_calloc(size_t struct_size, size_t nmemb, size_t size);
+void *mpd_sh_realloc(void *ptr, size_t struct_size, size_t nmemb, size_t size, uint8_t *err);
+
+mpd_t *mpd_qnew(void);
+mpd_t *mpd_new(mpd_context_t *ctx);
+mpd_t *mpd_qnew_size(mpd_ssize_t size);
+void mpd_del(mpd_t *dec);
+
+void mpd_uint_zero(mpd_uint_t *dest, size_t len);
+int mpd_qresize(mpd_t *result, mpd_ssize_t size, uint32_t *status);
+int mpd_qresize_zero(mpd_t *result, mpd_ssize_t size, uint32_t *status);
+void mpd_minalloc(mpd_t *result);
+
+int mpd_resize(mpd_t *result, mpd_ssize_t size, mpd_context_t *ctx);
+int mpd_resize_zero(mpd_t *result, mpd_ssize_t size, mpd_context_t *ctx);
+
+
+#ifdef __cplusplus
+} /* END extern "C" */
+#endif
+
+
+#endif /* MPDECIMAL64_H */
+
+
+
Added: python/branches/py3k-cdecimal/Modules/cdecimal/mptypes.h
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/mptypes.h Thu Jan 7 13:02:51 2010
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#ifndef MPTYPES_H
+#define MPTYPES_H
+
+
+#if defined(CONFIG_64)
+ #if defined(_MSC_VER)
+ #define PRI_size_t "llu"
+ #define PRI_mpd_ssize_t "lld"
+ #else
+ #define PRI_size_t "lu"
+ #define PRI_mpd_ssize_t "ld"
+ #endif
+ #define PRI_time_t "ld"
+ #define CONV_mpd_ssize_t "L"
+ #define ONE_UM 1ULL
+#elif defined(CONFIG_32)
+ #if defined (__OpenBSD__)
+ #define PRI_size_t "lu"
+ #define PRI_mpd_ssize_t "ld"
+ #define PRI_time_t "d"
+ #else
+ #define PRI_size_t "u"
+ #define PRI_mpd_ssize_t "d"
+ #define PRI_time_t "ld"
+ #endif
+ #define CONV_mpd_ssize_t "l"
+ #define ONE_UM 1UL
+#else
+ #error "define CONFIG_64 or CONFIG_32"
+#endif
+
+
+#endif
+
+
Added: python/branches/py3k-cdecimal/Modules/cdecimal/numbertheory.c
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/numbertheory.c Thu Jan 7 13:02:51 2010
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#include <stdlib.h>
+#include <assert.h>
+#include "bits.h"
+#include "mpdecimal.h"
+#include "umodarith.h"
+#include "numbertheory.h"
+
+
+/* transform kernel */
+mpd_uint_t
+_mpd_getkernel(mpd_uint_t n, int sign, int modnum)
+{
+ mpd_uint_t umod, p, r, xi;
+#ifdef PPRO
+ double dmod;
+ uint32_t dinvmod[3];
+#endif
+
+ SETMODULUS(modnum);
+ r = mpd_roots[modnum];
+ p = umod;
+ xi = (p-1) / n;
+
+ if (sign == -1)
+ return POWMOD(r, (p-1-xi));
+ else
+ return POWMOD(r, xi);
+}
+
+/* initialize transform parameters */
+struct fnt_params *
+_mpd_init_fnt_params(size_t n, int sign, int modnum)
+{
+ struct fnt_params *tparams;
+ mpd_uint_t umod;
+#ifdef PPRO
+ double dmod;
+ uint32_t dinvmod[3];
+#endif
+ mpd_uint_t kernel, imag, w;
+ mpd_uint_t i;
+ size_t nhalf;
+
+ assert(ispower2(n));
+ assert(sign == -1 || sign == 1);
+ assert(P1 <= modnum && modnum <= P3);
+
+ nhalf = n/2;
+ tparams = mpd_sh_alloc(sizeof *tparams, nhalf, sizeof (mpd_uint_t));
+ if (tparams == NULL) {
+ return NULL;
+ }
+
+ SETMODULUS(modnum);
+ kernel = _mpd_getkernel(n, sign, modnum);
+ imag = _mpd_getkernel(4, -sign, modnum);
+
+ tparams->modnum = modnum;
+ tparams->modulus = umod;
+ tparams->imag = imag;
+ tparams->kernel = kernel;
+
+ w = 1;
+ for (i = 0; i < nhalf; i++) {
+ tparams->wtable[i] = w;
+ w = MULMOD(w, kernel);
+ }
+
+ return tparams;
+}
+
+/* initialize wtable of size three */
+void
+_mpd_init_w3table(mpd_uint_t w3table[3], int sign, int modnum)
+{
+ mpd_uint_t umod;
+#ifdef PPRO
+ double dmod;
+ uint32_t dinvmod[3];
+#endif
+ mpd_uint_t kernel;
+
+ SETMODULUS(modnum);
+ kernel = _mpd_getkernel(3, sign, modnum);
+
+ w3table[0] = 1;
+ w3table[1] = kernel;
+ w3table[2] = POWMOD(kernel, 2);
+}
+
+
Added: python/branches/py3k-cdecimal/Modules/cdecimal/numbertheory.h
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/numbertheory.h Thu Jan 7 13:02:51 2010
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#ifndef NUMBER_THEORY_H
+#define NUMBER_THEORY_H
+
+
+#include "constants.h"
+#include "mpdecimal.h"
+
+
+/* transform parameters */
+struct fnt_params {
+ int modnum;
+ mpd_uint_t modulus;
+ mpd_uint_t imag;
+ mpd_uint_t kernel;
+ mpd_uint_t wtable[];
+};
+
+
+mpd_uint_t _mpd_getkernel(mpd_uint_t n, int sign, int modnum);
+struct fnt_params *_mpd_init_fnt_params(size_t n, int sign, int modnum);
+void _mpd_init_w3table(mpd_uint_t w3table[3], int sign, int modnum);
+
+
+static inline void
+std_setmodulus(int modnum, mpd_uint_t *umod)
+{
+ *umod = mpd_moduli[modnum];
+}
+
+
+#ifdef PPRO
+static inline void
+ppro_setmodulus(int modnum, mpd_uint_t *umod, double *dmod, uint32_t dinvmod[3])
+{
+ *dmod = *umod = mpd_moduli[modnum];
+ dinvmod[0] = mpd_invmoduli[modnum][0];
+ dinvmod[1] = mpd_invmoduli[modnum][1];
+ dinvmod[2] = mpd_invmoduli[modnum][2];
+}
+#endif
+
+
+#endif
+
+
Added: python/branches/py3k-cdecimal/Modules/cdecimal/sixstep.c
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/sixstep.c Thu Jan 7 13:02:51 2010
@@ -0,0 +1,176 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <assert.h>
+#include "bits.h"
+#include "difradix2.h"
+#include "mpdecimal.h"
+#include "mptypes.h"
+#include "numbertheory.h"
+#include "transpose.h"
+#include "umodarith.h"
+#include "sixstep.h"
+
+
+/*
+ * A variant of the six-step algorithm from:
+ *
+ * David H. Bailey: FFTs in External or Hierarchical Memory, Journal of
+ * Supercomputing, vol. 4, no. 1 (March 1990), p. 23-35.
+ *
+ * URL: http://crd.lbl.gov/~dhbailey/dhbpapers/
+ */
+
+
+/* forward transform with sign = -1 */
+int
+six_step_fnt(mpd_uint_t *a, size_t n, int modnum, int ordered)
+{
+ struct fnt_params *tparams;
+ size_t log2n, C, R;
+ mpd_uint_t kernel;
+ mpd_uint_t umod;
+#ifdef PPRO
+ double dmod;
+ uint32_t dinvmod[3];
+#endif
+ mpd_uint_t *x, w0, w1, wstep;
+ size_t i, k;
+
+
+ assert(ispower2(n));
+ assert(n >= 16);
+ assert(n <= MPD_MAXTRANSFORM_2N);
+
+ log2n = BSR(n);
+ C = (ONE_UM << (log2n / 2)); /* number of columns */
+ R = (ONE_UM << (log2n - (log2n / 2))); /* number of rows */
+
+
+ transpose_pow2(a, R, C); /* view a as a RxC matrix, tranpose */
+
+ if ((tparams = _mpd_init_fnt_params(R, -1, modnum)) == NULL) {
+ return 0;
+ }
+ for (x = a; x < a+n; x += R) {
+ fnt_dif2(x, R, tparams);
+ }
+
+ transpose_pow2(a, C, R);
+
+
+ SETMODULUS(modnum);
+ kernel = _mpd_getkernel(n, -1, modnum);
+ for (i = 1; i < R; i++) {
+ w0 = 1;
+ w1 = POWMOD(kernel, i);
+ wstep = MULMOD(w1, w1);
+ for (k = 0; k < C; k += 2) {
+ mpd_uint_t x0 = a[i*C+k];
+ mpd_uint_t x1 = a[i*C+k+1];
+ MULMOD2(&x0, w0, &x1, w1);
+ MULMOD2C(&w0, &w1, wstep);
+ a[i*C+k] = x0;
+ a[i*C+k+1] = x1;
+ }
+ }
+
+
+ if (C != R) {
+ mpd_free(tparams);
+ if ((tparams = _mpd_init_fnt_params(C, -1, modnum)) == NULL) {
+ return 0;
+ }
+ }
+ for (x = a; x < a+n; x += C) {
+ fnt_dif2(x, C, tparams);
+ }
+ mpd_free(tparams);
+
+
+ if (ordered) {
+ transpose_pow2(a, R, C);
+ }
+
+ return 1;
+}
+
+
+/* reverse transform, sign = 1 */
+int
+inv_six_step_fnt(mpd_uint_t *a, size_t n, int modnum, int ordered)
+{
+ struct fnt_params *tparams;
+ size_t log2n, C, R;
+ mpd_uint_t kernel;
+ mpd_uint_t umod;
+#ifdef PPRO
+ double dmod;
+ uint32_t dinvmod[3];
+#endif
+ mpd_uint_t *x, w0, w1, wstep;
+ size_t i, k;
+
+
+ assert(ispower2(n));
+ assert(n >= 16);
+ assert(n <= MPD_MAXTRANSFORM_2N);
+
+ log2n = BSR(n);
+ C = (ONE_UM << (log2n / 2)); /* number of columns */
+ R = (ONE_UM << (log2n - (log2n / 2))); /* number of rows */
+
+
+ if (ordered) {
+ transpose_pow2(a, C, R);
+ }
+
+ if ((tparams = _mpd_init_fnt_params(C, 1, modnum)) == NULL) {
+ return 0;
+ }
+ for (x = a; x < a+n; x += C) {
+ fnt_dif2(x, C, tparams);
+ }
+
+ transpose_pow2(a, R, C);
+
+
+ SETMODULUS(modnum);
+ kernel = _mpd_getkernel(n, 1, modnum);
+ for (i = 1; i < C; i++) {
+ w0 = 1;
+ w1 = POWMOD(kernel, i);
+ wstep = MULMOD(w1, w1);
+ for (k = 0; k < R; k += 2) {
+ mpd_uint_t x0 = a[i*R+k];
+ mpd_uint_t x1 = a[i*R+k+1];
+ MULMOD2(&x0, w0, &x1, w1);
+ MULMOD2C(&w0, &w1, wstep);
+ a[i*R+k] = x0;
+ a[i*R+k+1] = x1;
+ }
+ }
+
+
+ if (R != C) {
+ mpd_free(tparams);
+ if ((tparams = _mpd_init_fnt_params(R, 1, modnum)) == NULL) {
+ return 0;
+ }
+ }
+ for (x = a; x < a+n; x += R) {
+ fnt_dif2(x, R, tparams);
+ }
+ mpd_free(tparams);
+
+ transpose_pow2(a, C, R);
+
+ return 1;
+}
+
+
Added: python/branches/py3k-cdecimal/Modules/cdecimal/sixstep.h
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/sixstep.h Thu Jan 7 13:02:51 2010
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#ifndef SIX_STEP_H
+#define SIX_STEP_H
+
+
+#include <stdio.h>
+#include "mpdecimal.h"
+
+
+int six_step_fnt(mpd_uint_t *a, size_t n, int modnum, int ordered);
+int inv_six_step_fnt(mpd_uint_t *a, size_t n, int modnum, int ordered);
+
+
+#endif
Added: python/branches/py3k-cdecimal/Modules/cdecimal/transpose.c
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/transpose.c Thu Jan 7 13:02:51 2010
@@ -0,0 +1,250 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <limits.h>
+#include <assert.h>
+#include "bits.h"
+#include "constants.h"
+#include "mpdecimal.h"
+#include "typearith.h"
+#include "transpose.h"
+
+
+#define BUFSIZE 4096
+#define SIDE 128
+
+
+/* Definition of the matrix transpose */
+void
+std_trans(mpd_uint_t dest[], mpd_uint_t src[], size_t rows, size_t cols)
+{
+ size_t idest, isrc;
+ size_t r, c;
+
+ for (r = 0; r < rows; r++) {
+ isrc = r * cols;
+ idest = r;
+ for (c = 0; c < cols; c++) {
+ dest[idest] = src[isrc];
+ isrc += 1;
+ idest += rows;
+ }
+ }
+}
+
+/*
+ * Swap half-rows of 2^n * (2*2^n) matrix.
+ * FORWARD_CYCLE: even/odd permutation of the halfrows.
+ * BACKWARD_CYCLE: reverse the even/odd permutation.
+ */
+static int
+swap_halfrows_pow2(mpd_uint_t *matrix, size_t rows, size_t cols, int dir)
+{
+ mpd_uint_t buf1[BUFSIZE];
+ mpd_uint_t buf2[BUFSIZE];
+ mpd_uint_t *readbuf, *writebuf, *hp;
+ size_t *done, dbits;
+ size_t b = BUFSIZE, stride;
+ size_t hn, hmax; /* halfrow number */
+ size_t m, r=0;
+ size_t offset;
+ size_t next;
+
+
+ assert(cols == mul_size_t(2, rows));
+
+ if (dir == FORWARD_CYCLE) {
+ r = rows;
+ }
+ else if (dir == BACKWARD_CYCLE) {
+ r = 2;
+ }
+ else {
+ mpd_err_fatal("swap_halfrows_pow2: illegal argument for \"dir\"");
+ }
+
+ m = cols - 1;
+ hmax = rows; /* cycles start at odd halfrows */
+ dbits = 8 * sizeof *done;
+ if ((done = mpd_calloc(hmax/(sizeof *done) + 1, sizeof *done)) == NULL) {
+ return 0;
+ }
+
+ for (hn = 1; hn <= hmax; hn += 2) {
+
+ if (done[hn/dbits] & mpd_bits[hn%dbits]) {
+ continue;
+ }
+
+ readbuf = buf1; writebuf = buf2;
+
+ for (offset = 0; offset < cols/2; offset += b) {
+
+ stride = (offset + b < cols/2) ? b : cols/2-offset;
+
+ hp = matrix + hn*cols/2;
+ memcpy(readbuf, hp+offset, stride*(sizeof *readbuf));
+ pointerswap(&readbuf, &writebuf);
+
+ next = mulmod_size_t(hn, r, m);
+ hp = matrix + next*cols/2;
+
+ while (next != hn) {
+
+ memcpy(readbuf, hp+offset, stride*(sizeof *readbuf));
+ memcpy(hp+offset, writebuf, stride*(sizeof *writebuf));
+ pointerswap(&readbuf, &writebuf);
+
+ done[next/dbits] |= mpd_bits[next%dbits];
+
+ next = mulmod_size_t(next, r, m);
+ hp = matrix + next*cols/2;
+
+ }
+
+ memcpy(hp+offset, writebuf, stride*(sizeof *writebuf));
+
+ done[hn/dbits] |= mpd_bits[hn%dbits];
+ }
+ }
+
+ mpd_free(done);
+ return 1;
+}
+
+/* In-place transpose of a square matrix */
+static inline void
+squaretrans(mpd_uint_t *buf, size_t cols)
+{
+ mpd_uint_t tmp;
+ size_t idest, isrc;
+ size_t r, c;
+
+ for (r = 0; r < cols; r++) {
+ c = r+1;
+ isrc = r*cols + c;
+ idest = c*cols + r;
+ for (c = r+1; c < cols; c++) {
+ tmp = buf[isrc];
+ buf[isrc] = buf[idest];
+ buf[idest] = tmp;
+ isrc += 1;
+ idest += cols;
+ }
+ }
+}
+
+/*
+ * Transpose 2^n * 2^n matrix. For cache efficiency, the matrix is split into
+ * square blocks with side length 'SIDE'. First, the blocks are transposed,
+ * then a square tranposition is done on each individual block.
+ */
+static void
+squaretrans_pow2(mpd_uint_t *matrix, size_t size)
+{
+ mpd_uint_t buf1[SIDE*SIDE];
+ mpd_uint_t buf2[SIDE*SIDE];
+ mpd_uint_t *to, *from;
+ size_t b = size;
+ size_t r, c;
+ size_t i;
+
+ while (b > SIDE) b >>= 1;
+
+ for (r = 0; r < size; r += b) {
+
+ for (c = r; c < size; c += b) {
+
+ from = matrix + r*size + c;
+ to = buf1;
+ for (i = 0; i < b; i++) {
+ memcpy(to, from, b*(sizeof *to));
+ from += size;
+ to += b;
+ }
+ squaretrans(buf1, b);
+
+ if (r == c) {
+ to = matrix + r*size + c;
+ from = buf1;
+ for (i = 0; i < b; i++) {
+ memcpy(to, from, b*(sizeof *to));
+ from += b;
+ to += size;
+ }
+ continue;
+ }
+ else {
+ from = matrix + c*size + r;
+ to = buf2;
+ for (i = 0; i < b; i++) {
+ memcpy(to, from, b*(sizeof *to));
+ from += size;
+ to += b;
+ }
+ squaretrans(buf2, b);
+
+ to = matrix + c*size + r;
+ from = buf1;
+ for (i = 0; i < b; i++) {
+ memcpy(to, from, b*(sizeof *to));
+ from += b;
+ to += size;
+ }
+
+ to = matrix + r*size + c;
+ from = buf2;
+ for (i = 0; i < b; i++) {
+ memcpy(to, from, b*(sizeof *to));
+ from += b;
+ to += size;
+ }
+ }
+ }
+ }
+
+}
+
+/*
+ * In-place transposition of a 2^n x 2^n or a 2^n x (2*2^n)
+ * or a (2*2^n) x 2^n matrix.
+ */
+int
+transpose_pow2(mpd_uint_t *matrix, size_t rows, size_t cols)
+{
+ size_t size = mul_size_t(rows, cols);
+
+ assert(ispower2(rows));
+ assert(ispower2(cols));
+
+ if (cols == rows) {
+ squaretrans_pow2(matrix, rows);
+ }
+ else if (cols == mul_size_t(2, rows)) {
+ if (!swap_halfrows_pow2(matrix, rows, cols, FORWARD_CYCLE)) {
+ return 0;
+ }
+ squaretrans_pow2(matrix, rows);
+ squaretrans_pow2(matrix+(size/2), rows);
+ }
+ else if (rows == mul_size_t(2, cols)) {
+ squaretrans_pow2(matrix, cols);
+ squaretrans_pow2(matrix+(size/2), cols);
+ if (!swap_halfrows_pow2(matrix, cols, rows, BACKWARD_CYCLE)) {
+ return 0;
+ }
+ }
+ else {
+ mpd_err_fatal("transpose_pow2: illegal matrix size");
+ }
+
+ return 1;
+}
+
+
Added: python/branches/py3k-cdecimal/Modules/cdecimal/transpose.h
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/transpose.h Thu Jan 7 13:02:51 2010
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#ifndef TRANSPOSE_H
+#define TRANSPOSE_H
+
+
+#include <stdio.h>
+#include "mpdecimal.h"
+
+
+enum {FORWARD_CYCLE, BACKWARD_CYCLE};
+
+
+void std_trans(mpd_uint_t dest[], mpd_uint_t src[], size_t rows, size_t cols);
+int transpose_pow2(mpd_uint_t *matrix, size_t rows, size_t cols);
+void transpose_3xpow2(mpd_uint_t *matrix, size_t rows, size_t cols);
+
+
+static inline void pointerswap(mpd_uint_t **a, mpd_uint_t **b)
+{
+ mpd_uint_t *tmp;
+
+ tmp = *b;
+ *b = *a;
+ *a = tmp;
+}
+
+
+#endif
Added: python/branches/py3k-cdecimal/Modules/cdecimal/transpose3.c
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/transpose3.c Thu Jan 7 13:02:51 2010
@@ -0,0 +1,519 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#include <stdlib.h>
+#include <string.h>
+#include <limits.h>
+#include <assert.h>
+#include "bits.h"
+#include "constants.h"
+#include "mpdecimal.h"
+#include "typearith.h"
+#include "transpose.h"
+
+
+/*
+ * In situ transposition of a 3 x 2^n or 2^n x 3 matrix. For efficient memory
+ * access, we split the transposition into two steps. In the 3 x 2^n case, we
+ * first perform a block matrix transpose on blocks of size BMEMB followed by
+ * a series of 3 x BMEMB transposes. Example with BMEMB = 4:
+ *
+ * Input 3 x 2 block matrix:
+ *
+ * 0 1 2 3 4 5 6 7
+ * 8 9 10 11 12 13 14 15
+ * 16 17 18 19 20 21 22 23
+ *
+ * After the block transpose:
+ *
+ * 0 1 2 3 8 9 10 11 16 17 18 19
+ * 4 5 6 7 12 13 14 15 20 21 22 23
+ *
+ * After performing two 3 x BMEMB transpositions:
+ *
+ * 0 8 16
+ * 1 9 17
+ * 2 10 18
+ * (...)
+ *
+ * In the 2^n x 3 case, we simply do the steps in reverse order.
+ *
+ * For efficient in-place block transposition, we swap the blocks cyclically.
+ * The starting points of the distinct cycles are precalculated. The arrays
+ * below contain the block numbers, which have to be multiplied by BMEMB to
+ * get the actual addresses. In an m x n block matrix, the next block number t
+ * as a function of the current block number s is calculated by:
+ *
+ * t = m*s % (m*n - 1)
+ *
+ * The inverse of the transpose is:
+ *
+ * t = n*s % (m*n - 1)
+ *
+ * (This does not apply to the last block, which is not moved anyway.)
+ *
+ */
+
+
+/* Cycle start points */
+static const size_t c0[] = {SIZE_MAX}; /* 2^0 blocks */
+static const size_t c1[] = {1, SIZE_MAX}; /* 2^1 blocks */
+static const size_t c2[] = {1, 2, SIZE_MAX}; /* 2^2 blocks */
+static const size_t c3[] = {1, 5, SIZE_MAX}; /* (...) */
+static const size_t c4[] = {1, 5, SIZE_MAX};
+static const size_t c5[] = {1, 5, 7, 19, SIZE_MAX};
+static const size_t c6[] = {1, 7, SIZE_MAX};
+static const size_t c7[] = {1, 5, SIZE_MAX};
+static const size_t c8[] = {
+ 1, 2, 4, 5, 7, 8, 10, 13, 14, 26, 59, 118, 236, 413, SIZE_MAX
+};
+static const size_t c9[] = {
+ 1, 2, 4, 5, 7, 10, 11, 13, 14, 17, 20, 22, 23, 25, 28, 34, 35, 37, 46, 50,
+ 53, 68, 70, 74, 92, 100, 140, 307, SIZE_MAX
+};
+static const size_t c10[] = {1, 2, 17, 34, 37, 74, 83, 166, SIZE_MAX};
+static const size_t c11[] = {1, 5, SIZE_MAX};
+static const size_t c12[] = {
+ 1, 2, 4, 5, 7, 8, 11, 13, 14, 16, 17, 22, 25, 26, 32, 35, 41, 44, 49, 52,
+ 53, 55, 61, 65, 77, 82, 88, 103, 104, 154, 164, 176, 275, 352, 385, 539,
+ 1117, 2234, SIZE_MAX
+};
+static const size_t c13[] = {1, 5, 11, 25, 55, 125, 983, 4915, SIZE_MAX};
+static const size_t c14[] = {
+ 1, 2, 5, 7, 10, 13, 14, 23, 26, 46, 115, 230, 2137, 10685, SIZE_MAX
+};
+static const size_t c15[] = {1, 5, 11, 17, 23, 31, 197, 499, 985, 2167, SIZE_MAX};
+static const size_t c16[] = {
+ 1, 2, 4, 5, 8, 10, 11, 22, 421, 467, 842, 934, 1868, 3736, SIZE_MAX
+};
+static const size_t c17[] = {
+ 1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 20, 22, 23, 25, 26, 28, 29, 31,
+ 32, 34, 38, 40, 41, 43, 44, 46, 47, 50, 52, 53, 55, 56, 58, 59, 62, 64, 65,
+ 67, 68, 71, 73, 76, 77, 80, 82, 83, 85, 86, 88, 91, 92, 94, 95, 97, 100, 103,
+ 106, 110, 112, 115, 116, 118, 121, 128, 130, 134, 136, 137, 143, 146, 149,
+ 152, 155, 160, 161, 163, 166, 170, 176, 181, 187, 190, 194, 197, 200, 205,
+ 206, 209, 215, 221, 224, 227, 230, 232, 235, 251, 256, 263, 265, 272, 274,
+ 275, 277, 287, 295, 304, 310, 311, 320, 322, 326, 335, 337, 340, 341, 359,
+ 365, 380, 388, 410, 412, 442, 460, 470, 485, 502, 515, 530, 544, 548, 550,
+ 571, 575, 577, 589, 605, 613, 622, 644, 680, 685, 691, 715, 730, 745, 905,
+ 935, 970, 1226, 1795, 78643, SIZE_MAX
+};
+static const size_t c18[] = {1, 7, SIZE_MAX};
+static const size_t c19[] = {1, 5, 7, 13, 71, 355, 22153, 155071, SIZE_MAX};
+static const size_t c20[] = {
+ 1, 2, 4, 5, 7, 8, 10, 13, 14, 26, 241979, 483958, 967916, 1693853, SIZE_MAX
+};
+static const size_t c21[] = {1, 2, 4, 5, 7, 10, 14, 19, 20, 1258291, SIZE_MAX};
+static const size_t c22[] = {
+ 1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 20, 22, 23, 25, 26, 28, 29, 31,
+ 32, 34, 35, 37, 38, 40, 41, 43, 46, 47, 49, 50, 52, 56, 58, 61, 62, 64, 67,
+ 68, 70, 71, 73, 74, 76, 77, 79, 82, 83, 85, 86, 92, 94, 95, 97, 98, 100, 101,
+ 103, 104, 107, 109, 112, 113, 115, 116, 119, 121, 122, 124, 127, 128, 131,
+ 133, 136, 139, 140, 142, 143, 145, 146, 148, 149, 151, 152, 154, 155, 157,
+ 161, 163, 164, 166, 169, 172, 173, 179, 181, 184, 187, 190, 196, 197, 200,
+ 202, 205, 206, 208, 209, 214, 215, 217, 218, 223, 224, 229, 230, 232, 233,
+ 239, 241, 245, 248, 253, 257, 263, 266, 269, 272, 278, 280, 281, 283, 284,
+ 286, 289, 302, 304, 314, 319, 322, 323, 328, 329, 335, 338, 344, 346, 349,
+ 355, 358, 359, 365, 368, 373, 374, 377, 379, 380, 389, 392, 394, 407, 409,
+ 410, 416, 418, 425, 430, 431, 433, 436, 437, 448, 451, 457, 458, 460, 463,
+ 464, 466, 473, 478, 482, 485, 490, 496, 505, 511, 521, 526, 532, 533, 541,
+ 544, 556, 557, 559, 562, 566, 568, 569, 589, 593, 604, 646, 676, 679, 697,
+ 703, 713, 716, 743, 746, 749, 784, 799, 814, 815, 827, 832, 865, 866, 871,
+ 877, 893, 902, 913, 916, 946, 1031, 1039, 1075, 1079, 1114, 1127, 1292, 1387,
+ 1445, 1463, 1723, 2299, 103991, 207982, 415964, 519955, 727937, 831928,
+ 1039910, 1143901, 1351883, 1663856, 1767847, 1975829, 2079820, 2287802,
+ 2599775, 2703766, 3223721, 3535694, 3639685, 3951658, 4159640, 6343451,
+ 6967397, 7903316, SIZE_MAX
+};
+static const size_t c23[] = {
+ 1, 5, 7, 11, 13, 17, 19, 23, 25, 29, 31, 35, 37, 43, 47, 49, 59, 61, 65, 67,
+ 71, 77, 83, 85, 95, 97, 101, 103, 107, 113, 119, 125, 133, 145, 151, 163, 175,
+ 179, 185, 187, 199, 203, 209, 217, 221, 229, 239, 247, 269, 281, 289, 319,
+ 341, 377, 413, 421, 475, 479, 493, 551, 587, 703, 725, 841, 1421, 1463, 1885,
+ 1943, 2407, 2755, 45673, 502403, 867787, 1324517, SIZE_MAX
+};
+static const size_t c24[] = {
+ 1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 20, 22, 23, 25, 26, 28, 29, 31,
+ 32, 34, 35, 37, 38, 40, 41, 43, 44, 47, 49, 50, 52, 53, 55, 56, 58, 59, 61,
+ 62, 65, 67, 68, 70, 71, 73, 74, 76, 79, 80, 82, 83, 85, 86, 88, 89, 91, 94,
+ 95, 97, 98, 100, 101, 103, 106, 107, 109, 112, 113, 115, 116, 118, 119, 121,
+ 122, 124, 125, 130, 133, 136, 137, 140, 142, 143, 146, 148, 149, 151, 152,
+ 160, 161, 164, 166, 167, 169, 170, 172, 173, 175, 176, 178, 179, 181, 187,
+ 188, 190, 191, 193, 194, 196, 197, 199, 200, 202, 203, 211, 212, 214, 215,
+ 217, 221, 223, 224, 226, 229, 232, 235, 238, 241, 242, 244, 247, 250, 253,
+ 259, 260, 263, 265, 266, 269, 272, 274, 275, 277, 280, 281, 283, 284, 286,
+ 287, 292, 293, 295, 296, 298, 301, 302, 304, 305, 307, 313, 317, 328, 329,
+ 332, 334, 335, 337, 338, 340, 341, 343, 346, 347, 352, 353, 356, 361, 362,
+ 365, 367, 373, 374, 376, 377, 379, 380, 382, 386, 388, 391, 392, 394, 398,
+ 400, 401, 406, 419, 422, 424, 425, 428, 430, 433, 434, 437, 442, 445, 446,
+ 449, 452, 455, 458, 461, 463, 467, 470, 475, 476, 479, 482, 487, 488, 494,
+ 497, 503, 505, 511, 515, 517, 518, 523, 526, 529, 530, 532, 538, 544, 547,
+ 548, 551, 557, 560, 565, 566, 568, 569, 571, 572, 575, 577, 581, 583, 587,
+ 589, 590, 593, 595, 596, 602, 604, 610, 613, 614, 619, 623, 634, 643, 647,
+ 649, 664, 668, 674, 689, 691, 692, 694, 706, 707, 719, 721, 722, 727, 730,
+ 733, 737, 745, 748, 754, 760, 764, 767, 776, 781, 787, 788, 791, 800, 805,
+ 821, 823, 833, 835, 838, 844, 845, 848, 850, 856, 868, 875, 881, 883, 884,
+ 890, 892, 893, 899, 904, 905, 907, 916, 926, 931, 949, 964, 976, 979, 989,
+ 991, 995, 1010, 1019, 1022, 1036, 1043, 1046, 1055, 1064, 1073, 1075, 1091,
+ 1094, 1102, 1114, 1115, 1136, 1138, 1142, 1147, 1166, 1174, 1186, 1190, 1204,
+ 1211, 1219, 1220, 1238, 1246, 1273, 1279, 1297, 1298, 1301, 1315, 1325, 1327,
+ 1378, 1388, 1405, 1414, 1451, 1459, 1483, 1490, 1501, 1519, 1531, 1543, 1562,
+ 1574, 1633, 1646, 1676, 1690, 1709, 1814, 1862, 1867, 2021, 2128, 2171, 2219,
+ 2267, 2332, 2348, 2491, 2558, 2657, 2971, 3127, 3191, 3211, 3724, 3829, 4079,
+ 6563, 7669, 13126, 15338, 26252, 32815, 38345, 52504, 53683, 65630, 72193,
+ 76690, 84359, 99697, 105008, 107366, 130373, 131260, 144386, 168718, 176387,
+ 191725, 199394, 203453, 222401, 260746, 283753, 288772, 314429, 329767,
+ 375781, 406457, 421795, 444802, 452471, 498485, 544499, 605851, 651865,
+ 659534, 682541, 751562, 904942, 1234709, 1510793, 1648835, SIZE_MAX
+};
+static const size_t c25[] = {
+ 1, 5, 7, 11, 13, 17, 23, 25, 31, 49, 67, 115, 161, 253, 391, 875333, 4376665,
+ 6127331, 20132659, 21883325, SIZE_MAX
+};
+static const size_t c26[] = {
+ 1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 20, 22, 23, 25, 26, 28, 29, 31,
+ 32, 34, 35, 37, 38, 40, 41, 43, 44, 46, 47, 49, 50, 52, 53, 55, 56, 58, 59,
+ 61, 62, 64, 65, 67, 68, 70, 71, 73, 74, 76, 77, 79, 80, 82, 83, 88, 89, 91,
+ 92, 94, 97, 98, 100, 101, 103, 104, 106, 107, 109, 110, 112, 113, 115, 118,
+ 121, 122, 124, 125, 128, 130, 131, 133, 134, 136, 137, 139, 140, 142, 143,
+ 145, 146, 151, 152, 154, 155, 157, 158, 160, 161, 163, 164, 167, 169, 173,
+ 175, 176, 178, 179, 181, 184, 185, 187, 193, 194, 197, 199, 200, 202, 203,
+ 205, 206, 208, 209, 211, 212, 214, 215, 217, 218, 220, 221, 223, 224, 226,
+ 227, 229, 230, 233, 236, 241, 242, 244, 245, 247, 248, 250, 251, 253, 256,
+ 257, 259, 260, 262, 263, 265, 266, 268, 271, 272, 274, 278, 280, 281, 283,
+ 284, 286, 287, 289, 290, 292, 295, 301, 302, 304, 305, 307, 310, 313, 314,
+ 316, 317, 319, 320, 322, 323, 326, 328, 329, 335, 337, 338, 346, 347, 349,
+ 350, 352, 353, 356, 358, 361, 362, 367, 368, 370, 371, 373, 377, 383, 385,
+ 386, 391, 394, 395, 397, 398, 400, 401, 403, 404, 406, 407, 409, 410, 412,
+ 413, 416, 418, 419, 421, 422, 424, 428, 431, 433, 434, 436, 437, 440, 442,
+ 445, 446, 448, 449, 451, 452, 454, 455, 458, 460, 463, 466, 467, 469, 472,
+ 473, 481, 482, 484, 485, 488, 490, 491, 493, 494, 496, 500, 502, 503, 506,
+ 511, 512, 514, 517, 518, 521, 523, 524, 527, 529, 530, 533, 536, 544, 545,
+ 547, 548, 551, 553, 556, 560, 562, 569, 571, 574, 575, 577, 581, 583, 584,
+ 587, 589, 593, 599, 604, 605, 608, 610, 611, 614, 617, 620, 623, 625, 628,
+ 631, 632, 634, 637, 638, 640, 641, 644, 647, 652, 653, 658, 659, 661, 667,
+ 670, 671, 676, 683, 691, 692, 694, 697, 698, 704, 706, 707, 712, 713, 716,
+ 719, 722, 724, 727, 731, 733, 734, 736, 737, 746, 749, 751, 757, 763, 766,
+ 769, 770, 773, 775, 785, 788, 790, 791, 793, 794, 797, 799, 800, 802, 806,
+ 808, 809, 814, 815, 820, 821, 823, 824, 826, 832, 844, 847, 848, 851, 853,
+ 859, 862, 865, 868, 871, 874, 880, 881, 883, 890, 892, 895, 896, 901, 902,
+ 905, 908, 920, 923, 926, 932, 934, 938, 941, 944, 953, 961, 962, 964, 967,
+ 968, 977, 979, 982, 989, 991, 1000, 1001, 1003, 1004, 1012, 1015, 1019,
+ 1021, 1024, 1028, 1031, 1034, 1037, 1042, 1046, 1057, 1061, 1067, 1072,
+ 1079, 1088, 1090, 1093, 1094, 1103, 1106, 1112, 1121, 1124, 1127, 1133,
+ 1138, 1142, 1145, 1148, 1154, 1157, 1166, 1168, 1169, 1178, 1183, 1205,
+ 1208, 1216, 1219, 1220, 1223, 1225, 1234, 1240, 1243, 1246, 1247, 1250,
+ 1262, 1265, 1267, 1271, 1280, 1288, 1289, 1294, 1295, 1303, 1304, 1307,
+ 1315, 1339, 1342, 1366, 1382, 1393, 1396, 1412, 1415, 1417, 1423, 1424,
+ 1432, 1448, 1466, 1468, 1474, 1487, 1498, 1501, 1502, 1514, 1523, 1525,
+ 1538, 1543, 1546, 1549, 1561, 1565, 1570, 1577, 1580, 1582, 1607, 1612,
+ 1642, 1649, 1664, 1667, 1691, 1717, 1735, 1762, 1780, 1783, 1784, 1840,
+ 1846, 1852, 1859, 1864, 1868, 1876, 1879, 1888, 1897, 1927, 1928, 1934,
+ 1949, 1954, 1964, 1982, 2009, 2024, 2030, 2038, 2042, 2053, 2057, 2062,
+ 2065, 2092, 2114, 2147, 2173, 2188, 2203, 2224, 2233, 2237, 2239, 2266,
+ 2276, 2293, 2333, 2345, 2383, 2432, 2438, 2441, 2446, 2450, 2468, 2501,
+ 2530, 2560, 2576, 2659, 2732, 2735, 2786, 2813, 2848, 2915, 2948, 2957,
+ 2981, 3031, 3046, 3076, 3115, 3157, 3160, 3164, 3185, 3193, 3298, 3407,
+ 3560, 3619, 3737, 3752, 3856, 3898, 3971, 3985, 4076, 4228, 4478, 4853,
+ 5896, 6115, 8561, 12230, 15899, 17122, 20791, 23237, 28129, 30575, 35467,
+ 37913, 45251, 56258, 57481, 75826, 81941, 86833, 108847, 114962, 163882,
+ 164617, 173666, 217694, 329234, 658468, 823085, 1152319, 1316936, 1646170,
+ 1810787, 2798489, 3127723, 3292340, 3621574, 3786191, 4773893, 5761595,
+ 6090829, 6255446, 6584680, 6749297, 7243148, 8066233, 9053935, 9547786,
+ 12675509, 13498594, 21894061, SIZE_MAX
+};
+static const size_t c27[] = {
+ 1, 2, 4, 5, 7, 10, 11, 13, 14, 17, 19, 20, 22, 23, 26, 31, 35, 37, 43, 47, 52,
+ 55, 59, 61, 65, 67, 70, 71, 74, 83, 85, 89, 91, 94, 130, 131, 134, 142, 163,
+ 182, 188, 268, 329, 335, 517, 611, 658, 670, 799, 893, 1034, 1081, 1222, 1273,
+ 1457, 2021, 2444, 2867, 3149, 3337, 4277, 6298, 12596, 127867, 255734, 511468,
+ 639335, 1278670, 1406537, 6009749, 8567089, 12019498, 24038996, 42835445,
+ SIZE_MAX
+};
+static const size_t c28[] = {
+ 1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 17, 19, 20, 22, 23, 25, 26, 28, 29, 31, 34,
+ 35, 37, 38, 40, 41, 43, 44, 46, 49, 50, 52, 53, 55, 56, 58, 61, 62, 65, 67,
+ 68, 70, 71, 73, 74, 76, 77, 79, 82, 83, 85, 86, 88, 92, 95, 98, 100, 101, 103,
+ 104, 106, 107, 109, 110, 113, 115, 116, 119, 121, 122, 124, 125, 127, 130,
+ 131, 133, 134, 136, 137, 140, 142, 143, 145, 146, 151, 152, 154, 155, 158,
+ 161, 164, 166, 167, 170, 172, 173, 175, 181, 185, 190, 191, 193, 196, 197,
+ 200, 203, 205, 206, 209, 214, 217, 218, 221, 226, 230, 232, 238, 239, 242,
+ 244, 247, 248, 253, 254, 259, 260, 265, 266, 269, 271, 274, 280, 281, 284,
+ 289, 292, 293, 299, 301, 310, 311, 313, 316, 323, 325, 328, 334, 340, 341,
+ 343, 344, 346, 347, 350, 355, 359, 362, 365, 367, 370, 371, 379, 380, 382,
+ 385, 386, 392, 395, 397, 403, 406, 415, 427, 428, 431, 442, 449, 452, 457,
+ 461, 463, 473, 476, 478, 484, 488, 491, 494, 506, 509, 518, 521, 529, 530,
+ 532, 538, 539, 545, 548, 551, 563, 578, 586, 587, 593, 595, 598, 601, 613,
+ 622, 626, 629, 632, 643, 646, 659, 665, 667, 671, 685, 686, 710, 721, 730,
+ 731, 737, 758, 760, 770, 790, 835, 851, 854, 862, 883, 887, 905, 914, 923,
+ 926, 937, 952, 956, 983, 1009, 1012, 1025, 1069, 1126, 1156, 1172, 1241,
+ 1244, 1258, 1273, 1372, 1420, 1447, 1495, 1507, 1580, 1670, 2111, 2138,
+ 15683, 31366, 51349, 62732, 78415, 102698, 109781, 125464, 156830, 172513,
+ 203879, 219562, 266611, 313660, 345026, 360709, 392075, 407758, 439124,
+ 454807, 486173, 533222, 548905, 580271, 627320, 643003, 674369, 690052,
+ 721418, 768467, 784150, 815516, 831199, 862565, 878248, 909614, 972346,
+ 1019395, 1050761, 1066444, 1113493, 1144859, 1160542, 1207591, 1301689,
+ 1348738, 1380104, 1442836, 1536934, 1568300, 1583983, 1615349, 1631032,
+ 1662398, 1725130, 1772179, 1803545, 1819228, 1897643, 1944692, 1960375,
+ 1991741, 2038790, 2054473, 2101522, 2226986, 2242669, 2274035, 2289718,
+ 2368133, 2415182, 2430865, 2524963, 2603378, 2619061, 2697476, 2713159,
+ 2744525, 2838623, 2901355, 2995453, 3026819, 3073868, 3089551, 3136600,
+ 3183649, 3215015, 3403211, 3465943, 3544358, 3607090, 3638456, 3795286,
+ 3967799, 3983482, 4061897, 4077580, 4155995, 4218727, 4406923, 4453972,
+ 4532387, 4720583, 4877413, 5238122, 5347903, 5394952, 5442001, 5677246,
+ 5724295, 5802710, 5818393, 5990906, 6037955, 6053638, 6147736, 6367298,
+ 6508445, 6759373, 6931886, 7041667, 7088716, 7167131, 7590572, 8123794,
+ 8829529, 9064774, 9425483, 9754826, 10335097, 11307443, 11448590, 13518746,
+ 18129548, SIZE_MAX
+};
+static const size_t c29[] = {
+ 1, 5, 7, 11, 13, 17, 19, 23, 25, 29, 31, 35, 37, 41, 43, 47, 49, 53, 55, 59,
+ 61, 65, 67, 71, 73, 77, 79, 83, 85, 89, 91, 95, 97, 101, 103, 107, 109, 113,
+ 115, 119, 121, 125, 127, 131, 133, 137, 139, 143, 145, 149, 151, 155, 157,
+ 161, 167, 169, 173, 175, 179, 181, 185, 187, 191, 197, 203, 209, 211, 215,
+ 217, 223, 227, 233, 235, 239, 241, 245, 247, 251, 253, 257, 259, 263, 265,
+ 269, 271, 275, 277, 281, 283, 289, 293, 295, 299, 305, 307, 313, 317, 319,
+ 323, 329, 337, 341, 343, 347, 349, 353, 355, 359, 367, 371, 373, 377, 379,
+ 383, 385, 389, 395, 397, 407, 413, 415, 419, 425, 427, 431, 433, 437, 443,
+ 445, 449, 455, 457, 469, 479, 481, 485, 487, 491, 493, 497, 499, 503, 511,
+ 517, 523, 529, 533, 535, 539, 541, 547, 553, 557, 565, 569, 575, 589, 593,
+ 599, 605, 611, 617, 619, 623, 635, 637, 641, 643, 649, 653, 655, 661, 677,
+ 679, 685, 701, 703, 707, 715, 719, 721, 727, 731, 739, 743, 745, 755, 761,
+ 769, 775, 781, 785, 787, 793, 797, 799, 821, 823, 829, 845, 853, 863, 871,
+ 881, 895, 907, 917, 919, 929, 935, 941, 943, 947, 949, 955, 961, 967, 973,
+ 977, 979, 991, 997, 1001, 1003, 1007, 1015, 1019, 1027, 1031, 1033, 1043,
+ 1045, 1049, 1051, 1057, 1063, 1067, 1073, 1075, 1079, 1085, 1087, 1093,
+ 1097, 1099, 1109, 1117, 1129, 1147, 1151, 1157, 1165, 1169, 1171, 1187,
+ 1189, 1199, 1201, 1205, 1207, 1211, 1213, 1219, 1235, 1237, 1247, 1249,
+ 1259, 1261, 1265, 1271, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307,
+ 1313, 1315, 1319, 1321, 1327, 1343, 1345, 1367, 1369, 1375, 1385, 1387,
+ 1399, 1403, 1409, 1423, 1427, 1439, 1441, 1453, 1463, 1477, 1487, 1499,
+ 1501, 1511, 1523, 1525, 1535, 1565, 1595, 1627, 1631, 1633, 1637, 1649,
+ 1657, 1673, 1685, 1687, 1699, 1705, 1711, 1715, 1727, 1745, 1751, 1757,
+ 1771, 1811, 1823, 1829, 1843, 1865, 1873, 1897, 1957, 1963, 1967, 1975,
+ 1979, 2017, 2039, 2065, 2075, 2093, 2143, 2153, 2191, 2207, 2231, 2339,
+ 2359, 2405, 2425, 2437, 2443, 2471, 2473, 2479, 2507, 2533, 2573, 2579,
+ 2581, 2617, 2645, 2651, 2695, 2729, 2813, 2827, 2867, 2941, 2959, 3007,
+ 3031, 3055, 3059, 3085, 3173, 3181, 3197, 3221, 3247, 3275, 3377, 3395,
+ 3467, 3505, 3521, 3553, 3559, 3589, 3607, 3611, 3671, 3715, 3875, 3977,
+ 3983, 4049, 4129, 4171, 4183, 4187, 4315, 4559, 4691, 4753, 4777, 4807,
+ 4993, 5141, 5155, 5167, 5279, 5495, 5509, 5723, 5735, 5917, 6017, 6499,
+ 6887, 7081, 7217, 7265, 7663, 8051, 8245, 9215, 9797, 9991, 10379, 10573,
+ 11155, 11341, 11737, 12319, 13403, 13483, 13871, 14065, 14453, 15035, 15617,
+ 16105, 17527, 17557, 18139, 18527, 19589, 22547, 22795, 23183, 23713, 25775,
+ 29585, 29899, 30361, 31331, 31961, 35431, 36085, 38147, 41873, 42271, 44333,
+ 48457, 50519, 54643, 54757, 55193, 56705, 60829, 62891, 67015, 69077, 73201,
+ 74083, 75263, 75757, 79387, 80525, 81449, 85573, 87635, 91759, 93409, 93821,
+ 97945, 99851, 100007, 104131, 106193, 110317, 112735, 116503, 118565, 119177,
+ 122689, 124751, 128875, 130937, 135061, 137123, 141247, 147433, 149495,
+ 151387, 153619, 159805, 161867, 165991, 170713, 172177, 174239, 178363,
+ 180425, 184549, 186611, 190735, 192797, 196481, 196921, 215479, 217541,
+ 221665, 223727, 228691, 229913, 234037, 240223, 242285, 248471, 252595,
+ 254459, 254657, 258781, 260843, 264967, 267029, 271153, 273215, 277339,
+ 279401, 285587, 291773, 297959, 304145, 308269, 312437, 316517, 322703,
+ 326827, 328889, 333013, 339199, 347447, 351571, 353633, 357757, 359819,
+ 363943, 366005, 378377, 382501, 384563, 388687, 390749, 394873, 396935,
+ 401059, 407245, 419617, 425803, 427865, 431989, 438175, 440237, 441277,
+ 446423, 450547, 469105, 471167, 483539, 486371, 493849, 495911, 499255,
+ 500035, 502097, 506221, 508283, 533027, 539213, 545399, 549523, 551585,
+ 555709, 557771, 582515, 586639, 592825, 607259, 611383, 629941, 636127,
+ 642313, 673243, 681491, 697987, 700049, 706235, 722731, 724793, 741289,
+ 743351, 766033, 784591, 799025, 809335, 817583, 821707, 871195, 889753,
+ 922745, 935117, 945427, 947489, 963985, 970171, 972233, 984605, 990791,
+ 1007287, 1021721, 1027907, 1032031, 1034093, 1038217, 1050589, 1075333,
+ 1100077, 1106263, 1112449, 1120697, 1126883, 1163999, 1242355, 1244417,
+ 1275347, 1285657, 1298029, 1300091, 1310401, 1328959, 1331021, 1368137,
+ 1384633, 1386695, 1411439, 1427935, 1442369, 1562185, 1681561, 1683623,
+ 1687747, 1700119, 1751669, 1757855, 1825901, 1900133, 2036225, 2079527,
+ 2187059, 2500175, 2652763, 2778545, 2914637, 3320851, 3500245, 3663143,
+ 3700259, 4100287, 4300301, 4700329, 4900343, 5300371, 5900413, 6100427,
+ 7100497, 7900553, 8300581, 8500595, 10300721, 10700749, 10935295, 14301001,
+ 16604255, 23245957, 23501645, 36529361, 43171063, 56454467, 83021275,
+ 96304679, 156079997, 176005103, 322122547, SIZE_MAX
+};
+static const size_t c30[] = {
+ 1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 20, 22, 23, 25, 26, 28, 29, 31,
+ 32, 34, 35, 37, 38, 40, 41, 43, 44, 46, 47, 50, 52, 53, 55, 56, 58, 61, 62,
+ 64, 65, 67, 68, 70, 71, 73, 74, 76, 77, 79, 80, 82, 83, 85, 86, 88, 89, 91,
+ 92, 94, 95, 97, 100, 101, 103, 104, 106, 107, 109, 110, 112, 113, 115, 116,
+ 119, 122, 124, 125, 127, 128, 130, 133, 134, 136, 137, 142, 143, 145, 146,
+ 148, 149, 152, 154, 155, 157, 158, 160, 161, 163, 164, 166, 167, 172, 175,
+ 176, 178, 179, 181, 182, 185, 187, 190, 193, 194, 197, 199, 200, 202, 203,
+ 205, 206, 208, 209, 211, 212, 214, 215, 217, 218, 220, 221, 223, 224, 226,
+ 227, 229, 230, 232, 235, 238, 239, 244, 250, 251, 253, 254, 256, 257, 259,
+ 260, 263, 265, 266, 268, 269, 271, 272, 275, 277, 284, 286, 287, 290, 292,
+ 296, 298, 299, 304, 308, 311, 313, 316, 317, 319, 320, 322, 323, 325, 326,
+ 328, 329, 331, 332, 334, 335, 337, 344, 347, 349, 353, 355, 356, 358, 359,
+ 362, 364, 365, 367, 370, 371, 373, 374, 377, 379, 380, 383, 385, 386, 388,
+ 389, 391, 394, 395, 397, 398, 401, 403, 404, 407, 410, 415, 416, 421, 422,
+ 424, 425, 430, 431, 433, 434, 436, 437, 440, 442, 443, 446, 448, 449, 451,
+ 452, 457, 458, 463, 464, 467, 470, 475, 488, 491, 499, 500, 503, 505, 506,
+ 508, 511, 512, 514, 515, 518, 520, 521, 523, 526, 527, 530, 532, 533, 535,
+ 538, 541, 542, 544, 547, 550, 553, 554, 557, 559, 565, 568, 569, 571, 572,
+ 574, 575, 577, 580, 584, 587, 589, 592, 593, 595, 598, 599, 601, 611, 616,
+ 619, 622, 623, 625, 626, 629, 631, 632, 635, 638, 640, 641, 646, 650, 652,
+ 656, 658, 659, 661, 662, 664, 667, 668, 670, 673, 677, 679, 689, 691, 694,
+ 697, 698, 706, 707, 709, 712, 713, 716, 718, 725, 728, 734, 737, 739, 742,
+ 748, 757, 758, 760, 761, 769, 770, 772, 773, 776, 778, 779, 781, 782, 788,
+ 790, 791, 793, 794, 796, 799, 802, 806, 809, 814, 817, 821, 827, 829, 830,
+ 832, 835, 844, 862, 868, 872, 874, 880, 884, 887, 892, 893, 896, 901, 902,
+ 911, 919, 925, 928, 935, 943, 965, 971, 977, 982, 983, 985, 991, 1000,
+ 1010, 1012, 1015, 1016, 1019, 1022, 1024, 1025, 1027, 1028, 1030, 1031,
+ 1033, 1036, 1043, 1049, 1054, 1060, 1061, 1064, 1066, 1070, 1073, 1082,
+ 1084, 1100, 1106, 1114, 1130, 1133, 1136, 1148, 1154, 1160, 1168, 1169,
+ 1174, 1178, 1181, 1184, 1201, 1232, 1237, 1241, 1249, 1250, 1252, 1258,
+ 1261, 1262, 1264, 1270, 1271, 1285, 1291, 1292, 1301, 1304, 1307, 1318,
+ 1322, 1324, 1334, 1336, 1343, 1354, 1369, 1373, 1379, 1381, 1382, 1385,
+ 1388, 1391, 1393, 1396, 1414, 1427, 1429, 1432, 1436, 1439, 1456, 1468,
+ 1477, 1489, 1495, 1496, 1516, 1520, 1522, 1531, 1538, 1544, 1552, 1555,
+ 1576, 1582, 1588, 1589, 1592, 1595, 1598, 1612, 1615, 1618, 1625, 1627,
+ 1634, 1639, 1642, 1649, 1651, 1654, 1675, 1693, 1709, 1724, 1759, 1765,
+ 1774, 1781, 1783, 1792, 1802, 1822, 1838, 1847, 1856, 1873, 1921, 1925,
+ 1945, 1951, 2005, 2021, 2029, 2044, 2048, 2050, 2077, 2105, 2108, 2120,
+ 2123, 2146, 2155, 2164, 2177, 2191, 2200, 2212, 2215, 2260, 2266, 2272,
+ 2293, 2308, 2315, 2320, 2341, 2356, 2413, 2455, 2495, 2498, 2522, 2540,
+ 2584, 2602, 2629, 2635, 2648, 2672, 2723, 2738, 2759, 2765, 2782, 2786,
+ 2833, 2878, 2917, 2954, 2978, 3017, 3110, 3145, 3236, 3350, 3383, 3391,
+ 3427, 3448, 3529, 3593, 3676, 4310, 4351, 4640, 4741, 4993, 5603, 5789,
+ 6034, 6896, 6973, 7327, 8189, 8620, 9482, 10775, 12068, 12499, 13361,
+ 13792, 14654, 15085, 17240, 18533, 21550, 22843, 24136, 24998, 26291,
+ 26722, 28015, 28877, 29308, 30601, 31463, 36635, 38359, 39221, 41807,
+ 43100, 45686, 46979, 48703, 49996, 51289, 52582, 57754, 58616, 59047,
+ 61633, 62926, 70253, 76718, 96113, 97406, 98699, 102578, 113353, 142661,
+ 153005, 7473841, 37369205, 52316887, 82212251, 97159933, 142002979,
+ 171898343, 231689071, 261584435, 351270527, SIZE_MAX
+};
+
+#ifdef CONFIG_64
+
+#if SIZE_MAX != 18446744073709551615ULL
+ #error "transpose3: need 64 bits for SIZE_MAX"
+#endif
+/* Maximum n for 3 * 2^n matrix, limited by log2(2^n/BMEMB) <= 30.
+ * This limit can be raised by increasing BMEMB or by extending
+ * the above cycle tables beyond 30. */
+#define MAXN 42
+#define BMEMB 4096 /* block members */
+
+/* END CONFIG_64 */
+#else
+
+#if SIZE_MAX != 4294967295UL
+ #error "transpose3: need 32 bits for SIZE_MAX"
+#endif
+#define MAXN 30 /* maximum n for 3 * 2^n matrix, limited by SIZE_MAX */
+#define BMEMB 4096 /* block members */
+
+#endif /* END CONFIG_32 */
+
+
+/* all cycles */
+static const size_t *start[] = {
+ c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15, c16,
+ c17, c18, c19, c20, c21, c22, c23, c24, c25, c26, c27, c28, c29, c30
+};
+
+
+
+/*
+ * Block transpose on a 3 x 2^n or a 2^n x 3 matrix. 2^n is split into
+ * nprime blocks of size BMEMB, and the blocks are transposed cyclically.
+ */
+static void
+_block_transpose_3xpow2(mpd_uint_t *matrix, size_t rows, size_t cols)
+{
+ mpd_uint_t buf1[BMEMB];
+ mpd_uint_t buf2[BMEMB];
+ mpd_uint_t *readbuf, *writebuf;
+ size_t nprime; /* number of blocks per row (or column) */
+ size_t log2n;
+ size_t a, mod;
+ size_t s, next;
+ size_t i;
+
+
+ if (rows == 3) {
+ nprime = cols / BMEMB;
+ a = 3;
+ }
+ else { /* cols == 3 */
+ nprime = rows / BMEMB;
+ a = nprime;
+ }
+
+ log2n = BSR(nprime);
+ mod = 3 * nprime - 1;
+
+ for (i = 0; start[log2n][i] != SIZE_MAX; i++) {
+
+ s = start[log2n][i];
+
+ readbuf = buf1; writebuf = buf2;
+
+ memcpy(readbuf, matrix+BMEMB*s, BMEMB*(sizeof *readbuf));
+
+ pointerswap(&readbuf, &writebuf);
+ next = mulmod_size_t(s, a, mod);
+
+ while (next != s) {
+
+ memcpy(readbuf, matrix+BMEMB*next, BMEMB*(sizeof *readbuf));
+ memcpy(matrix+BMEMB*next, writebuf, BMEMB*(sizeof *writebuf));
+
+ pointerswap(&readbuf, &writebuf);
+ next = mulmod_size_t(next, a, mod);
+
+ }
+
+ memcpy(matrix+BMEMB*next, writebuf, BMEMB*(sizeof *writebuf));
+ }
+}
+
+
+/*
+ * In place transposition of 3 x 2^n or 2^n x 3 matrix.
+ * Maximum size: 3 x 2^MAXN or 2^MAXN x 3
+ */
+void
+transpose_3xpow2(mpd_uint_t *matrix, size_t rows, size_t cols)
+{
+ mpd_uint_t buf[3*BMEMB];
+ mpd_uint_t *p;
+ size_t msize, bsize;
+
+ msize = mul_size_t(rows, cols);
+ bsize = 3*BMEMB;
+
+ if (msize <= bsize) {
+ std_trans(buf, matrix, rows, cols);
+ memcpy(matrix, buf, msize * (sizeof *matrix));
+ }
+ else if (rows == 3) {
+ assert(ispower2(cols));
+ assert(BSR(cols) <= MAXN);
+
+ _block_transpose_3xpow2(matrix, rows, cols);
+ for (p = matrix; p < matrix+msize; p += bsize) {
+ std_trans(buf, p, rows, BMEMB);
+ memcpy(p, buf, bsize * (sizeof *matrix));
+ }
+ }
+ else if (cols == 3) {
+ assert(ispower2(rows));
+ assert(BSR(rows) <= MAXN);
+
+ for (p = matrix; p < matrix+msize; p += bsize) {
+ std_trans(buf, p, BMEMB, cols);
+ memcpy(p, buf, bsize * (sizeof *matrix));
+ }
+ _block_transpose_3xpow2(matrix, rows, cols);
+ }
+ else {
+ mpd_err_fatal("transpose_3xpow2: wrong input for rows or cols");
+ }
+}
+
+
Added: python/branches/py3k-cdecimal/Modules/cdecimal/typearith.h
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/typearith.h Thu Jan 7 13:02:51 2010
@@ -0,0 +1,325 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#ifndef TYPEARITH_H
+#define TYPEARITH_H
+
+
+#include "mpdecimal.h"
+
+
+/*****************************************************************************/
+/* Native arithmetic on basic types */
+/*****************************************************************************/
+
+
+/** ------------------------------------------------------------
+ ** Double width multiplication and division
+ ** ------------------------------------------------------------
+ */
+
+#if defined (CONFIG_64)
+#if defined (__GNUC__)
+static inline void
+_mpd_mul_words(mpd_uint_t *hi, mpd_uint_t *lo, mpd_uint_t a, mpd_uint_t b)
+{
+ mpd_uint_t h, l;
+
+ asm( "mulq %3\n\t"\
+ : "=d" (h), "=a" (l)\
+ : "%a" (a), "rm" (b)\
+ : "cc"
+ );
+
+ *hi = h;
+ *lo = l;
+}
+
+static inline void
+_mpd_div_words(mpd_uint_t *q, mpd_uint_t *r, mpd_uint_t hi, mpd_uint_t lo, mpd_uint_t d)
+{
+ mpd_uint_t qq, rr;
+
+ asm ( "divq %4\n\t"\
+ : "=a" (qq), "=d" (rr)\
+ : "a" (lo), "d" (hi), "rm" (d)\
+ : "cc"
+ );
+
+ *q = qq;
+ *r = rr;
+}
+/* END CONFIG_64: __GNUC__ */
+
+#elif defined (_MSC_VER)
+#include <intrin.h>
+#pragma intrinsic(_umul128)
+
+static inline void
+_mpd_mul_words(mpd_uint_t *hi, mpd_uint_t *lo, mpd_uint_t a, mpd_uint_t b)
+{
+ *lo = _umul128(a, b, hi);
+}
+
+void _mpd_div_words(mpd_uint_t *q, mpd_uint_t *r, mpd_uint_t hi, mpd_uint_t lo, mpd_uint_t d);
+/* END CONFIG_64: _MSC_VER */
+
+#else
+ #error "need platform specific 128 bit multiplication and division"
+#endif
+
+static inline void
+_mpd_divmod_pow10(mpd_uint_t *q, mpd_uint_t *r, mpd_uint_t v, mpd_uint_t exp)
+{
+ assert(exp <= 19);
+
+ if (exp <= 9) {
+ if (exp <= 4) {
+ switch (exp) {
+ case 0: *q = v; *r = 0; break;
+ case 1: *q = v / 10ULL; *r = v - *q * 10ULL; break;
+ case 2: *q = v / 100ULL; *r = v - *q * 100ULL; break;
+ case 3: *q = v / 1000ULL; *r = v - *q * 1000ULL; break;
+ case 4: *q = v / 10000ULL; *r = v - *q * 10000ULL; break;
+ }
+ }
+ else {
+ switch (exp) {
+ case 5: *q = v / 100000ULL; *r = v - *q * 100000ULL; break;
+ case 6: *q = v / 1000000ULL; *r = v - *q * 1000000ULL; break;
+ case 7: *q = v / 10000000ULL; *r = v - *q * 10000000ULL; break;
+ case 8: *q = v / 100000000ULL; *r = v - *q * 100000000ULL; break;
+ case 9: *q = v / 1000000000ULL; *r = v - *q * 1000000000ULL; break;
+ }
+ }
+ }
+ else {
+ if (exp <= 14) {
+ switch (exp) {
+ case 10: *q = v / 10000000000ULL; *r = v - *q * 10000000000ULL; break;
+ case 11: *q = v / 100000000000ULL; *r = v - *q * 100000000000ULL; break;
+ case 12: *q = v / 1000000000000ULL; *r = v - *q * 1000000000000ULL; break;
+ case 13: *q = v / 10000000000000ULL; *r = v - *q * 10000000000000ULL; break;
+ case 14: *q = v / 100000000000000ULL; *r = v - *q * 100000000000000ULL; break;
+ }
+ }
+ else {
+ switch (exp) {
+ case 15: *q = v / 1000000000000000ULL; *r = v - *q * 1000000000000000ULL; break;
+ case 16: *q = v / 10000000000000000ULL; *r = v - *q * 10000000000000000ULL; break;
+ case 17: *q = v / 100000000000000000ULL; *r = v - *q * 100000000000000000ULL; break;
+ case 18: *q = v / 1000000000000000000ULL; *r = v - *q * 1000000000000000000ULL; break;
+ case 19: *q = v / 10000000000000000000ULL; *r = v - *q * 10000000000000000000ULL; break;
+ }
+ }
+ }
+}
+/* END CONFIG_64 */
+
+#elif defined (CONFIG_32)
+#if defined (ANSI)
+static inline void
+_mpd_mul_words(mpd_uint_t *hi, mpd_uint_t *lo, mpd_uint_t a, mpd_uint_t b)
+{
+ mpd_uuint_t hl;
+
+ hl = (mpd_uuint_t)a * b;
+
+ *hi = hl >> 32;
+ *lo = hl;
+}
+
+static inline void
+_mpd_div_words(mpd_uint_t *q, mpd_uint_t *r, mpd_uint_t hi, mpd_uint_t lo, mpd_uint_t d)
+{
+ mpd_uuint_t hl;
+
+ hl = ((mpd_uuint_t)hi<<32) + lo;
+ *q = hl / d; /* quotient is known to fit */
+ *r = hl - (mpd_uuint_t)(*q) * d;
+}
+/* END CONFIG_32: ANSI */
+
+#elif defined(__GNUC__)
+static inline void
+_mpd_mul_words(mpd_uint_t *hi, mpd_uint_t *lo, mpd_uint_t a, mpd_uint_t b)
+{
+ mpd_uint_t h, l;
+
+ asm( "mull %3\n\t"\
+ : "=d" (h), "=a" (l)\
+ : "%a" (a), "rm" (b)\
+ : "cc"
+ );
+
+ *hi = h;
+ *lo = l;
+}
+
+static inline void
+_mpd_div_words(mpd_uint_t *q, mpd_uint_t *r, mpd_uint_t hi, mpd_uint_t lo, mpd_uint_t d)
+{
+ mpd_uint_t qq, rr;
+
+ asm ( "divl %4\n\t"\
+ : "=a" (qq), "=d" (rr)\
+ : "a" (lo), "d" (hi), "rm" (d)\
+ : "cc"
+ );
+
+ *q = qq;
+ *r = rr;
+}
+/* END CONFIG_32: __GNUC__ */
+
+#elif defined (_MSC_VER)
+static inline void __cdecl
+_mpd_mul_words(mpd_uint_t *hi, mpd_uint_t *lo, mpd_uint_t a, mpd_uint_t b)
+{
+ mpd_uint_t h, l;
+
+ __asm {
+ mov eax, a
+ mul b
+ mov h, edx
+ mov l, eax
+ }
+
+ *hi = h;
+ *lo = l;
+}
+
+static inline void __cdecl
+_mpd_div_words(mpd_uint_t *q, mpd_uint_t *r, mpd_uint_t hi, mpd_uint_t lo, mpd_uint_t d)
+{
+ mpd_uint_t qq, rr;
+
+ __asm {
+ mov eax, lo
+ mov edx, hi
+ div d
+ mov qq, eax
+ mov rr, edx
+ }
+
+ *q = qq;
+ *r = rr;
+}
+/* END CONFIG_32: _MSC_VER */
+
+#else
+ #error "need platform specific 64 bit multiplication and division"
+#endif
+
+static inline void
+_mpd_divmod_pow10(mpd_uint_t *q, mpd_uint_t *r, mpd_uint_t v, mpd_uint_t exp)
+{
+ assert(exp <= 9);
+
+ if (exp <= 4) {
+ switch (exp) {
+ case 0: *q = v; *r = 0; break;
+ case 1: *q = v / 10ULL; *r = v - *q * 10ULL; break;
+ case 2: *q = v / 100ULL; *r = v - *q * 100ULL; break;
+ case 3: *q = v / 1000ULL; *r = v - *q * 1000ULL; break;
+ case 4: *q = v / 10000ULL; *r = v - *q * 10000ULL; break;
+ }
+ }
+ else {
+ switch (exp) {
+ case 5: *q = v / 100000ULL; *r = v - *q * 100000ULL; break;
+ case 6: *q = v / 1000000ULL; *r = v - *q * 1000000ULL; break;
+ case 7: *q = v / 10000000ULL; *r = v - *q * 10000000ULL; break;
+ case 8: *q = v / 100000000ULL; *r = v - *q * 100000000ULL; break;
+ case 9: *q = v / 1000000000ULL; *r = v - *q * 1000000000ULL; break;
+ }
+ }
+}
+/* END CONFIG_32 */
+
+/* NO CONFIG */
+#else
+ #error "define CONFIG_64 or CONFIG_32"
+#endif /* CONFIG */
+
+
+static inline void
+_mpd_div_word(mpd_uint_t *q, mpd_uint_t *r, mpd_uint_t v, mpd_uint_t d)
+{
+ *q = v / d;
+ *r = v - *q * d;
+}
+
+static inline void
+_mpd_idiv_word(mpd_ssize_t *q, mpd_ssize_t *r, mpd_ssize_t v, mpd_ssize_t d)
+{
+ *q = v / d;
+ *r = v - *q * d;
+}
+
+
+/** ------------------------------------------------------------
+ ** Arithmetic with overflow checking
+ ** ------------------------------------------------------------
+ */
+static inline size_t
+add_size_t(size_t a, size_t b)
+{
+ if (a > SIZE_MAX - b) {
+ mpd_err_fatal("add_size_t(): overflow: check the context");
+ }
+ return a + b;
+}
+
+static inline size_t
+sub_size_t(size_t a, size_t b)
+{
+ if (b > a) {
+ mpd_err_fatal("sub_size_t(): overflow: check the context");
+ }
+ return a - b;
+}
+
+#if SIZE_MAX != MPD_UINT_MAX
+ #error "adapt mul_size_t(), mod_mpd_ssize_t() and mulmod_size_t()"
+#endif
+
+static inline size_t
+mul_size_t(size_t a, size_t b)
+{
+ mpd_uint_t hi, lo;
+
+ _mpd_mul_words(&hi, &lo, (mpd_uint_t)a, (mpd_uint_t)b);
+ if (hi) {
+ mpd_err_fatal("mul_size_t(): overflow: check the context");
+ }
+ return lo;
+}
+
+static inline mpd_ssize_t
+mod_mpd_ssize_t(mpd_ssize_t a, mpd_ssize_t m)
+{
+ mpd_ssize_t r = a % m;
+ return (r < 0) ? r + m : r;
+}
+
+static inline size_t
+mulmod_size_t(size_t a, size_t b, size_t m)
+{
+ mpd_uint_t hi, lo;
+ mpd_uint_t q, r;
+
+ _mpd_mul_words(&hi, &lo, (mpd_uint_t)a, (mpd_uint_t)b);
+ _mpd_div_words(&q, &r, hi, lo, (mpd_uint_t)m);
+
+ return r;
+}
+
+
+#endif /* TYPEARITH_H */
+
+
+
Added: python/branches/py3k-cdecimal/Modules/cdecimal/umodarith.h
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/umodarith.h Thu Jan 7 13:02:51 2010
@@ -0,0 +1,538 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#ifndef UMODARITH_H
+#define UMODARITH_H
+
+
+#include "constants.h"
+#include "mpdecimal.h"
+#include "typearith.h"
+
+
+/**************************************************************************/
+/* ANSI C99 modular arithmetic */
+/**************************************************************************/
+
+
+/*
+ * Restrictions: a < m and b < m
+ * ACL2 proof: umodarith.lisp: addmod-correct
+ */
+static inline mpd_uint_t
+addmod(mpd_uint_t a, mpd_uint_t b, mpd_uint_t m)
+{
+ mpd_uint_t s;
+
+ s = a + b;
+ s = (s < a) ? s - m : s;
+ s = (s >= m) ? s - m : s;
+
+ return s;
+}
+
+/*
+ * Restrictions: a < m and b < m
+ * ACL2 proof: umodarith.lisp: submod-2-correct
+ */
+static inline mpd_uint_t
+submod(mpd_uint_t a, mpd_uint_t b, mpd_uint_t m)
+{
+ mpd_uint_t d;
+
+ d = a - b;
+ d = (a < b) ? d + m : d;
+
+ return d;
+}
+
+/*
+ * Restrictions: a < 2m and b < 2m
+ * ACL2 proof: umodarith.lisp: ext-submod-2-correct
+ */
+static inline mpd_uint_t
+ext_submod(mpd_uint_t a, mpd_uint_t b, mpd_uint_t m)
+{
+ mpd_uint_t d;
+
+ a = (a >= m) ? a - m : a;
+ b = (b >= m) ? b - m : b;
+
+ d = a - b;
+ d = (a < b) ? d + m : d;
+
+ return d;
+}
+
+/* divide 2 words by v, return remainder */
+static inline mpd_uint_t
+bigmod2(mpd_uint_t hi, mpd_uint_t lo, mpd_uint_t v)
+{
+ mpd_uint_t r1, r2, w;
+
+ _mpd_div_word(&w, &r1, hi, v);
+ _mpd_div_words(&w, &r2, r1, lo, v);
+
+ return r2;
+}
+
+/* subtract double word hi,lo from a */
+static inline mpd_uint_t
+dw_submod(mpd_uint_t a, mpd_uint_t hi, mpd_uint_t lo, mpd_uint_t m)
+{
+ mpd_uint_t d, r;
+
+ r = bigmod2(hi, lo, m);
+ d = a - r;
+ d = (a < r) ? d + m : d;
+
+ return d;
+}
+
+
+#ifdef ANSI /* compiler has type mpd_uuint_t */
+static inline
+mpd_uint_t std_mulmod(mpd_uint_t a, mpd_uint_t b, mpd_uint_t m)
+{
+ return ((mpd_uuint_t) a * b) % m;
+}
+
+static inline void
+std_mulmod2c(mpd_uint_t *a, mpd_uint_t *b, mpd_uint_t w, mpd_uint_t m)
+{
+ *a = ((mpd_uuint_t) *a * w) % m;
+ *b = ((mpd_uuint_t) *b * w) % m;
+}
+
+static inline void
+std_mulmod2(mpd_uint_t *a0, mpd_uint_t b0, mpd_uint_t *a1, mpd_uint_t b1, mpd_uint_t m)
+{
+ *a0 = ((mpd_uuint_t) *a0 * b0) % m;
+ *a1 = ((mpd_uuint_t) *a1 * b1) % m;
+}
+
+static inline
+mpd_uint_t std_powmod(mpd_uint_t base, mpd_uint_t exp, mpd_uint_t umod)
+{
+ mpd_uint_t r = 1;
+
+ while (exp > 0) {
+ if (exp & 1)
+ r = std_mulmod(r, base, umod);
+ base = std_mulmod(base, base, umod);
+ exp >>= 1;
+ }
+
+ return r;
+}
+#endif
+
+
+/**************************************************************************/
+/* x64 modular arithmetic */
+/**************************************************************************/
+
+/*
+ * Description of the algorithm in apfloat.pdf, Chapter 7.1.1, by Mikko Tommila.
+ * http://www.apfloat.org/apfloat/2.41/
+ *
+ * ACL2 proof: umodarith.lisp: section "Fast modular reduction"
+ */
+
+#ifdef CONFIG_64
+static inline mpd_uint_t
+x64_mulmod(mpd_uint_t a, mpd_uint_t b, mpd_uint_t m)
+{
+ mpd_uint_t hi, lo, x, y;
+
+
+ _mpd_mul_words(&hi, &lo, a, b);
+
+ if (m & (1ULL<<32)) { /* P1 */
+
+ /* first reduction */
+ x = y = hi;
+ hi >>= 32;
+
+ x = lo - x;
+ if (x > lo) hi--;
+
+ y <<= 32;
+ lo = y + x;
+ if (lo < y) hi++;
+
+ /* second reduction */
+ x = y = hi;
+ hi >>= 32;
+
+ x = lo - x;
+ if (x > lo) hi--;
+
+ y <<= 32;
+ lo = y + x;
+ if (lo < y) hi++;
+
+ return (hi || lo >= m ? lo - m : lo);
+ }
+ else if (m & (1ULL<<34)) { /* P2 */
+
+ /* first reduction */
+ x = y = hi;
+ hi >>= 30;
+
+ x = lo - x;
+ if (x > lo) hi--;
+
+ y <<= 34;
+ lo = y + x;
+ if (lo < y) hi++;
+
+ /* second reduction */
+ x = y = hi;
+ hi >>= 30;
+
+ x = lo - x;
+ if (x > lo) hi--;
+
+ y <<= 34;
+ lo = y + x;
+ if (lo < y) hi++;
+
+ /* third reduction */
+ x = y = hi;
+ hi >>= 30;
+
+ x = lo - x;
+ if (x > lo) hi--;
+
+ y <<= 34;
+ lo = y + x;
+ if (lo < y) hi++;
+
+ return (hi || lo >= m ? lo - m : lo);
+ }
+ else { /* P3 */
+
+ /* first reduction */
+ x = y = hi;
+ hi >>= 24;
+
+ x = lo - x;
+ if (x > lo) hi--;
+
+ y <<= 40;
+ lo = y + x;
+ if (lo < y) hi++;
+
+ /* second reduction */
+ x = y = hi;
+ hi >>= 24;
+
+ x = lo - x;
+ if (x > lo) hi--;
+
+ y <<= 40;
+ lo = y + x;
+ if (lo < y) hi++;
+
+ /* third reduction */
+ x = y = hi;
+ hi >>= 24;
+
+ x = lo - x;
+ if (x > lo) hi--;
+
+ y <<= 40;
+ lo = y + x;
+ if (lo < y) hi++;
+
+ return (hi || lo >= m ? lo - m : lo);
+ }
+}
+
+static inline void
+x64_mulmod2c(mpd_uint_t *a, mpd_uint_t *b, mpd_uint_t w, mpd_uint_t m)
+{
+ *a = x64_mulmod(*a, w, m);
+ *b = x64_mulmod(*b, w, m);
+}
+
+static inline void
+x64_mulmod2(mpd_uint_t *a0, mpd_uint_t b0, mpd_uint_t *a1, mpd_uint_t b1, mpd_uint_t m)
+{
+ *a0 = x64_mulmod(*a0, b0, m);
+ *a1 = x64_mulmod(*a1, b1, m);
+}
+
+static inline
+mpd_uint_t x64_powmod(mpd_uint_t base, mpd_uint_t exp, mpd_uint_t umod)
+{
+ mpd_uint_t r = 1;
+
+ while (exp > 0) {
+ if (exp & 1)
+ r = x64_mulmod(r, base, umod);
+ base = x64_mulmod(base, base, umod);
+ exp >>= 1;
+ }
+
+ return r;
+}
+#endif
+
+
+/**************************************************************************/
+/* Pentium Pro modular arithmetic */
+/**************************************************************************/
+
+/*
+ * Description of the algorithm in apfloat.pdf, Chapter 7.1.1, by Mikko Tommila.
+ * http://www.apfloat.org/apfloat/2.41/
+ *
+ * Remarks:
+ *
+ * - dinvmod points to an array of three uint32_t, which is interpreted
+ * as an 80 bit long double.
+ * - Intel compilers prior to version 11 do not seem to handle the
+ * __GNUC__ inline assembly correctly.
+ * - random tests are provided in tests/extended/ppro_mulmod.c
+ */
+
+#ifdef PPRO
+#ifdef __GNUC__
+
+/* all operands < dmod */
+static inline mpd_uint_t
+ppro_mulmod(mpd_uint_t a, mpd_uint_t b, double *dmod, uint32_t *dinvmod)
+{
+ mpd_uint_t retval;
+
+ asm(
+ "fildl %2\n\t"\
+ "fildl %1\n\t"\
+ "fmulp %%st, %%st(1)\n\t"\
+ "fldt (%4)\n\t"\
+ "fmul %%st(1), %%st\n\t"\
+ "flds MPD_TWO63\n\t"\
+ "fadd %%st, %%st(1)\n\t"\
+ "fsubrp %%st, %%st(1)\n\t"\
+ "fldl (%3)\n\t"\
+ "fmulp %%st, %%st(1)\n\t"\
+ "fsubrp %%st, %%st(1)\n\t"\
+ "fistpl %0\n\t"\
+ : "=m" (retval)\
+ : "m" (a), "m" (b), "r" (dmod), "r" (dinvmod)\
+ : "st", "memory"
+ );
+
+ return retval;
+
+}
+
+/* all operands < dmod */
+static inline void
+ppro_mulmod2c(mpd_uint_t *a0, mpd_uint_t *a1, mpd_uint_t w, double *dmod, uint32_t *dinvmod)
+{
+
+ asm(
+ "fildl %2\n\t"\
+ "fildl (%1)\n\t"\
+ "fmul %%st(1), %%st\n\t"\
+ "fxch %%st(1)\n\t"\
+ "fildl (%0)\n\t"\
+ "fmulp %%st, %%st(1) \n\t"\
+ "fldt (%4)\n\t"\
+ "flds MPD_TWO63\n\t"\
+ "fld %%st(2)\n\t"\
+ "fmul %%st(2)\n\t"\
+ "fadd %%st(1)\n\t"\
+ "fsub %%st(1)\n\t"\
+ "fmull (%3)\n\t"\
+ "fsubrp %%st, %%st(3)\n\t"\
+ "fxch %%st(2)\n\t"\
+ "fistpl (%0)\n\t"\
+ "fmul %%st(2)\n\t"\
+ "fadd %%st(1)\n\t"\
+ "fsubp %%st, %%st(1)\n\t"\
+ "fmull (%3)\n\t"\
+ "fsubrp %%st, %%st(1)\n\t"\
+ "fistpl (%1)\n\t"\
+ : : "r" (a0), "r" (a1), "m" (w), "r" (dmod), "r" (dinvmod)\
+ : "st", "memory"
+ );
+
+}
+
+/* all operands < dmod */
+static inline void
+ppro_mulmod2(mpd_uint_t *a0, mpd_uint_t b0, mpd_uint_t *a1, mpd_uint_t b1, double *dmod, uint32_t *dinvmod)
+{
+
+ asm(
+ "fildl %3\n\t"\
+ "fildl (%2)\n\t"\
+ "fmulp %%st, %%st(1)\n\t"\
+ "fildl %1\n\t"\
+ "fildl (%0)\n\t"\
+ "fmulp %%st, %%st(1)\n\t"\
+ "fldt (%5)\n\t"\
+ "fld %%st(2)\n\t"\
+ "fmul %%st(1), %%st\n\t"\
+ "fxch %%st(1)\n\t"\
+ "fmul %%st(2), %%st\n\t"\
+ "flds MPD_TWO63\n\t"\
+ "fldl (%4)\n\t"\
+ "fxch %%st(3)\n\t"\
+ "fadd %%st(1), %%st\n\t"\
+ "fxch %%st(2)\n\t"\
+ "fadd %%st(1), %%st\n\t"\
+ "fxch %%st(2)\n\t"\
+ "fsub %%st(1), %%st\n\t"\
+ "fxch %%st(2)\n\t"\
+ "fsubp %%st, %%st(1)\n\t"\
+ "fxch %%st(1)\n\t"\
+ "fmul %%st(2), %%st\n\t"\
+ "fxch %%st(1)\n\t"\
+ "fmulp %%st, %%st(2)\n\t"\
+ "fsubrp %%st, %%st(3)\n\t"\
+ "fsubrp %%st, %%st(1)\n\t"\
+ "fxch %%st(1)\n\t"\
+ "fistpl (%2)\n\t"\
+ "fistpl (%0)\n\t"\
+ : : "r" (a0), "m" (b0), "r" (a1), "m" (b1), "r" (dmod), "r" (dinvmod)\
+ : "st", "memory"
+ );
+
+}
+/* END PPRO __GNUC__ */
+#elif defined (_MSC_VER)
+
+/* all operands < dmod */
+static inline mpd_uint_t __cdecl
+ppro_mulmod(mpd_uint_t a, mpd_uint_t b, double *dmod, uint32_t *dinvmod)
+{
+ mpd_uint_t retval;
+
+ __asm {
+ mov eax, dinvmod
+ mov edx, dmod
+ fild b
+ fild a
+ fmulp st(1), st
+ fld TBYTE PTR [eax]
+ fmul st, st(1)
+ fld MPD_TWO63
+ fadd st(1), st
+ fsubp st(1), st
+ fld QWORD PTR [edx]
+ fmulp st(1), st
+ fsubp st(1), st
+ fistp retval
+ }
+
+ return retval;
+}
+
+/* all operands < dmod */
+static inline mpd_uint_t __cdecl
+ppro_mulmod2c(mpd_uint_t *a0, mpd_uint_t *a1, mpd_uint_t w, double *dmod, uint32_t *dinvmod)
+{
+ __asm {
+ mov ecx, dmod
+ mov edx, a1
+ mov ebx, dinvmod
+ mov eax, a0
+ fild w
+ fild DWORD PTR [edx]
+ fmul st, st(1)
+ fxch st(1)
+ fild DWORD PTR [eax]
+ fmulp st(1), st
+ fld TBYTE PTR [ebx]
+ fld MPD_TWO63
+ fld st(2)
+ fmul st, st(2)
+ fadd st, st(1)
+ fsub st, st(1)
+ fmul QWORD PTR [ecx]
+ fsubp st(3), st
+ fxch st(2)
+ fistp DWORD PTR [eax]
+ fmul st, st(2)
+ fadd st, st(1)
+ fsubrp st(1), st
+ fmul QWORD PTR [ecx]
+ fsubp st(1), st
+ fistp DWORD PTR [edx]
+ }
+}
+
+/* all operands < dmod */
+static inline void __cdecl
+ppro_mulmod2(mpd_uint_t *a0, mpd_uint_t b0, mpd_uint_t *a1, mpd_uint_t b1, double *dmod, uint32_t *dinvmod)
+{
+ __asm {
+ mov ecx, dmod
+ mov edx, a1
+ mov ebx, dinvmod
+ mov eax, a0
+ fild b1
+ fild DWORD PTR [edx]
+ fmulp st(1), st
+ fild b0
+ fild DWORD PTR [eax]
+ fmulp st(1), st
+ fld TBYTE PTR [ebx]
+ fld st(2)
+ fmul st, st(1)
+ fxch st(1)
+ fmul st, st(2)
+ fld DWORD PTR MPD_TWO63
+ fld QWORD PTR [ecx]
+ fxch st(3)
+ fadd st, st(1)
+ fxch st(2)
+ fadd st, st(1)
+ fxch st(2)
+ fsub st, st(1)
+ fxch st(2)
+ fsubrp st(1), st
+ fxch st(1)
+ fmul st, st(2)
+ fxch st(1)
+ fmulp st(2), st
+ fsubp st(3), st
+ fsubp st(1), st
+ fxch st(1)
+ fistp DWORD PTR [edx]
+ fistp DWORD PTR [eax]
+ }
+}
+#endif /* PPRO _MSC_VER */
+
+
+/* all operands < dmod */
+static inline mpd_uint_t
+ppro_powmod(mpd_uint_t base, mpd_uint_t exp, double *dmod, uint32_t *dinvmod)
+{
+ mpd_uint_t r = 1;
+
+ while (exp > 0) {
+ if (exp & 1)
+ r = ppro_mulmod(r, base, dmod, dinvmod);
+ base = ppro_mulmod(base, base, dmod, dinvmod);
+ exp >>= 1;
+ }
+
+ return r;
+}
+#endif /* PPRO */
+
+
+#endif /* UMODARITH_H */
+
+
+
Added: python/branches/py3k-cdecimal/Modules/cdecimal/vccompat.h
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/vccompat.h Thu Jan 7 13:02:51 2010
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+ * Licensed to PSF under a Contributor Agreement.
+ */
+
+
+#ifndef VCCOMPAT_H
+#define VCCOMPAT_H
+
+
+/* Visual C fixes: no stdint.h, no snprintf ...*/
+#ifdef _MSC_VER
+ #include "vcstdint.h"
+ #undef inline
+ #define inline __inline
+ #undef random
+ #define random rand
+ #undef srandom
+ #define srandom srand
+ #undef snprintf
+ #define snprintf sprintf_s
+ #undef strncasecmp
+ #define strncasecmp _strnicmp
+ #undef strcasecmp
+ #define strcasecmp _stricmp
+ #undef strtoll
+ #define strtoll _strtoi64
+#endif
+
+
+#endif /* VCCOMPAT_H */
+
+
+
Added: python/branches/py3k-cdecimal/Modules/cdecimal/vcdiv64.asm
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/vcdiv64.asm Thu Jan 7 13:02:51 2010
@@ -0,0 +1,28 @@
+;
+; Copyright (c) 2008-2010 Stefan Krah. All Rights Reserved.
+; Licensed to PSF under a Contributor Agreement.
+;
+
+
+PUBLIC _mpd_div_words
+_TEXT SEGMENT
+q$ = 8
+r$ = 16
+hi$ = 24
+lo$ = 32
+d$ = 40
+_mpd_div_words PROC
+ mov r10, rdx
+ mov rdx, r8
+ mov rax, r9
+ div QWORD PTR d$[rsp]
+ mov QWORD PTR [r10], rdx
+ mov QWORD PTR [rcx], rax
+ ret 0
+_mpd_div_words ENDP
+_TEXT ENDS
+
+
+end
+
+
Added: python/branches/py3k-cdecimal/Modules/cdecimal/vcstdint.h
==============================================================================
--- (empty file)
+++ python/branches/py3k-cdecimal/Modules/cdecimal/vcstdint.h Thu Jan 7 13:02:51 2010
@@ -0,0 +1,232 @@
+// ISO C9x compliant stdint.h for Microsoft Visual Studio
+// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124
+//
+// Copyright (c) 2006-2008 Alexander Chemeris
+//
+// 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.
+//
+// 3. The name of the author may be used to endorse or promote products
+// derived from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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 _MSC_VER // [
+#error "Use this header only with Microsoft Visual C++ compilers!"
+#endif // _MSC_VER ]
+
+#ifndef _MSC_STDINT_H_ // [
+#define _MSC_STDINT_H_
+
+#if _MSC_VER > 1000
+#pragma once
+#endif
+
+#include <limits.h>
+
+// For Visual Studio 6 in C++ mode wrap <wchar.h> include with 'extern "C++" {}'
+// or compiler give many errors like this:
+// error C2733: second C linkage of overloaded function 'wmemchr' not allowed
+#if (_MSC_VER < 1300) && defined(__cplusplus)
+ extern "C++" {
+#endif
+# include <wchar.h>
+#if (_MSC_VER < 1300) && defined(__cplusplus)
+ }
+#endif
+
+// Define _W64 macros to mark types changing their size, like intptr_t.
+#ifndef _W64
+# if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300
+# define _W64 __w64
+# else
+# define _W64
+# endif
+#endif
+
+
+// 7.18.1 Integer types
+
+// 7.18.1.1 Exact-width integer types
+typedef __int8 int8_t;
+typedef __int16 int16_t;
+typedef __int32 int32_t;
+typedef __int64 int64_t;
+typedef unsigned __int8 uint8_t;
+typedef unsigned __int16 uint16_t;
+typedef unsigned __int32 uint32_t;
+typedef unsigned __int64 uint64_t;
+
+// 7.18.1.2 Minimum-width integer types
+typedef int8_t int_least8_t;
+typedef int16_t int_least16_t;
+typedef int32_t int_least32_t;
+typedef int64_t int_least64_t;
+typedef uint8_t uint_least8_t;
+typedef uint16_t uint_least16_t;
+typedef uint32_t uint_least32_t;
+typedef uint64_t uint_least64_t;
+
+// 7.18.1.3 Fastest minimum-width integer types
+typedef int8_t int_fast8_t;
+typedef int16_t int_fast16_t;
+typedef int32_t int_fast32_t;
+typedef int64_t int_fast64_t;
+typedef uint8_t uint_fast8_t;
+typedef uint16_t uint_fast16_t;
+typedef uint32_t uint_fast32_t;
+typedef uint64_t uint_fast64_t;
+
+// 7.18.1.4 Integer types capable of holding object pointers
+#ifdef _WIN64 // [
+ typedef __int64 intptr_t;
+ typedef unsigned __int64 uintptr_t;
+#else // _WIN64 ][
+ typedef _W64 int intptr_t;
+ typedef _W64 unsigned int uintptr_t;
+#endif // _WIN64 ]
+
+// 7.18.1.5 Greatest-width integer types
+typedef int64_t intmax_t;
+typedef uint64_t uintmax_t;
+
+
+// 7.18.2 Limits of specified-width integer types
+
+#if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259
+
+// 7.18.2.1 Limits of exact-width integer types
+#define INT8_MIN ((int8_t)_I8_MIN)
+#define INT8_MAX _I8_MAX
+#define INT16_MIN ((int16_t)_I16_MIN)
+#define INT16_MAX _I16_MAX
+#define INT32_MIN ((int32_t)_I32_MIN)
+#define INT32_MAX _I32_MAX
+#define INT64_MIN ((int64_t)_I64_MIN)
+#define INT64_MAX _I64_MAX
+#define UINT8_MAX _UI8_MAX
+#define UINT16_MAX _UI16_MAX
+#define UINT32_MAX _UI32_MAX
+#define UINT64_MAX _UI64_MAX
+
+// 7.18.2.2 Limits of minimum-width integer types
+#define INT_LEAST8_MIN INT8_MIN
+#define INT_LEAST8_MAX INT8_MAX
+#define INT_LEAST16_MIN INT16_MIN
+#define INT_LEAST16_MAX INT16_MAX
+#define INT_LEAST32_MIN INT32_MIN
+#define INT_LEAST32_MAX INT32_MAX
+#define INT_LEAST64_MIN INT64_MIN
+#define INT_LEAST64_MAX INT64_MAX
+#define UINT_LEAST8_MAX UINT8_MAX
+#define UINT_LEAST16_MAX UINT16_MAX
+#define UINT_LEAST32_MAX UINT32_MAX
+#define UINT_LEAST64_MAX UINT64_MAX
+
+// 7.18.2.3 Limits of fastest minimum-width integer types
+#define INT_FAST8_MIN INT8_MIN
+#define INT_FAST8_MAX INT8_MAX
+#define INT_FAST16_MIN INT16_MIN
+#define INT_FAST16_MAX INT16_MAX
+#define INT_FAST32_MIN INT32_MIN
+#define INT_FAST32_MAX INT32_MAX
+#define INT_FAST64_MIN INT64_MIN
+#define INT_FAST64_MAX INT64_MAX
+#define UINT_FAST8_MAX UINT8_MAX
+#define UINT_FAST16_MAX UINT16_MAX
+#define UINT_FAST32_MAX UINT32_MAX
+#define UINT_FAST64_MAX UINT64_MAX
+
+// 7.18.2.4 Limits of integer types capable of holding object pointers
+#ifdef _WIN64 // [
+# define INTPTR_MIN INT64_MIN
+# define INTPTR_MAX INT64_MAX
+# define UINTPTR_MAX UINT64_MAX
+#else // _WIN64 ][
+# define INTPTR_MIN INT32_MIN
+# define INTPTR_MAX INT32_MAX
+# define UINTPTR_MAX UINT32_MAX
+#endif // _WIN64 ]
+
+// 7.18.2.5 Limits of greatest-width integer types
+#define INTMAX_MIN INT64_MIN
+#define INTMAX_MAX INT64_MAX
+#define UINTMAX_MAX UINT64_MAX
+
+// 7.18.3 Limits of other integer types
+
+#ifdef _WIN64 // [
+# define PTRDIFF_MIN _I64_MIN
+# define PTRDIFF_MAX _I64_MAX
+#else // _WIN64 ][
+# define PTRDIFF_MIN _I32_MIN
+# define PTRDIFF_MAX _I32_MAX
+#endif // _WIN64 ]
+
+#define SIG_ATOMIC_MIN INT_MIN
+#define SIG_ATOMIC_MAX INT_MAX
+
+#ifndef SIZE_MAX // [
+# ifdef _WIN64 // [
+# define SIZE_MAX _UI64_MAX
+# else // _WIN64 ][
+# define SIZE_MAX _UI32_MAX
+# endif // _WIN64 ]
+#endif // SIZE_MAX ]
+
+// WCHAR_MIN and WCHAR_MAX are also defined in <wchar.h>
+#ifndef WCHAR_MIN // [
+# define WCHAR_MIN 0
+#endif // WCHAR_MIN ]
+#ifndef WCHAR_MAX // [
+# define WCHAR_MAX _UI16_MAX
+#endif // WCHAR_MAX ]
+
+#define WINT_MIN 0
+#define WINT_MAX _UI16_MAX
+
+#endif // __STDC_LIMIT_MACROS ]
+
+
+// 7.18.4 Limits of other integer types
+
+#if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260
+
+// 7.18.4.1 Macros for minimum-width integer constants
+
+#define INT8_C(val) val##i8
+#define INT16_C(val) val##i16
+#define INT32_C(val) val##i32
+#define INT64_C(val) val##i64
+
+#define UINT8_C(val) val##ui8
+#define UINT16_C(val) val##ui16
+#define UINT32_C(val) val##ui32
+#define UINT64_C(val) val##ui64
+
+// 7.18.4.2 Macros for greatest-width integer constants
+#define INTMAX_C INT64_C
+#define UINTMAX_C UINT64_C
+
+#endif // __STDC_CONSTANT_MACROS ]
+
+
+#endif // _MSC_STDINT_H_ ]
More information about the Python-checkins
mailing list