1/* Decimal 64-bit format module for the decNumber C Library.
2   Copyright (C) 2005-2015 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
17Under Section 7 of GPL version 3, you are granted additional
18permissions described in the GCC Runtime Library Exception, version
193.1, as published by the Free Software Foundation.
20
21You should have received a copy of the GNU General Public License and
22a copy of the GCC Runtime Library Exception along with this program;
23see 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++ */
47extern const uInt COMBEXP[32], COMBMSD[32];
48extern const uShort DPD2BIN[1024];
49extern const uShort BIN2DPD[1000];
50extern const uByte  BIN2CHAR[4001];
51
52extern void decDigitsFromDPD(decNumber *, const uInt *, Int);
53extern void decDigitsToDPD(const decNumber *, uInt *, Int);
54
55#if DECTRACE || DECCHECK
56void decimal64Show(const decimal64 *);		  /* for debug */
57extern 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/* ------------------------------------------------------------------ */
87decimal64 * 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 comb, exp;		   /* .. */
94  uInt uiwork;			   /* for macros */
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  if (DECLITEND) {
192    /* lo int then hi */
193    UBFROMUI(d64->bytes,   targar[0]);
194    UBFROMUI(d64->bytes+4, targar[1]);
195    }
196   else {
197    /* hi int then lo */
198    UBFROMUI(d64->bytes,   targar[1]);
199    UBFROMUI(d64->bytes+4, targar[0]);
200    }
201
202  if (status!=0) decContextSetStatus(set, status); /* pass on status */
203  /* decimal64Show(d64); */
204  return d64;
205  } /* decimal64FromNumber */
206
207/* ------------------------------------------------------------------ */
208/* decimal64ToNumber -- convert decimal64 to decNumber		      */
209/*   d64 is the source decimal64				      */
210/*   dn is the target number, with appropriate space		      */
211/* No error is possible.					      */
212/* ------------------------------------------------------------------ */
213decNumber * decimal64ToNumber(const decimal64 *d64, decNumber *dn) {
214  uInt msd;			   /* coefficient MSD */
215  uInt exp;			   /* exponent top two bits */
216  uInt comb;			   /* combination field */
217  Int  need;			   /* work */
218  uInt uiwork;			   /* for macros */
219  uInt sourar[2];		   /* source 64-bit */
220  #define sourhi sourar[1]	   /* name the word with the sign */
221  #define sourlo sourar[0]	   /* and the lower word */
222
223  /* load source from storage; this is endian */
224  if (DECLITEND) {
225    sourlo=UBTOUI(d64->bytes  );   /* directly load the low int */
226    sourhi=UBTOUI(d64->bytes+4);   /* then the high int */
227    }
228   else {
229    sourhi=UBTOUI(d64->bytes  );   /* directly load the high int */
230    sourlo=UBTOUI(d64->bytes+4);   /* 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/* ------------------------------------------------------------------ */
292char * decimal64ToEngString(const decimal64 *d64, char *string){
293  decNumber dn; 			/* work */
294  decimal64ToNumber(d64, &dn);
295  decNumberToEngString(&dn, string);
296  return string;
297  } /* decimal64ToEngString */
298
299char * 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 uByte *u;		   /* work */
306  char *s, *t;			   /* .. (source, target) */
307  Int  dpd;			   /* .. */
308  Int  pre, e;			   /* .. */
309  uInt uiwork;			   /* for macros */
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  if (DECLITEND) {
317    sourlo=UBTOUI(d64->bytes  );   /* directly load the low int */
318    sourhi=UBTOUI(d64->bytes+4);   /* then the high int */
319    }
320   else {
321    sourhi=UBTOUI(d64->bytes  );   /* directly load the high int */
322    sourlo=UBTOUI(d64->bytes+4);   /* then the low int */
323    }
324
325  c=string;			   /* where result will go */
326  if (((Int)sourhi)<0) *c++='-';   /* handle sign */
327
328  comb=(sourhi>>26)&0x1f;	   /* combination field */
329  msd=COMBMSD[comb];		   /* decode the combination field */
330  exp=COMBEXP[comb];		   /* .. */
331
332  if (exp==3) {
333    if (msd==0) {		   /* infinity */
334      strcpy(c,   "Inf");
335      strcpy(c+3, "inity");
336      return string;		   /* easy */
337      }
338    if (sourhi&0x02000000) *c++='s'; /* sNaN */
339    strcpy(c, "NaN");		   /* complete word */
340    c+=3;			   /* step past */
341    if (sourlo==0 && (sourhi&0x0003ffff)==0) return string; /* zero payload */
342    /* otherwise drop through to add integer; set correct exp */
343    exp=0; msd=0;		   /* setup for following code */
344    }
345   else exp=(exp<<8)+((sourhi>>18)&0xff)-DECIMAL64_Bias;
346
347  /* convert 16 digits of significand to characters */
348  cstart=c;			   /* save start of coefficient */
349  if (msd) *c++='0'+(char)msd;	   /* non-zero most significant digit */
350
351  /* Now decode the declets.  After extracting each one, it is */
352  /* decoded to binary and then to a 4-char sequence by table lookup; */
353  /* the 4-chars are a 1-char length (significant digits, except 000 */
354  /* has length 0).  This allows us to left-align the first declet */
355  /* with non-zero content, then remaining ones are full 3-char */
356  /* length.  We use fixed-length memcpys because variable-length */
357  /* causes a subroutine call in GCC.  (These are length 4 for speed */
358  /* and are safe because the array has an extra terminator byte.) */
359  #define dpd2char u=&BIN2CHAR[DPD2BIN[dpd]*4]; 		  \
360		   if (c!=cstart) {memcpy(c, u+1, 4); c+=3;}	  \
361		    else if (*u)  {memcpy(c, u+4-*u, 4); c+=*u;}
362
363  dpd=(sourhi>>8)&0x3ff;		     /* declet 1 */
364  dpd2char;
365  dpd=((sourhi&0xff)<<2) | (sourlo>>30);     /* declet 2 */
366  dpd2char;
367  dpd=(sourlo>>20)&0x3ff;		     /* declet 3 */
368  dpd2char;
369  dpd=(sourlo>>10)&0x3ff;		     /* declet 4 */
370  dpd2char;
371  dpd=(sourlo)&0x3ff;			     /* declet 5 */
372  dpd2char;
373
374  if (c==cstart) *c++='0';	   /* all zeros -- make 0 */
375
376  if (exp==0) { 		   /* integer or NaN case -- easy */
377    *c='\0';			   /* terminate */
378    return string;
379    }
380
381  /* non-0 exponent */
382  e=0;				   /* assume no E */
383  pre=c-cstart+exp;
384  /* [here, pre-exp is the digits count (==1 for zero)] */
385  if (exp>0 || pre<-5) {	   /* need exponential form */
386    e=pre-1;			   /* calculate E value */
387    pre=1;			   /* assume one digit before '.' */
388    } /* exponential form */
389
390  /* modify the coefficient, adding 0s, '.', and E+nn as needed */
391  s=c-1;			   /* source (LSD) */
392  if (pre>0) {			   /* ddd.ddd (plain), perhaps with E */
393    char *dotat=cstart+pre;
394    if (dotat<c) {		   /* if embedded dot needed... */
395      t=c;				/* target */
396      for (; s>=dotat; s--, t--) *t=*s; /* open the gap; leave t at gap */
397      *t='.';				/* insert the dot */
398      c++;				/* length increased by one */
399      }
400
401    /* finally add the E-part, if needed; it will never be 0, and has */
402    /* a maximum length of 3 digits */
403    if (e!=0) {
404      *c++='E'; 		   /* starts with E */
405      *c++='+'; 		   /* assume positive */
406      if (e<0) {
407	*(c-1)='-';		   /* oops, need '-' */
408	e=-e;			   /* uInt, please */
409	}
410      u=&BIN2CHAR[e*4]; 	   /* -> length byte */
411      memcpy(c, u+4-*u, 4);	   /* copy fixed 4 characters [is safe] */
412      c+=*u;			   /* bump pointer appropriately */
413      }
414    *c='\0';			   /* add terminator */
415    /*printf("res %s\n", string); */
416    return string;
417    } /* pre>0 */
418
419  /* -5<=pre<=0: here for plain 0.ddd or 0.000ddd forms (can never have E) */
420  t=c+1-pre;
421  *(t+1)='\0';				/* can add terminator now */
422  for (; s>=cstart; s--, t--) *t=*s;	/* shift whole coefficient right */
423  c=cstart;
424  *c++='0';				/* always starts with 0. */
425  *c++='.';
426  for (; pre<0; pre++) *c++='0';	/* add any 0's after '.' */
427  /*printf("res %s\n", string); */
428  return string;
429  } /* decimal64ToString */
430
431/* ------------------------------------------------------------------ */
432/* to-number -- conversion from numeric string			      */
433/*								      */
434/*   decimal64FromString(result, string, set);			      */
435/*								      */
436/*  result  is the decimal64 format number which gets the result of   */
437/*	    the conversion					      */
438/*  *string is the character string which should contain a valid      */
439/*	    number (which may be a special value)		      */
440/*  set     is the context					      */
441/*								      */
442/* The context is supplied to this routine is used for error handling */
443/* (setting of status and traps) and for the rounding mode, only.     */
444/* If an error occurs, the result will be a valid decimal64 NaN.      */
445/* ------------------------------------------------------------------ */
446decimal64 * decimal64FromString(decimal64 *result, const char *string,
447				decContext *set) {
448  decContext dc;			     /* work */
449  decNumber dn; 			     /* .. */
450
451  decContextDefault(&dc, DEC_INIT_DECIMAL64); /* no traps, please */
452  dc.round=set->round;			      /* use supplied rounding */
453
454  decNumberFromString(&dn, string, &dc);     /* will round if needed */
455
456  decimal64FromNumber(result, &dn, &dc);
457  if (dc.status!=0) {			     /* something happened */
458    decContextSetStatus(set, dc.status);     /* .. pass it on */
459    }
460  return result;
461  } /* decimal64FromString */
462
463/* ------------------------------------------------------------------ */
464/* decimal64IsCanonical -- test whether encoding is canonical	      */
465/*   d64 is the source decimal64				      */
466/*   returns 1 if the encoding of d64 is canonical, 0 otherwise       */
467/* No error is possible.					      */
468/* ------------------------------------------------------------------ */
469uInt decimal64IsCanonical(const decimal64 *d64) {
470  decNumber dn; 			/* work */
471  decimal64 canon;			/* .. */
472  decContext dc;			/* .. */
473  decContextDefault(&dc, DEC_INIT_DECIMAL64);
474  decimal64ToNumber(d64, &dn);
475  decimal64FromNumber(&canon, &dn, &dc);/* canon will now be canonical */
476  return memcmp(d64, &canon, DECIMAL64_Bytes)==0;
477  } /* decimal64IsCanonical */
478
479/* ------------------------------------------------------------------ */
480/* decimal64Canonical -- copy an encoding, ensuring it is canonical   */
481/*   d64 is the source decimal64				      */
482/*   result is the target (may be the same decimal64)		      */
483/*   returns result						      */
484/* No error is possible.					      */
485/* ------------------------------------------------------------------ */
486decimal64 * decimal64Canonical(decimal64 *result, const decimal64 *d64) {
487  decNumber dn; 			/* work */
488  decContext dc;			/* .. */
489  decContextDefault(&dc, DEC_INIT_DECIMAL64);
490  decimal64ToNumber(d64, &dn);
491  decimal64FromNumber(result, &dn, &dc);/* result will now be canonical */
492  return result;
493  } /* decimal64Canonical */
494
495#if DECTRACE || DECCHECK
496/* Macros for accessing decimal64 fields.  These assume the
497   argument is a reference (pointer) to the decimal64 structure,
498   and the decimal64 is in network byte order (big-endian) */
499/* Get sign */
500#define decimal64Sign(d)       ((unsigned)(d)->bytes[0]>>7)
501
502/* Get combination field */
503#define decimal64Comb(d)       (((d)->bytes[0] & 0x7c)>>2)
504
505/* Get exponent continuation [does not remove bias] */
506#define decimal64ExpCon(d)     ((((d)->bytes[0] & 0x03)<<6)	      \
507			     | ((unsigned)(d)->bytes[1]>>2))
508
509/* Set sign [this assumes sign previously 0] */
510#define decimal64SetSign(d, b) {				      \
511  (d)->bytes[0]|=((unsigned)(b)<<7);}
512
513/* Set exponent continuation [does not apply bias] */
514/* This assumes range has been checked and exponent previously 0; */
515/* type of exponent must be unsigned */
516#define decimal64SetExpCon(d, e) {				      \
517  (d)->bytes[0]|=(uByte)((e)>>6);				      \
518  (d)->bytes[1]|=(uByte)(((e)&0x3F)<<2);}
519
520/* ------------------------------------------------------------------ */
521/* decimal64Show -- display a decimal64 in hexadecimal [debug aid]    */
522/*   d64 -- the number to show					      */
523/* ------------------------------------------------------------------ */
524/* Also shows sign/cob/expconfields extracted */
525void decimal64Show(const decimal64 *d64) {
526  char buf[DECIMAL64_Bytes*2+1];
527  Int i, j=0;
528
529  if (DECLITEND) {
530    for (i=0; i<DECIMAL64_Bytes; i++, j+=2) {
531      sprintf(&buf[j], "%02x", d64->bytes[7-i]);
532      }
533    printf(" D64> %s [S:%d Cb:%02x Ec:%02x] LittleEndian\n", buf,
534	   d64->bytes[7]>>7, (d64->bytes[7]>>2)&0x1f,
535	   ((d64->bytes[7]&0x3)<<6)| (d64->bytes[6]>>2));
536    }
537   else { /* big-endian */
538    for (i=0; i<DECIMAL64_Bytes; i++, j+=2) {
539      sprintf(&buf[j], "%02x", d64->bytes[i]);
540      }
541    printf(" D64> %s [S:%d Cb:%02x Ec:%02x] BigEndian\n", buf,
542	   decimal64Sign(d64), decimal64Comb(d64), decimal64ExpCon(d64));
543    }
544  } /* decimal64Show */
545#endif
546
547/* ================================================================== */
548/* Shared utility routines and tables				      */
549/* ================================================================== */
550/* define and include the conversion tables to use for shared code */
551#if DECDPUN==3
552  #define DEC_DPD2BIN 1
553#else
554  #define DEC_DPD2BCD 1
555#endif
556#include "decDPD.h"	      /* lookup tables */
557
558/* The maximum number of decNumberUnits needed for a working copy of */
559/* the units array is the ceiling of digits/DECDPUN, where digits is */
560/* the maximum number of digits in any of the formats for which this */
561/* is used.  decimal128.h must not be included in this module, so, as */
562/* a very special case, that number is defined as a literal here. */
563#define DECMAX754   34
564#define DECMAXUNITS ((DECMAX754+DECDPUN-1)/DECDPUN)
565
566/* ------------------------------------------------------------------ */
567/* Combination field lookup tables (uInts to save measurable work)    */
568/*								      */
569/*	COMBEXP - 2-bit most-significant-bits of exponent	      */
570/*		  [11 if an Infinity or NaN]			      */
571/*	COMBMSD - 4-bit most-significant-digit			      */
572/*		  [0=Infinity, 1=NaN if COMBEXP=11]		      */
573/*								      */
574/* Both are indexed by the 5-bit combination field (0-31)	      */
575/* ------------------------------------------------------------------ */
576const uInt COMBEXP[32]={0, 0, 0, 0, 0, 0, 0, 0,
577			1, 1, 1, 1, 1, 1, 1, 1,
578			2, 2, 2, 2, 2, 2, 2, 2,
579			0, 0, 1, 1, 2, 2, 3, 3};
580const uInt COMBMSD[32]={0, 1, 2, 3, 4, 5, 6, 7,
581			0, 1, 2, 3, 4, 5, 6, 7,
582			0, 1, 2, 3, 4, 5, 6, 7,
583			8, 9, 8, 9, 8, 9, 0, 1};
584
585/* ------------------------------------------------------------------ */
586/* decDigitsToDPD -- pack coefficient into DPD form		      */
587/*								      */
588/*   dn   is the source number (assumed valid, max DECMAX754 digits)  */
589/*   targ is 1, 2, or 4-element uInt array, which the caller must     */
590/*	  have cleared to zeros 				      */
591/*   shift is the number of 0 digits to add on the right (normally 0) */
592/*								      */
593/* The coefficient must be known small enough to fit.  The full       */
594/* coefficient is copied, including the leading 'odd' digit.  This    */
595/* digit is retrieved and packed into the combination field by the    */
596/* caller.							      */
597/*								      */
598/* The target uInts are altered only as necessary to receive the      */
599/* digits of the decNumber.  When more than one uInt is needed, they  */
600/* are filled from left to right (that is, the uInt at offset 0 will  */
601/* end up with the least-significant digits).			      */
602/*								      */
603/* shift is used for 'fold-down' padding.			      */
604/*								      */
605/* No error is possible.					      */
606/* ------------------------------------------------------------------ */
607#if DECDPUN<=4
608/* Constant multipliers for divide-by-power-of five using reciprocal */
609/* multiply, after removing powers of 2 by shifting, and final shift */
610/* of 17 [we only need up to **4] */
611static const uInt multies[]={131073, 26215, 5243, 1049, 210};
612/* QUOT10 -- macro to return the quotient of unit u divided by 10**n */
613#define QUOT10(u, n) ((((uInt)(u)>>(n))*multies[n])>>17)
614#endif
615void decDigitsToDPD(const decNumber *dn, uInt *targ, Int shift) {
616  Int  cut;		      /* work */
617  Int  n;		      /* output bunch counter */
618  Int  digits=dn->digits;     /* digit countdown */
619  uInt dpd;		      /* densely packed decimal value */
620  uInt bin;		      /* binary value 0-999 */
621  uInt *uout=targ;	      /* -> current output uInt */
622  uInt	uoff=0; 	      /* -> current output offset [from right] */
623  const Unit *inu=dn->lsu;    /* -> current input unit */
624  Unit	uar[DECMAXUNITS];     /* working copy of units, iff shifted */
625  #if DECDPUN!=3	      /* not fast path */
626    Unit in;		      /* current unit */
627  #endif
628
629  if (shift!=0) {	      /* shift towards most significant required */
630    /* shift the units array to the left by pad digits and copy */
631    /* [this code is a special case of decShiftToMost, which could */
632    /* be used instead if exposed and the array were copied first] */
633    const Unit *source; 		/* .. */
634    Unit  *target, *first;		/* .. */
635    uInt  next=0;			/* work */
636
637    source=dn->lsu+D2U(digits)-1;	/* where msu comes from */
638    target=uar+D2U(digits)-1+D2U(shift);/* where upper part of first cut goes */
639    cut=DECDPUN-MSUDIGITS(shift);	/* where to slice */
640    if (cut==0) {			/* unit-boundary case */
641      for (; source>=dn->lsu; source--, target--) *target=*source;
642      }
643     else {
644      first=uar+D2U(digits+shift)-1;	/* where msu will end up */
645      for (; source>=dn->lsu; source--, target--) {
646	/* split the source Unit and accumulate remainder for next */
647	#if DECDPUN<=4
648	  uInt quot=QUOT10(*source, cut);
649	  uInt rem=*source-quot*DECPOWERS[cut];
650	  next+=quot;
651	#else
652	  uInt rem=*source%DECPOWERS[cut];
653	  next+=*source/DECPOWERS[cut];
654	#endif
655	if (target<=first) *target=(Unit)next; /* write to target iff valid */
656	next=rem*DECPOWERS[DECDPUN-cut];       /* save remainder for next Unit */
657	}
658      } /* shift-move */
659    /* propagate remainder to one below and clear the rest */
660    for (; target>=uar; target--) {
661      *target=(Unit)next;
662      next=0;
663      }
664    digits+=shift;		   /* add count (shift) of zeros added */
665    inu=uar;			   /* use units in working array */
666    }
667
668  /* now densely pack the coefficient into DPD declets */
669
670  #if DECDPUN!=3		   /* not fast path */
671    in=*inu;			   /* current unit */
672    cut=0;			   /* at lowest digit */
673    bin=0;			   /* [keep compiler quiet] */
674  #endif
675
676  for(n=0; digits>0; n++) {	   /* each output bunch */
677    #if DECDPUN==3		   /* fast path, 3-at-a-time */
678      bin=*inu; 		   /* 3 digits ready for convert */
679      digits-=3;		   /* [may go negative] */
680      inu++;			   /* may need another */
681
682    #else			   /* must collect digit-by-digit */
683      Unit dig; 		   /* current digit */
684      Int j;			   /* digit-in-declet count */
685      for (j=0; j<3; j++) {
686	#if DECDPUN<=4
687	  Unit temp=(Unit)((uInt)(in*6554)>>16);
688	  dig=(Unit)(in-X10(temp));
689	  in=temp;
690	#else
691	  dig=in%10;
692	  in=in/10;
693	#endif
694	if (j==0) bin=dig;
695	 else if (j==1)  bin+=X10(dig);
696	 else /* j==2 */ bin+=X100(dig);
697	digits--;
698	if (digits==0) break;	   /* [also protects *inu below] */
699	cut++;
700	if (cut==DECDPUN) {inu++; in=*inu; cut=0;}
701	}
702    #endif
703    /* here there are 3 digits in bin, or have used all input digits */
704
705    dpd=BIN2DPD[bin];
706
707    /* write declet to uInt array */
708    *uout|=dpd<<uoff;
709    uoff+=10;
710    if (uoff<32) continue;	   /* no uInt boundary cross */
711    uout++;
712    uoff-=32;
713    *uout|=dpd>>(10-uoff);	   /* collect top bits */
714    } /* n declets */
715  return;
716  } /* decDigitsToDPD */
717
718/* ------------------------------------------------------------------ */
719/* decDigitsFromDPD -- unpack a format's coefficient		      */
720/*								      */
721/*   dn is the target number, with 7, 16, or 34-digit space.	      */
722/*   sour is a 1, 2, or 4-element uInt array containing only declets  */
723/*   declets is the number of (right-aligned) declets in sour to      */
724/*     be processed.  This may be 1 more than the obvious number in   */
725/*     a format, as any top digit is prefixed to the coefficient      */
726/*     continuation field.  It also may be as small as 1, as the      */
727/*     caller may pre-process leading zero declets.		      */
728/*								      */
729/* When doing the 'extra declet' case care is taken to avoid writing  */
730/* extra digits when there are leading zeros, as these could overflow */
731/* the units array when DECDPUN is not 3.			      */
732/*								      */
733/* The target uInts are used only as necessary to process declets     */
734/* declets into the decNumber.	When more than one uInt is needed,    */
735/* they are used from left to right (that is, the uInt at offset 0    */
736/* provides the least-significant digits).			      */
737/*								      */
738/* dn->digits is set, but not the sign or exponent.		      */
739/* No error is possible [the redundant 888 codes are allowed].	      */
740/* ------------------------------------------------------------------ */
741void decDigitsFromDPD(decNumber *dn, const uInt *sour, Int declets) {
742
743  uInt	dpd;			   /* collector for 10 bits */
744  Int	n;			   /* counter */
745  Unit	*uout=dn->lsu;		   /* -> current output unit */
746  Unit	*last=uout;		   /* will be unit containing msd */
747  const uInt *uin=sour; 	   /* -> current input uInt */
748  uInt	uoff=0; 		   /* -> current input offset [from right] */
749
750  #if DECDPUN!=3
751  uInt	bcd;			   /* BCD result */
752  uInt	nibble; 		   /* work */
753  Unit	out=0;			   /* accumulator */
754  Int	cut=0;			   /* power of ten in current unit */
755  #endif
756  #if DECDPUN>4
757  uInt const *pow;		   /* work */
758  #endif
759
760  /* Expand the densely-packed integer, right to left */
761  for (n=declets-1; n>=0; n--) {   /* count down declets of 10 bits */
762    dpd=*uin>>uoff;
763    uoff+=10;
764    if (uoff>32) {		   /* crossed uInt boundary */
765      uin++;
766      uoff-=32;
767      dpd|=*uin<<(10-uoff);	   /* get waiting bits */
768      }
769    dpd&=0x3ff; 		   /* clear uninteresting bits */
770
771  #if DECDPUN==3
772    if (dpd==0) *uout=0;
773     else {
774      *uout=DPD2BIN[dpd];	   /* convert 10 bits to binary 0-999 */
775      last=uout;		   /* record most significant unit */
776      }
777    uout++;
778    } /* n */
779
780  #else /* DECDPUN!=3 */
781    if (dpd==0) {		   /* fastpath [e.g., leading zeros] */
782      /* write out three 0 digits (nibbles); out may have digit(s) */
783      cut++;
784      if (cut==DECDPUN) {*uout=out; if (out) {last=uout; out=0;} uout++; cut=0;}
785      if (n==0) break;		   /* [as below, works even if MSD=0] */
786      cut++;
787      if (cut==DECDPUN) {*uout=out; if (out) {last=uout; out=0;} uout++; cut=0;}
788      cut++;
789      if (cut==DECDPUN) {*uout=out; if (out) {last=uout; out=0;} uout++; cut=0;}
790      continue;
791      }
792
793    bcd=DPD2BCD[dpd];		   /* convert 10 bits to 12 bits BCD */
794
795    /* now accumulate the 3 BCD nibbles into units */
796    nibble=bcd & 0x00f;
797    if (nibble) out=(Unit)(out+nibble*DECPOWERS[cut]);
798    cut++;
799    if (cut==DECDPUN) {*uout=out; if (out) {last=uout; out=0;} uout++; cut=0;}
800    bcd>>=4;
801
802    /* if this is the last declet and the remaining nibbles in bcd */
803    /* are 00 then process no more nibbles, because this could be */
804    /* the 'odd' MSD declet and writing any more Units would then */
805    /* overflow the unit array */
806    if (n==0 && !bcd) break;
807
808    nibble=bcd & 0x00f;
809    if (nibble) out=(Unit)(out+nibble*DECPOWERS[cut]);
810    cut++;
811    if (cut==DECDPUN) {*uout=out; if (out) {last=uout; out=0;} uout++; cut=0;}
812    bcd>>=4;
813
814    nibble=bcd & 0x00f;
815    if (nibble) out=(Unit)(out+nibble*DECPOWERS[cut]);
816    cut++;
817    if (cut==DECDPUN) {*uout=out; if (out) {last=uout; out=0;} uout++; cut=0;}
818    } /* n */
819  if (cut!=0) { 			/* some more left over */
820    *uout=out;				/* write out final unit */
821    if (out) last=uout; 		/* and note if non-zero */
822    }
823  #endif
824
825  /* here, last points to the most significant unit with digits; */
826  /* inspect it to get the final digits count -- this is essentially */
827  /* the same code as decGetDigits in decNumber.c */
828  dn->digits=(last-dn->lsu)*DECDPUN+1;	/* floor of digits, plus */
829					/* must be at least 1 digit */
830  #if DECDPUN>1
831  if (*last<10) return; 		/* common odd digit or 0 */
832  dn->digits++; 			/* must be 2 at least */
833  #if DECDPUN>2
834  if (*last<100) return;		/* 10-99 */
835  dn->digits++; 			/* must be 3 at least */
836  #if DECDPUN>3
837  if (*last<1000) return;		/* 100-999 */
838  dn->digits++; 			/* must be 4 at least */
839  #if DECDPUN>4
840  for (pow=&DECPOWERS[4]; *last>=*pow; pow++) dn->digits++;
841  #endif
842  #endif
843  #endif
844  #endif
845  return;
846  } /*decDigitsFromDPD */
847