Import gcc-4.4.1
[dragonfly.git] / contrib / gcc-4.4 / libdecnumber / dpd / decimal64.c
1 /* Decimal 64-bit format module for the decNumber C Library.
2    Copyright (C) 2005, 2007, 2009 Free Software Foundation, Inc.
3    Contributed by IBM Corporation.  Author Mike Cowlishaw.
4
5    This file is part of GCC.
6
7    GCC is free software; you can redistribute it and/or modify it under
8    the terms of the GNU General Public License as published by the Free
9    Software Foundation; either version 3, or (at your option) any later
10    version.
11
12    GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13    WARRANTY; without even the implied warranty of MERCHANTABILITY or
14    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15    for more details.
16
17 Under Section 7 of GPL version 3, you are granted additional
18 permissions described in the GCC Runtime Library Exception, version
19 3.1, as published by the Free Software Foundation.
20
21 You should have received a copy of the GNU General Public License and
22 a copy of the GCC Runtime Library Exception along with this program;
23 see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
24 <http://www.gnu.org/licenses/>.  */
25
26 /* ------------------------------------------------------------------ */
27 /* Decimal 64-bit format module                                       */
28 /* ------------------------------------------------------------------ */
29 /* This module comprises the routines for decimal64 format numbers.   */
30 /* Conversions are supplied to and from decNumber and String.         */
31 /*                                                                    */
32 /* This is used when decNumber provides operations, either for all    */
33 /* operations or as a proxy between decNumber and decSingle.          */
34 /*                                                                    */
35 /* Error handling is the same as decNumber (qv.).                     */
36 /* ------------------------------------------------------------------ */
37 #include <string.h>           /* [for memset/memcpy] */
38 #include <stdio.h>            /* [for printf] */
39
40 #include "dconfig.h"          /* GCC definitions */
41 #define  DECNUMDIGITS 16      /* make decNumbers with space for 16 */
42 #include "decNumber.h"        /* base number library */
43 #include "decNumberLocal.h"   /* decNumber local types, etc. */
44 #include "decimal64.h"        /* our primary include */
45
46 /* Utility routines and tables [in decimal64.c]; externs for C++ */
47 extern const uInt COMBEXP[32], COMBMSD[32];
48 extern const uShort DPD2BIN[1024];
49 extern const uShort BIN2DPD[1000];
50 extern const uByte  BIN2CHAR[4001];
51
52 extern void decDigitsFromDPD(decNumber *, const uInt *, Int);
53 extern void decDigitsToDPD(const decNumber *, uInt *, Int);
54
55 #if DECTRACE || DECCHECK
56 void decimal64Show(const decimal64 *);            /* for debug */
57 extern void decNumberShow(const decNumber *);     /* .. */
58 #endif
59
60 /* Useful macro */
61 /* Clear a structure (e.g., a decNumber) */
62 #define DEC_clear(d) memset(d, 0, sizeof(*d))
63
64 /* define and include the tables to use for conversions */
65 #define DEC_BIN2CHAR 1
66 #define DEC_DPD2BIN  1
67 #define DEC_BIN2DPD  1             /* used for all sizes */
68 #include "decDPD.h"                /* lookup tables */
69
70 /* ------------------------------------------------------------------ */
71 /* decimal64FromNumber -- convert decNumber to decimal64              */
72 /*                                                                    */
73 /*   ds is the target decimal64                                       */
74 /*   dn is the source number (assumed valid)                          */
75 /*   set is the context, used only for reporting errors               */
76 /*                                                                    */
77 /* The set argument is used only for status reporting and for the     */
78 /* rounding mode (used if the coefficient is more than DECIMAL64_Pmax */
79 /* digits or an overflow is detected).  If the exponent is out of the */
80 /* valid range then Overflow or Underflow will be raised.             */
81 /* After Underflow a subnormal result is possible.                    */
82 /*                                                                    */
83 /* DEC_Clamped is set if the number has to be 'folded down' to fit,   */
84 /* by reducing its exponent and multiplying the coefficient by a      */
85 /* power of ten, or if the exponent on a zero had to be clamped.      */
86 /* ------------------------------------------------------------------ */
87 decimal64 * decimal64FromNumber(decimal64 *d64, const decNumber *dn,
88                                 decContext *set) {
89   uInt status=0;                   /* status accumulator */
90   Int ae;                          /* adjusted exponent */
91   decNumber  dw;                   /* work */
92   decContext dc;                   /* .. */
93   uInt *pu;                        /* .. */
94   uInt comb, exp;                  /* .. */
95   uInt targar[2]={0, 0};           /* target 64-bit */
96   #define targhi targar[1]         /* name the word with the sign */
97   #define targlo targar[0]         /* and the other */
98
99   /* If the number has too many digits, or the exponent could be */
100   /* out of range then reduce the number under the appropriate */
101   /* constraints.  This could push the number to Infinity or zero, */
102   /* so this check and rounding must be done before generating the */
103   /* decimal64] */
104   ae=dn->exponent+dn->digits-1;              /* [0 if special] */
105   if (dn->digits>DECIMAL64_Pmax              /* too many digits */
106    || ae>DECIMAL64_Emax                      /* likely overflow */
107    || ae<DECIMAL64_Emin) {                   /* likely underflow */
108     decContextDefault(&dc, DEC_INIT_DECIMAL64); /* [no traps] */
109     dc.round=set->round;                     /* use supplied rounding */
110     decNumberPlus(&dw, dn, &dc);             /* (round and check) */
111     /* [this changes -0 to 0, so enforce the sign...] */
112     dw.bits|=dn->bits&DECNEG;
113     status=dc.status;                        /* save status */
114     dn=&dw;                                  /* use the work number */
115     } /* maybe out of range */
116
117   if (dn->bits&DECSPECIAL) {                      /* a special value */
118     if (dn->bits&DECINF) targhi=DECIMAL_Inf<<24;
119      else {                                       /* sNaN or qNaN */
120       if ((*dn->lsu!=0 || dn->digits>1)           /* non-zero coefficient */
121        && (dn->digits<DECIMAL64_Pmax)) {          /* coefficient fits */
122         decDigitsToDPD(dn, targar, 0);
123         }
124       if (dn->bits&DECNAN) targhi|=DECIMAL_NaN<<24;
125        else targhi|=DECIMAL_sNaN<<24;
126       } /* a NaN */
127     } /* special */
128
129    else { /* is finite */
130     if (decNumberIsZero(dn)) {               /* is a zero */
131       /* set and clamp exponent */
132       if (dn->exponent<-DECIMAL64_Bias) {
133         exp=0;                               /* low clamp */
134         status|=DEC_Clamped;
135         }
136        else {
137         exp=dn->exponent+DECIMAL64_Bias;     /* bias exponent */
138         if (exp>DECIMAL64_Ehigh) {           /* top clamp */
139           exp=DECIMAL64_Ehigh;
140           status|=DEC_Clamped;
141           }
142         }
143       comb=(exp>>5) & 0x18;             /* msd=0, exp top 2 bits .. */
144       }
145      else {                             /* non-zero finite number */
146       uInt msd;                         /* work */
147       Int pad=0;                        /* coefficient pad digits */
148
149       /* the dn is known to fit, but it may need to be padded */
150       exp=(uInt)(dn->exponent+DECIMAL64_Bias);    /* bias exponent */
151       if (exp>DECIMAL64_Ehigh) {                  /* fold-down case */
152         pad=exp-DECIMAL64_Ehigh;
153         exp=DECIMAL64_Ehigh;                      /* [to maximum] */
154         status|=DEC_Clamped;
155         }
156
157       /* fastpath common case */
158       if (DECDPUN==3 && pad==0) {
159         uInt dpd[6]={0,0,0,0,0,0};
160         uInt i;
161         Int d=dn->digits;
162         for (i=0; d>0; i++, d-=3) dpd[i]=BIN2DPD[dn->lsu[i]];
163         targlo =dpd[0];
164         targlo|=dpd[1]<<10;
165         targlo|=dpd[2]<<20;
166         if (dn->digits>6) {
167           targlo|=dpd[3]<<30;
168           targhi =dpd[3]>>2;
169           targhi|=dpd[4]<<8;
170           }
171         msd=dpd[5];                /* [did not really need conversion] */
172         }
173        else { /* general case */
174         decDigitsToDPD(dn, targar, pad);
175         /* save and clear the top digit */
176         msd=targhi>>18;
177         targhi&=0x0003ffff;
178         }
179
180       /* create the combination field */
181       if (msd>=8) comb=0x18 | ((exp>>7) & 0x06) | (msd & 0x01);
182              else comb=((exp>>5) & 0x18) | msd;
183       }
184     targhi|=comb<<26;              /* add combination field .. */
185     targhi|=(exp&0xff)<<18;        /* .. and exponent continuation */
186     } /* finite */
187
188   if (dn->bits&DECNEG) targhi|=0x80000000; /* add sign bit */
189
190   /* now write to storage; this is now always endian */
191   pu=(uInt *)d64->bytes;           /* overlay */
192   if (DECLITEND) {
193     pu[0]=targar[0];               /* directly store the low int */
194     pu[1]=targar[1];               /* then the high int */
195     }
196    else {
197     pu[0]=targar[1];               /* directly store the high int */
198     pu[1]=targar[0];               /* then the low int */
199     }
200
201   if (status!=0) decContextSetStatus(set, status); /* pass on status */
202   /* decimal64Show(d64); */
203   return d64;
204   } /* decimal64FromNumber */
205
206 /* ------------------------------------------------------------------ */
207 /* decimal64ToNumber -- convert decimal64 to decNumber                */
208 /*   d64 is the source decimal64                                      */
209 /*   dn is the target number, with appropriate space                  */
210 /* No error is possible.                                              */
211 /* ------------------------------------------------------------------ */
212 decNumber * decimal64ToNumber(const decimal64 *d64, decNumber *dn) {
213   uInt msd;                        /* coefficient MSD */
214   uInt exp;                        /* exponent top two bits */
215   uInt comb;                       /* combination field */
216   const uInt *pu;                  /* work */
217   Int  need;                       /* .. */
218   uInt sourar[2];                  /* source 64-bit */
219   #define sourhi sourar[1]         /* name the word with the sign */
220   #define sourlo sourar[0]         /* and the lower word */
221
222   /* load source from storage; this is endian */
223   pu=(const uInt *)d64->bytes;     /* overlay */
224   if (DECLITEND) {
225     sourlo=pu[0];                  /* directly load the low int */
226     sourhi=pu[1];                  /* then the high int */
227     }
228    else {
229     sourhi=pu[0];                  /* directly load the high int */
230     sourlo=pu[1];                  /* then the low int */
231     }
232
233   comb=(sourhi>>26)&0x1f;          /* combination field */
234
235   decNumberZero(dn);               /* clean number */
236   if (sourhi&0x80000000) dn->bits=DECNEG; /* set sign if negative */
237
238   msd=COMBMSD[comb];               /* decode the combination field */
239   exp=COMBEXP[comb];               /* .. */
240
241   if (exp==3) {                    /* is a special */
242     if (msd==0) {
243       dn->bits|=DECINF;
244       return dn;                   /* no coefficient needed */
245       }
246     else if (sourhi&0x02000000) dn->bits|=DECSNAN;
247     else dn->bits|=DECNAN;
248     msd=0;                         /* no top digit */
249     }
250    else {                          /* is a finite number */
251     dn->exponent=(exp<<8)+((sourhi>>18)&0xff)-DECIMAL64_Bias; /* unbiased */
252     }
253
254   /* get the coefficient */
255   sourhi&=0x0003ffff;              /* clean coefficient continuation */
256   if (msd) {                       /* non-zero msd */
257     sourhi|=msd<<18;               /* prefix to coefficient */
258     need=6;                        /* process 6 declets */
259     }
260    else { /* msd=0 */
261     if (!sourhi) {                 /* top word 0 */
262       if (!sourlo) return dn;      /* easy: coefficient is 0 */
263       need=3;                      /* process at least 3 declets */
264       if (sourlo&0xc0000000) need++; /* process 4 declets */
265       /* [could reduce some more, here] */
266       }
267      else {                        /* some bits in top word, msd=0 */
268       need=4;                      /* process at least 4 declets */
269       if (sourhi&0x0003ff00) need++; /* top declet!=0, process 5 */
270       }
271     } /*msd=0 */
272
273   decDigitsFromDPD(dn, sourar, need);   /* process declets */
274   return dn;
275   } /* decimal64ToNumber */
276
277
278 /* ------------------------------------------------------------------ */
279 /* to-scientific-string -- conversion to numeric string               */
280 /* to-engineering-string -- conversion to numeric string              */
281 /*                                                                    */
282 /*   decimal64ToString(d64, string);                                  */
283 /*   decimal64ToEngString(d64, string);                               */
284 /*                                                                    */
285 /*  d64 is the decimal64 format number to convert                     */
286 /*  string is the string where the result will be laid out            */
287 /*                                                                    */
288 /*  string must be at least 24 characters                             */
289 /*                                                                    */
290 /*  No error is possible, and no status can be set.                   */
291 /* ------------------------------------------------------------------ */
292 char * decimal64ToEngString(const decimal64 *d64, char *string){
293   decNumber dn;                         /* work */
294   decimal64ToNumber(d64, &dn);
295   decNumberToEngString(&dn, string);
296   return string;
297   } /* decimal64ToEngString */
298
299 char * decimal64ToString(const decimal64 *d64, char *string){
300   uInt msd;                        /* coefficient MSD */
301   Int  exp;                        /* exponent top two bits or full */
302   uInt comb;                       /* combination field */
303   char *cstart;                    /* coefficient start */
304   char *c;                         /* output pointer in string */
305   const uInt *pu;                  /* work */
306   char *s, *t;                     /* .. (source, target) */
307   Int  dpd;                        /* .. */
308   Int  pre, e;                     /* .. */
309   const uByte *u;                  /* .. */
310
311   uInt sourar[2];                  /* source 64-bit */
312   #define sourhi sourar[1]         /* name the word with the sign */
313   #define sourlo sourar[0]         /* and the lower word */
314
315   /* load source from storage; this is endian */
316   pu=(const uInt *)d64->bytes;     /* overlay */
317   if (DECLITEND) {
318     sourlo=pu[0];                  /* directly load the low int */
319     sourhi=pu[1];                  /* then the high int */
320     }
321    else {
322     sourhi=pu[0];                  /* directly load the high int */
323     sourlo=pu[1];                  /* then the low int */
324     }
325
326   c=string;                        /* where result will go */
327   if (((Int)sourhi)<0) *c++='-';   /* handle sign */
328
329   comb=(sourhi>>26)&0x1f;          /* combination field */
330   msd=COMBMSD[comb];               /* decode the combination field */
331   exp=COMBEXP[comb];               /* .. */
332
333   if (exp==3) {
334     if (msd==0) {                  /* infinity */
335       strcpy(c,   "Inf");
336       strcpy(c+3, "inity");
337       return string;               /* easy */
338       }
339     if (sourhi&0x02000000) *c++='s'; /* sNaN */
340     strcpy(c, "NaN");              /* complete word */
341     c+=3;                          /* step past */
342     if (sourlo==0 && (sourhi&0x0003ffff)==0) return string; /* zero payload */
343     /* otherwise drop through to add integer; set correct exp */
344     exp=0; msd=0;                  /* setup for following code */
345     }
346    else exp=(exp<<8)+((sourhi>>18)&0xff)-DECIMAL64_Bias;
347
348   /* convert 16 digits of significand to characters */
349   cstart=c;                        /* save start of coefficient */
350   if (msd) *c++='0'+(char)msd;     /* non-zero most significant digit */
351
352   /* Now decode the declets.  After extracting each one, it is */
353   /* decoded to binary and then to a 4-char sequence by table lookup; */
354   /* the 4-chars are a 1-char length (significant digits, except 000 */
355   /* has length 0).  This allows us to left-align the first declet */
356   /* with non-zero content, then remaining ones are full 3-char */
357   /* length.  We use fixed-length memcpys because variable-length */
358   /* causes a subroutine call in GCC.  (These are length 4 for speed */
359   /* and are safe because the array has an extra terminator byte.) */
360   #define dpd2char u=&BIN2CHAR[DPD2BIN[dpd]*4];                   \
361                    if (c!=cstart) {memcpy(c, u+1, 4); c+=3;}      \
362                     else if (*u)  {memcpy(c, u+4-*u, 4); c+=*u;}
363
364   dpd=(sourhi>>8)&0x3ff;                     /* declet 1 */
365   dpd2char;
366   dpd=((sourhi&0xff)<<2) | (sourlo>>30);     /* declet 2 */
367   dpd2char;
368   dpd=(sourlo>>20)&0x3ff;                    /* declet 3 */
369   dpd2char;
370   dpd=(sourlo>>10)&0x3ff;                    /* declet 4 */
371   dpd2char;
372   dpd=(sourlo)&0x3ff;                        /* declet 5 */
373   dpd2char;
374
375   if (c==cstart) *c++='0';         /* all zeros -- make 0 */
376
377   if (exp==0) {                    /* integer or NaN case -- easy */
378     *c='\0';                       /* terminate */
379     return string;
380     }
381
382   /* non-0 exponent */
383   e=0;                             /* assume no E */
384   pre=c-cstart+exp;
385   /* [here, pre-exp is the digits count (==1 for zero)] */
386   if (exp>0 || pre<-5) {           /* need exponential form */
387     e=pre-1;                       /* calculate E value */
388     pre=1;                         /* assume one digit before '.' */
389     } /* exponential form */
390
391   /* modify the coefficient, adding 0s, '.', and E+nn as needed */
392   s=c-1;                           /* source (LSD) */
393   if (pre>0) {                     /* ddd.ddd (plain), perhaps with E */
394     char *dotat=cstart+pre;
395     if (dotat<c) {                 /* if embedded dot needed... */
396       t=c;                              /* target */
397       for (; s>=dotat; s--, t--) *t=*s; /* open the gap; leave t at gap */
398       *t='.';                           /* insert the dot */
399       c++;                              /* length increased by one */
400       }
401
402     /* finally add the E-part, if needed; it will never be 0, and has */
403     /* a maximum length of 3 digits */
404     if (e!=0) {
405       *c++='E';                    /* starts with E */
406       *c++='+';                    /* assume positive */
407       if (e<0) {
408         *(c-1)='-';                /* oops, need '-' */
409         e=-e;                      /* uInt, please */
410         }
411       u=&BIN2CHAR[e*4];            /* -> length byte */
412       memcpy(c, u+4-*u, 4);        /* copy fixed 4 characters [is safe] */
413       c+=*u;                       /* bump pointer appropriately */
414       }
415     *c='\0';                       /* add terminator */
416     /*printf("res %s\n", string); */
417     return string;
418     } /* pre>0 */
419
420   /* -5<=pre<=0: here for plain 0.ddd or 0.000ddd forms (can never have E) */
421   t=c+1-pre;
422   *(t+1)='\0';                          /* can add terminator now */
423   for (; s>=cstart; s--, t--) *t=*s;    /* shift whole coefficient right */
424   c=cstart;
425   *c++='0';                             /* always starts with 0. */
426   *c++='.';
427   for (; pre<0; pre++) *c++='0';        /* add any 0's after '.' */
428   /*printf("res %s\n", string); */
429   return string;
430   } /* decimal64ToString */
431
432 /* ------------------------------------------------------------------ */
433 /* to-number -- conversion from numeric string                        */
434 /*                                                                    */
435 /*   decimal64FromString(result, string, set);                        */
436 /*                                                                    */
437 /*  result  is the decimal64 format number which gets the result of   */
438 /*          the conversion                                            */
439 /*  *string is the character string which should contain a valid      */
440 /*          number (which may be a special value)                     */
441 /*  set     is the context                                            */
442 /*                                                                    */
443 /* The context is supplied to this routine is used for error handling */
444 /* (setting of status and traps) and for the rounding mode, only.     */
445 /* If an error occurs, the result will be a valid decimal64 NaN.      */
446 /* ------------------------------------------------------------------ */
447 decimal64 * decimal64FromString(decimal64 *result, const char *string,
448                                 decContext *set) {
449   decContext dc;                             /* work */
450   decNumber dn;                              /* .. */
451
452   decContextDefault(&dc, DEC_INIT_DECIMAL64); /* no traps, please */
453   dc.round=set->round;                        /* use supplied rounding */
454
455   decNumberFromString(&dn, string, &dc);     /* will round if needed */
456
457   decimal64FromNumber(result, &dn, &dc);
458   if (dc.status!=0) {                        /* something happened */
459     decContextSetStatus(set, dc.status);     /* .. pass it on */
460     }
461   return result;
462   } /* decimal64FromString */
463
464 /* ------------------------------------------------------------------ */
465 /* decimal64IsCanonical -- test whether encoding is canonical         */
466 /*   d64 is the source decimal64                                      */
467 /*   returns 1 if the encoding of d64 is canonical, 0 otherwise       */
468 /* No error is possible.                                              */
469 /* ------------------------------------------------------------------ */
470 uint32_t decimal64IsCanonical(const decimal64 *d64) {
471   decNumber dn;                         /* work */
472   decimal64 canon;                      /* .. */
473   decContext dc;                        /* .. */
474   decContextDefault(&dc, DEC_INIT_DECIMAL64);
475   decimal64ToNumber(d64, &dn);
476   decimal64FromNumber(&canon, &dn, &dc);/* canon will now be canonical */
477   return memcmp(d64, &canon, DECIMAL64_Bytes)==0;
478   } /* decimal64IsCanonical */
479
480 /* ------------------------------------------------------------------ */
481 /* decimal64Canonical -- copy an encoding, ensuring it is canonical   */
482 /*   d64 is the source decimal64                                      */
483 /*   result is the target (may be the same decimal64)                 */
484 /*   returns result                                                   */
485 /* No error is possible.                                              */
486 /* ------------------------------------------------------------------ */
487 decimal64 * decimal64Canonical(decimal64 *result, const decimal64 *d64) {
488   decNumber dn;                         /* work */
489   decContext dc;                        /* .. */
490   decContextDefault(&dc, DEC_INIT_DECIMAL64);
491   decimal64ToNumber(d64, &dn);
492   decimal64FromNumber(result, &dn, &dc);/* result will now be canonical */
493   return result;
494   } /* decimal64Canonical */
495
496 #if DECTRACE || DECCHECK
497 /* Macros for accessing decimal64 fields.  These assume the
498    argument is a reference (pointer) to the decimal64 structure,
499    and the decimal64 is in network byte order (big-endian) */
500 /* Get sign */
501 #define decimal64Sign(d)       ((unsigned)(d)->bytes[0]>>7)
502
503 /* Get combination field */
504 #define decimal64Comb(d)       (((d)->bytes[0] & 0x7c)>>2)
505
506 /* Get exponent continuation [does not remove bias] */
507 #define decimal64ExpCon(d)     ((((d)->bytes[0] & 0x03)<<6)           \
508                              | ((unsigned)(d)->bytes[1]>>2))
509
510 /* Set sign [this assumes sign previously 0] */
511 #define decimal64SetSign(d, b) {                                      \
512   (d)->bytes[0]|=((unsigned)(b)<<7);}
513
514 /* Set exponent continuation [does not apply bias] */
515 /* This assumes range has been checked and exponent previously 0; */
516 /* type of exponent must be unsigned */
517 #define decimal64SetExpCon(d, e) {                                    \
518   (d)->bytes[0]|=(uint8_t)((e)>>6);                                   \
519   (d)->bytes[1]|=(uint8_t)(((e)&0x3F)<<2);}
520
521 /* ------------------------------------------------------------------ */
522 /* decimal64Show -- display a decimal64 in hexadecimal [debug aid]    */
523 /*   d64 -- the number to show                                        */
524 /* ------------------------------------------------------------------ */
525 /* Also shows sign/cob/expconfields extracted */
526 void decimal64Show(const decimal64 *d64) {
527   char buf[DECIMAL64_Bytes*2+1];
528   Int i, j=0;
529
530   if (DECLITEND) {
531     for (i=0; i<DECIMAL64_Bytes; i++, j+=2) {
532       sprintf(&buf[j], "%02x", d64->bytes[7-i]);
533       }
534     printf(" D64> %s [S:%d Cb:%02x Ec:%02x] LittleEndian\n", buf,
535            d64->bytes[7]>>7, (d64->bytes[7]>>2)&0x1f,
536            ((d64->bytes[7]&0x3)<<6)| (d64->bytes[6]>>2));
537     }
538    else { /* big-endian */
539     for (i=0; i<DECIMAL64_Bytes; i++, j+=2) {
540       sprintf(&buf[j], "%02x", d64->bytes[i]);
541       }
542     printf(" D64> %s [S:%d Cb:%02x Ec:%02x] BigEndian\n", buf,
543            decimal64Sign(d64), decimal64Comb(d64), decimal64ExpCon(d64));
544     }
545   } /* decimal64Show */
546 #endif
547
548 /* ================================================================== */
549 /* Shared utility routines and tables                                 */
550 /* ================================================================== */
551 /* define and include the conversion tables to use for shared code */
552 #if DECDPUN==3
553   #define DEC_DPD2BIN 1
554 #else
555   #define DEC_DPD2BCD 1
556 #endif
557 #include "decDPD.h"           /* lookup tables */
558
559 /* The maximum number of decNumberUnits needed for a working copy of */
560 /* the units array is the ceiling of digits/DECDPUN, where digits is */
561 /* the maximum number of digits in any of the formats for which this */
562 /* is used.  decimal128.h must not be included in this module, so, as */
563 /* a very special case, that number is defined as a literal here. */
564 #define DECMAX754   34
565 #define DECMAXUNITS ((DECMAX754+DECDPUN-1)/DECDPUN)
566
567 /* ------------------------------------------------------------------ */
568 /* Combination field lookup tables (uInts to save measurable work)    */
569 /*                                                                    */
570 /*      COMBEXP - 2-bit most-significant-bits of exponent             */
571 /*                [11 if an Infinity or NaN]                          */
572 /*      COMBMSD - 4-bit most-significant-digit                        */
573 /*                [0=Infinity, 1=NaN if COMBEXP=11]                   */
574 /*                                                                    */
575 /* Both are indexed by the 5-bit combination field (0-31)             */
576 /* ------------------------------------------------------------------ */
577 const uInt COMBEXP[32]={0, 0, 0, 0, 0, 0, 0, 0,
578                         1, 1, 1, 1, 1, 1, 1, 1,
579                         2, 2, 2, 2, 2, 2, 2, 2,
580                         0, 0, 1, 1, 2, 2, 3, 3};
581 const uInt COMBMSD[32]={0, 1, 2, 3, 4, 5, 6, 7,
582                         0, 1, 2, 3, 4, 5, 6, 7,
583                         0, 1, 2, 3, 4, 5, 6, 7,
584                         8, 9, 8, 9, 8, 9, 0, 1};
585
586 /* ------------------------------------------------------------------ */
587 /* decDigitsToDPD -- pack coefficient into DPD form                   */
588 /*                                                                    */
589 /*   dn   is the source number (assumed valid, max DECMAX754 digits)  */
590 /*   targ is 1, 2, or 4-element uInt array, which the caller must     */
591 /*        have cleared to zeros                                       */
592 /*   shift is the number of 0 digits to add on the right (normally 0) */
593 /*                                                                    */
594 /* The coefficient must be known small enough to fit.  The full       */
595 /* coefficient is copied, including the leading 'odd' digit.  This    */
596 /* digit is retrieved and packed into the combination field by the    */
597 /* caller.                                                            */
598 /*                                                                    */
599 /* The target uInts are altered only as necessary to receive the      */
600 /* digits of the decNumber.  When more than one uInt is needed, they  */
601 /* are filled from left to right (that is, the uInt at offset 0 will  */
602 /* end up with the least-significant digits).                         */
603 /*                                                                    */
604 /* shift is used for 'fold-down' padding.                             */
605 /*                                                                    */
606 /* No error is possible.                                              */
607 /* ------------------------------------------------------------------ */
608 #if DECDPUN<=4
609 /* Constant multipliers for divide-by-power-of five using reciprocal */
610 /* multiply, after removing powers of 2 by shifting, and final shift */
611 /* of 17 [we only need up to **4] */
612 static const uInt multies[]={131073, 26215, 5243, 1049, 210};
613 /* QUOT10 -- macro to return the quotient of unit u divided by 10**n */
614 #define QUOT10(u, n) ((((uInt)(u)>>(n))*multies[n])>>17)
615 #endif
616 void decDigitsToDPD(const decNumber *dn, uInt *targ, Int shift) {
617   Int  cut;                   /* work */
618   Int  n;                     /* output bunch counter */
619   Int  digits=dn->digits;     /* digit countdown */
620   uInt dpd;                   /* densely packed decimal value */
621   uInt bin;                   /* binary value 0-999 */
622   uInt *uout=targ;            /* -> current output uInt */
623   uInt  uoff=0;               /* -> current output offset [from right] */
624   const Unit *inu=dn->lsu;    /* -> current input unit */
625   Unit  uar[DECMAXUNITS];     /* working copy of units, iff shifted */
626   #if DECDPUN!=3              /* not fast path */
627     Unit in;                  /* current unit */
628   #endif
629
630   if (shift!=0) {             /* shift towards most significant required */
631     /* shift the units array to the left by pad digits and copy */
632     /* [this code is a special case of decShiftToMost, which could */
633     /* be used instead if exposed and the array were copied first] */
634     const Unit *source;                 /* .. */
635     Unit  *target, *first;              /* .. */
636     uInt  next=0;                       /* work */
637
638     source=dn->lsu+D2U(digits)-1;       /* where msu comes from */
639     target=uar+D2U(digits)-1+D2U(shift);/* where upper part of first cut goes */
640     cut=DECDPUN-MSUDIGITS(shift);       /* where to slice */
641     if (cut==0) {                       /* unit-boundary case */
642       for (; source>=dn->lsu; source--, target--) *target=*source;
643       }
644      else {
645       first=uar+D2U(digits+shift)-1;    /* where msu will end up */
646       for (; source>=dn->lsu; source--, target--) {
647         /* split the source Unit and accumulate remainder for next */
648         #if DECDPUN<=4
649           uInt quot=QUOT10(*source, cut);
650           uInt rem=*source-quot*DECPOWERS[cut];
651           next+=quot;
652         #else
653           uInt rem=*source%DECPOWERS[cut];
654           next+=*source/DECPOWERS[cut];
655         #endif
656         if (target<=first) *target=(Unit)next; /* write to target iff valid */
657         next=rem*DECPOWERS[DECDPUN-cut];       /* save remainder for next Unit */
658         }
659       } /* shift-move */
660     /* propagate remainder to one below and clear the rest */
661     for (; target>=uar; target--) {
662       *target=(Unit)next;
663       next=0;
664       }
665     digits+=shift;                 /* add count (shift) of zeros added */
666     inu=uar;                       /* use units in working array */
667     }
668
669   /* now densely pack the coefficient into DPD declets */
670
671   #if DECDPUN!=3                   /* not fast path */
672     in=*inu;                       /* current unit */
673     cut=0;                         /* at lowest digit */
674     bin=0;                         /* [keep compiler quiet] */
675   #endif
676
677   for(n=0; digits>0; n++) {        /* each output bunch */
678     #if DECDPUN==3                 /* fast path, 3-at-a-time */
679       bin=*inu;                    /* 3 digits ready for convert */
680       digits-=3;                   /* [may go negative] */
681       inu++;                       /* may need another */
682
683     #else                          /* must collect digit-by-digit */
684       Unit dig;                    /* current digit */
685       Int j;                       /* digit-in-declet count */
686       for (j=0; j<3; j++) {
687         #if DECDPUN<=4
688           Unit temp=(Unit)((uInt)(in*6554)>>16);
689           dig=(Unit)(in-X10(temp));
690           in=temp;
691         #else
692           dig=in%10;
693           in=in/10;
694         #endif
695         if (j==0) bin=dig;
696          else if (j==1)  bin+=X10(dig);
697          else /* j==2 */ bin+=X100(dig);
698         digits--;
699         if (digits==0) break;      /* [also protects *inu below] */
700         cut++;
701         if (cut==DECDPUN) {inu++; in=*inu; cut=0;}
702         }
703     #endif
704     /* here there are 3 digits in bin, or have used all input digits */
705
706     dpd=BIN2DPD[bin];
707
708     /* write declet to uInt array */
709     *uout|=dpd<<uoff;
710     uoff+=10;
711     if (uoff<32) continue;         /* no uInt boundary cross */
712     uout++;
713     uoff-=32;
714     *uout|=dpd>>(10-uoff);         /* collect top bits */
715     } /* n declets */
716   return;
717   } /* decDigitsToDPD */
718
719 /* ------------------------------------------------------------------ */
720 /* decDigitsFromDPD -- unpack a format's coefficient                  */
721 /*                                                                    */
722 /*   dn is the target number, with 7, 16, or 34-digit space.          */
723 /*   sour is a 1, 2, or 4-element uInt array containing only declets  */
724 /*   declets is the number of (right-aligned) declets in sour to      */
725 /*     be processed.  This may be 1 more than the obvious number in   */
726 /*     a format, as any top digit is prefixed to the coefficient      */
727 /*     continuation field.  It also may be as small as 1, as the      */
728 /*     caller may pre-process leading zero declets.                   */
729 /*                                                                    */
730 /* When doing the 'extra declet' case care is taken to avoid writing  */
731 /* extra digits when there are leading zeros, as these could overflow */
732 /* the units array when DECDPUN is not 3.                             */
733 /*                                                                    */
734 /* The target uInts are used only as necessary to process declets     */
735 /* declets into the decNumber.  When more than one uInt is needed,    */
736 /* they are used from left to right (that is, the uInt at offset 0    */
737 /* provides the least-significant digits).                            */
738 /*                                                                    */
739 /* dn->digits is set, but not the sign or exponent.                   */
740 /* No error is possible [the redundant 888 codes are allowed].        */
741 /* ------------------------------------------------------------------ */
742 void decDigitsFromDPD(decNumber *dn, const uInt *sour, Int declets) {
743
744   uInt  dpd;                       /* collector for 10 bits */
745   Int   n;                         /* counter */
746   Unit  *uout=dn->lsu;             /* -> current output unit */
747   Unit  *last=uout;                /* will be unit containing msd */
748   const uInt *uin=sour;            /* -> current input uInt */
749   uInt  uoff=0;                    /* -> current input offset [from right] */
750
751   #if DECDPUN!=3
752   uInt  bcd;                       /* BCD result */
753   uInt  nibble;                    /* work */
754   Unit  out=0;                     /* accumulator */
755   Int   cut=0;                     /* power of ten in current unit */
756   #endif
757   #if DECDPUN>4
758   uInt const *pow;                 /* work */
759   #endif
760
761   /* Expand the densely-packed integer, right to left */
762   for (n=declets-1; n>=0; n--) {   /* count down declets of 10 bits */
763     dpd=*uin>>uoff;
764     uoff+=10;
765     if (uoff>32) {                 /* crossed uInt boundary */
766       uin++;
767       uoff-=32;
768       dpd|=*uin<<(10-uoff);        /* get waiting bits */
769       }
770     dpd&=0x3ff;                    /* clear uninteresting bits */
771
772   #if DECDPUN==3
773     if (dpd==0) *uout=0;
774      else {
775       *uout=DPD2BIN[dpd];          /* convert 10 bits to binary 0-999 */
776       last=uout;                   /* record most significant unit */
777       }
778     uout++;
779     } /* n */
780
781   #else /* DECDPUN!=3 */
782     if (dpd==0) {                  /* fastpath [e.g., leading zeros] */
783       /* write out three 0 digits (nibbles); out may have digit(s) */
784       cut++;
785       if (cut==DECDPUN) {*uout=out; if (out) {last=uout; out=0;} uout++; cut=0;}
786       if (n==0) break;             /* [as below, works even if MSD=0] */
787       cut++;
788       if (cut==DECDPUN) {*uout=out; if (out) {last=uout; out=0;} uout++; cut=0;}
789       cut++;
790       if (cut==DECDPUN) {*uout=out; if (out) {last=uout; out=0;} uout++; cut=0;}
791       continue;
792       }
793
794     bcd=DPD2BCD[dpd];              /* convert 10 bits to 12 bits BCD */
795
796     /* now accumulate the 3 BCD nibbles into units */
797     nibble=bcd & 0x00f;
798     if (nibble) out=(Unit)(out+nibble*DECPOWERS[cut]);
799     cut++;
800     if (cut==DECDPUN) {*uout=out; if (out) {last=uout; out=0;} uout++; cut=0;}
801     bcd>>=4;
802
803     /* if this is the last declet and the remaining nibbles in bcd */
804     /* are 00 then process no more nibbles, because this could be */
805     /* the 'odd' MSD declet and writing any more Units would then */
806     /* overflow the unit array */
807     if (n==0 && !bcd) break;
808
809     nibble=bcd & 0x00f;
810     if (nibble) out=(Unit)(out+nibble*DECPOWERS[cut]);
811     cut++;
812     if (cut==DECDPUN) {*uout=out; if (out) {last=uout; out=0;} uout++; cut=0;}
813     bcd>>=4;
814
815     nibble=bcd & 0x00f;
816     if (nibble) out=(Unit)(out+nibble*DECPOWERS[cut]);
817     cut++;
818     if (cut==DECDPUN) {*uout=out; if (out) {last=uout; out=0;} uout++; cut=0;}
819     } /* n */
820   if (cut!=0) {                         /* some more left over */
821     *uout=out;                          /* write out final unit */
822     if (out) last=uout;                 /* and note if non-zero */
823     }
824   #endif
825
826   /* here, last points to the most significant unit with digits; */
827   /* inspect it to get the final digits count -- this is essentially */
828   /* the same code as decGetDigits in decNumber.c */
829   dn->digits=(last-dn->lsu)*DECDPUN+1;  /* floor of digits, plus */
830                                         /* must be at least 1 digit */
831   #if DECDPUN>1
832   if (*last<10) return;                 /* common odd digit or 0 */
833   dn->digits++;                         /* must be 2 at least */
834   #if DECDPUN>2
835   if (*last<100) return;                /* 10-99 */
836   dn->digits++;                         /* must be 3 at least */
837   #if DECDPUN>3
838   if (*last<1000) return;               /* 100-999 */
839   dn->digits++;                         /* must be 4 at least */
840   #if DECDPUN>4
841   for (pow=&DECPOWERS[4]; *last>=*pow; pow++) dn->digits++;
842   #endif
843   #endif
844   #endif
845   #endif
846   return;
847   } /*decDigitsFromDPD */