MySQL 5.6.14 Source Code Document
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
decimal.c
1 /* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
2 
3  This program is free software; you can redistribute it and/or modify
4  it under the terms of the GNU General Public License as published by
5  the Free Software Foundation; version 2 of the License.
6 
7  This program is distributed in the hope that it will be useful,
8  but WITHOUT ANY WARRANTY; without even the implied warranty of
9  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  GNU General Public License for more details.
11 
12  You should have received a copy of the GNU General Public License
13  along with this program; if not, write to the Free Software
14  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */
15 
16 /*
17 =======================================================================
18  NOTE: this library implements SQL standard "exact numeric" type
19  and is not at all generic, but rather intentinally crippled to
20  follow the standard :)
21 =======================================================================
22  Quoting the standard
23  (SQL:2003, Part 2 Foundations, aka ISO/IEC 9075-2:2003)
24 
25 4.4.2 Characteristics of numbers, page 27:
26 
27  An exact numeric type has a precision P and a scale S. P is a positive
28  integer that determines the number of significant digits in a
29  particular radix R, where R is either 2 or 10. S is a non-negative
30  integer. Every value of an exact numeric type of scale S is of the
31  form n*10^{-S}, where n is an integer such that ­-R^P <= n <= R^P.
32 
33  [...]
34 
35  If an assignment of some number would result in a loss of its most
36  significant digit, an exception condition is raised. If least
37  significant digits are lost, implementation-defined rounding or
38  truncating occurs, with no exception condition being raised.
39 
40  [...]
41 
42  Whenever an exact or approximate numeric value is assigned to an exact
43  numeric value site, an approximation of its value that preserves
44  leading significant digits after rounding or truncating is represented
45  in the declared type of the target. The value is converted to have the
46  precision and scale of the target. The choice of whether to truncate
47  or round is implementation-defined.
48 
49  [...]
50 
51  All numeric values between the smallest and the largest value,
52  inclusive, in a given exact numeric type have an approximation
53  obtained by rounding or truncation for that type; it is
54  implementation-defined which other numeric values have such
55  approximations.
56 
57 5.3 <literal>, page 143
58 
59  <exact numeric literal> ::=
60  <unsigned integer> [ <period> [ <unsigned integer> ] ]
61  | <period> <unsigned integer>
62 
63 6.1 <data type>, page 165:
64 
65  19) The <scale> of an <exact numeric type> shall not be greater than
66  the <precision> of the <exact numeric type>.
67 
68  20) For the <exact numeric type>s DECIMAL and NUMERIC:
69 
70  a) The maximum value of <precision> is implementation-defined.
71  <precision> shall not be greater than this value.
72  b) The maximum value of <scale> is implementation-defined. <scale>
73  shall not be greater than this maximum value.
74 
75  21) NUMERIC specifies the data type exact numeric, with the decimal
76  precision and scale specified by the <precision> and <scale>.
77 
78  22) DECIMAL specifies the data type exact numeric, with the decimal
79  scale specified by the <scale> and the implementation-defined
80  decimal precision equal to or greater than the value of the
81  specified <precision>.
82 
83 6.26 <numeric value expression>, page 241:
84 
85  1) If the declared type of both operands of a dyadic arithmetic
86  operator is exact numeric, then the declared type of the result is
87  an implementation-defined exact numeric type, with precision and
88  scale determined as follows:
89 
90  a) Let S1 and S2 be the scale of the first and second operands
91  respectively.
92  b) The precision of the result of addition and subtraction is
93  implementation-defined, and the scale is the maximum of S1 and S2.
94  c) The precision of the result of multiplication is
95  implementation-defined, and the scale is S1 + S2.
96  d) The precision and scale of the result of division are
97  implementation-defined.
98 */
99 
100 #include <my_global.h>
101 #include <m_ctype.h>
102 #include <myisampack.h>
103 #include <my_sys.h> /* for my_alloca */
104 #include <m_string.h>
105 #include <decimal.h>
106 
107 /*
108  Internally decimal numbers are stored base 10^9 (see DIG_BASE below)
109  So one variable of type decimal_digit_t is limited:
110 
111  0 < decimal_digit <= DIG_MAX < DIG_BASE
112 
113  in the struct st_decimal_t:
114 
115  intg is the number of *decimal* digits (NOT number of decimal_digit_t's !)
116  before the point
117  frac - number of decimal digits after the point
118  buf is an array of decimal_digit_t's
119  len is the length of buf (length of allocated space) in decimal_digit_t's,
120  not in bytes
121 */
122 typedef decimal_digit_t dec1;
123 typedef longlong dec2;
124 
125 #define DIG_PER_DEC1 9
126 #define DIG_MASK 100000000
127 #define DIG_BASE 1000000000
128 #define DIG_MAX (DIG_BASE-1)
129 #define DIG_BASE2 ((dec2)DIG_BASE * (dec2)DIG_BASE)
130 #define ROUND_UP(X) (((X)+DIG_PER_DEC1-1)/DIG_PER_DEC1)
131 static const dec1 powers10[DIG_PER_DEC1+1]={
132  1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000};
133 static const int dig2bytes[DIG_PER_DEC1+1]={0, 1, 1, 2, 2, 3, 3, 4, 4, 4};
134 static const dec1 frac_max[DIG_PER_DEC1-1]={
135  900000000, 990000000, 999000000,
136  999900000, 999990000, 999999000,
137  999999900, 999999990 };
138 
139 #ifdef HAVE_purify
140 #define sanity(d) DBUG_ASSERT((d)->len > 0)
141 #else
142 #define sanity(d) DBUG_ASSERT((d)->len >0 && ((d)->buf[0] | \
143  (d)->buf[(d)->len-1] | 1))
144 #endif
145 
146 #define FIX_INTG_FRAC_ERROR(len, intg1, frac1, error) \
147  do \
148  { \
149  if (unlikely(intg1+frac1 > (len))) \
150  { \
151  if (unlikely(intg1 > (len))) \
152  { \
153  intg1=(len); \
154  frac1=0; \
155  error=E_DEC_OVERFLOW; \
156  } \
157  else \
158  { \
159  frac1=(len)-intg1; \
160  error=E_DEC_TRUNCATED; \
161  } \
162  } \
163  else \
164  error=E_DEC_OK; \
165  } while(0)
166 
167 #define ADD(to, from1, from2, carry) /* assume carry <= 1 */ \
168  do \
169  { \
170  dec1 a=(from1)+(from2)+(carry); \
171  DBUG_ASSERT((carry) <= 1); \
172  if (((carry)= a >= DIG_BASE)) /* no division here! */ \
173  a-=DIG_BASE; \
174  (to)=a; \
175  } while(0)
176 
177 #define ADD2(to, from1, from2, carry) \
178  do \
179  { \
180  dec2 a=((dec2)(from1))+(from2)+(carry); \
181  if (((carry)= a >= DIG_BASE)) \
182  a-=DIG_BASE; \
183  if (unlikely(a >= DIG_BASE)) \
184  { \
185  a-=DIG_BASE; \
186  carry++; \
187  } \
188  (to)=(dec1) a; \
189  } while(0)
190 
191 #define SUB(to, from1, from2, carry) /* to=from1-from2 */ \
192  do \
193  { \
194  dec1 a=(from1)-(from2)-(carry); \
195  if (((carry)= a < 0)) \
196  a+=DIG_BASE; \
197  (to)=a; \
198  } while(0)
199 
200 #define SUB2(to, from1, from2, carry) /* to=from1-from2 */ \
201  do \
202  { \
203  dec1 a=(from1)-(from2)-(carry); \
204  if (((carry)= a < 0)) \
205  a+=DIG_BASE; \
206  if (unlikely(a < 0)) \
207  { \
208  a+=DIG_BASE; \
209  carry++; \
210  } \
211  (to)=a; \
212  } while(0)
213 
214 /*
215  Get maximum value for given precision and scale
216 
217  SYNOPSIS
218  max_decimal()
219  precision/scale - see decimal_bin_size() below
220  to - decimal where where the result will be stored
221  to->buf and to->len must be set.
222 */
223 
224 void max_decimal(int precision, int frac, decimal_t *to)
225 {
226  int intpart;
227  dec1 *buf= to->buf;
228  DBUG_ASSERT(precision && precision >= frac);
229 
230  to->sign= 0;
231  if ((intpart= to->intg= (precision - frac)))
232  {
233  int firstdigits= intpart % DIG_PER_DEC1;
234  if (firstdigits)
235  *buf++= powers10[firstdigits] - 1; /* get 9 99 999 ... */
236  for(intpart/= DIG_PER_DEC1; intpart; intpart--)
237  *buf++= DIG_MAX;
238  }
239 
240  if ((to->frac= frac))
241  {
242  int lastdigits= frac % DIG_PER_DEC1;
243  for(frac/= DIG_PER_DEC1; frac; frac--)
244  *buf++= DIG_MAX;
245  if (lastdigits)
246  *buf= frac_max[lastdigits - 1];
247  }
248 }
249 
250 
251 static dec1 *remove_leading_zeroes(const decimal_t *from, int *intg_result)
252 {
253  int intg= from->intg, i;
254  dec1 *buf0= from->buf;
255  i= ((intg - 1) % DIG_PER_DEC1) + 1;
256  while (intg > 0 && *buf0 == 0)
257  {
258  intg-= i;
259  i= DIG_PER_DEC1;
260  buf0++;
261  }
262  if (intg > 0)
263  {
264  for (i= (intg - 1) % DIG_PER_DEC1; *buf0 < powers10[i--]; intg--) ;
265  DBUG_ASSERT(intg > 0);
266  }
267  else
268  intg=0;
269  *intg_result= intg;
270  return buf0;
271 }
272 
273 
274 /*
275  Count actual length of fraction part (without ending zeroes)
276 
277  SYNOPSIS
278  decimal_actual_fraction()
279  from number for processing
280 */
281 
282 int decimal_actual_fraction(decimal_t *from)
283 {
284  int frac= from->frac, i;
285  dec1 *buf0= from->buf + ROUND_UP(from->intg) + ROUND_UP(frac) - 1;
286 
287  if (frac == 0)
288  return 0;
289 
290  i= ((frac - 1) % DIG_PER_DEC1 + 1);
291  while (frac > 0 && *buf0 == 0)
292  {
293  frac-= i;
294  i= DIG_PER_DEC1;
295  buf0--;
296  }
297  if (frac > 0)
298  {
299  for (i= DIG_PER_DEC1 - ((frac - 1) % DIG_PER_DEC1);
300  *buf0 % powers10[i++] == 0;
301  frac--) ;
302  }
303  return frac;
304 }
305 
306 
307 /*
308  Convert decimal to its printable string representation
309 
310  SYNOPSIS
311  decimal2string()
312  from - value to convert
313  to - points to buffer where string representation
314  should be stored
315  *to_len - in: size of to buffer (incl. terminating '\0')
316  out: length of the actually written string (excl. '\0')
317  fixed_precision - 0 if representation can be variable length and
318  fixed_decimals will not be checked in this case.
319  Put number as with fixed point position with this
320  number of digits (sign counted and decimal point is
321  counted)
322  fixed_decimals - number digits after point.
323  filler - character to fill gaps in case of fixed_precision > 0
324 
325  RETURN VALUE
326  E_DEC_OK/E_DEC_TRUNCATED/E_DEC_OVERFLOW
327 */
328 
329 int decimal2string(const decimal_t *from, char *to, int *to_len,
330  int fixed_precision, int fixed_decimals,
331  char filler)
332 {
333  /* {intg_len, frac_len} output widths; {intg, frac} places in input */
334  int len, intg, frac= from->frac, i, intg_len, frac_len, fill;
335  /* number digits before decimal point */
336  int fixed_intg= (fixed_precision ?
337  (fixed_precision - fixed_decimals) : 0);
338  int error=E_DEC_OK;
339  char *s=to;
340  dec1 *buf, *buf0=from->buf, tmp;
341 
342  DBUG_ASSERT(*to_len >= 2+from->sign);
343 
344  /* removing leading zeroes */
345  buf0= remove_leading_zeroes(from, &intg);
346  if (unlikely(intg+frac==0))
347  {
348  intg=1;
349  tmp=0;
350  buf0=&tmp;
351  }
352 
353  if (!(intg_len= fixed_precision ? fixed_intg : intg))
354  intg_len= 1;
355  frac_len= fixed_precision ? fixed_decimals : frac;
356  len= from->sign + intg_len + test(frac) + frac_len;
357  if (fixed_precision)
358  {
359  if (frac > fixed_decimals)
360  {
361  error= E_DEC_TRUNCATED;
362  frac= fixed_decimals;
363  }
364  if (intg > fixed_intg)
365  {
366  error= E_DEC_OVERFLOW;
367  intg= fixed_intg;
368  }
369  }
370  else if (unlikely(len > --*to_len)) /* reserve one byte for \0 */
371  {
372  int j= len - *to_len; /* excess printable chars */
373  error= (frac && j <= frac + 1) ? E_DEC_TRUNCATED : E_DEC_OVERFLOW;
374 
375  /*
376  If we need to cut more places than frac is wide, we'll end up
377  dropping the decimal point as well. Account for this.
378  */
379  if (frac && j >= frac + 1)
380  j--;
381 
382  if (j > frac)
383  {
384  intg_len= intg-= j-frac;
385  frac= 0;
386  }
387  else
388  frac-=j;
389  frac_len= frac;
390  len= from->sign + intg_len + test(frac) + frac_len;
391  }
392  *to_len= len;
393  s[len]= 0;
394 
395  if (from->sign)
396  *s++='-';
397 
398  if (frac)
399  {
400  char *s1= s + intg_len;
401  fill= frac_len - frac;
402  buf=buf0+ROUND_UP(intg);
403  *s1++='.';
404  for (; frac>0; frac-=DIG_PER_DEC1)
405  {
406  dec1 x=*buf++;
407  for (i= MY_MIN(frac, DIG_PER_DEC1); i; i--)
408  {
409  dec1 y=x/DIG_MASK;
410  *s1++='0'+(uchar)y;
411  x-=y*DIG_MASK;
412  x*=10;
413  }
414  }
415  for(; fill > 0; fill--)
416  *s1++=filler;
417  }
418 
419  fill= intg_len - intg;
420  if (intg == 0)
421  fill--; /* symbol 0 before digital point */
422  for(; fill > 0; fill--)
423  *s++=filler;
424  if (intg)
425  {
426  s+=intg;
427  for (buf=buf0+ROUND_UP(intg); intg>0; intg-=DIG_PER_DEC1)
428  {
429  dec1 x=*--buf;
430  for (i= MY_MIN(intg, DIG_PER_DEC1); i; i--)
431  {
432  dec1 y=x/10;
433  *--s='0'+(uchar)(x-y*10);
434  x=y;
435  }
436  }
437  }
438  else
439  *s= '0';
440 
441  return error;
442 }
443 
444 
445 /*
446  Return bounds of decimal digits in the number
447 
448  SYNOPSIS
449  digits_bounds()
450  from - decimal number for processing
451  start_result - index (from 0 ) of first decimal digits will
452  be written by this address
453  end_result - index of position just after last decimal digit
454  be written by this address
455 */
456 
457 static void digits_bounds(decimal_t *from, int *start_result, int *end_result)
458 {
459  int start, stop, i;
460  dec1 *buf_beg= from->buf;
461  dec1 *end= from->buf + ROUND_UP(from->intg) + ROUND_UP(from->frac);
462  dec1 *buf_end= end - 1;
463 
464  /* find non-zero digit from number begining */
465  while (buf_beg < end && *buf_beg == 0)
466  buf_beg++;
467 
468  if (buf_beg >= end)
469  {
470  /* it is zero */
471  *start_result= *end_result= 0;
472  return;
473  }
474 
475  /* find non-zero decimal digit from number begining */
476  if (buf_beg == from->buf && from->intg)
477  {
478  start= DIG_PER_DEC1 - (i= ((from->intg-1) % DIG_PER_DEC1 + 1));
479  i--;
480  }
481  else
482  {
483  i= DIG_PER_DEC1 - 1;
484  start= (int) ((buf_beg - from->buf) * DIG_PER_DEC1);
485  }
486  if (buf_beg < end)
487  for (; *buf_beg < powers10[i--]; start++) ;
488  *start_result= start; /* index of first decimal digit (from 0) */
489 
490  /* find non-zero digit at the end */
491  while (buf_end > buf_beg && *buf_end == 0)
492  buf_end--;
493  /* find non-zero decimal digit from the end */
494  if (buf_end == end - 1 && from->frac)
495  {
496  stop= (int) (((buf_end - from->buf) * DIG_PER_DEC1 +
497  (i= ((from->frac - 1) % DIG_PER_DEC1 + 1))));
498  i= DIG_PER_DEC1 - i + 1;
499  }
500  else
501  {
502  stop= (int) ((buf_end - from->buf + 1) * DIG_PER_DEC1);
503  i= 1;
504  }
505  for (; *buf_end % powers10[i++] == 0; stop--) ;
506  *end_result= stop; /* index of position after last decimal digit (from 0) */
507 }
508 
509 
510 /*
511  Left shift for alignment of data in buffer
512 
513  SYNOPSIS
514  do_mini_left_shift()
515  dec pointer to decimal number which have to be shifted
516  shift number of decimal digits on which it should be shifted
517  beg/end bounds of decimal digits (see digits_bounds())
518 
519  NOTE
520  Result fitting in the buffer should be garanted.
521  'shift' have to be from 1 to DIG_PER_DEC1-1 (inclusive)
522 */
523 
524 void do_mini_left_shift(decimal_t *dec, int shift, int beg, int last)
525 {
526  dec1 *from= dec->buf + ROUND_UP(beg + 1) - 1;
527  dec1 *end= dec->buf + ROUND_UP(last) - 1;
528  int c_shift= DIG_PER_DEC1 - shift;
529  DBUG_ASSERT(from >= dec->buf);
530  DBUG_ASSERT(end < dec->buf + dec->len);
531  if (beg % DIG_PER_DEC1 < shift)
532  *(from - 1)= (*from) / powers10[c_shift];
533  for(; from < end; from++)
534  *from= ((*from % powers10[c_shift]) * powers10[shift] +
535  (*(from + 1)) / powers10[c_shift]);
536  *from= (*from % powers10[c_shift]) * powers10[shift];
537 }
538 
539 
540 /*
541  Right shift for alignment of data in buffer
542 
543  SYNOPSIS
544  do_mini_left_shift()
545  dec pointer to decimal number which have to be shifted
546  shift number of decimal digits on which it should be shifted
547  beg/end bounds of decimal digits (see digits_bounds())
548 
549  NOTE
550  Result fitting in the buffer should be garanted.
551  'shift' have to be from 1 to DIG_PER_DEC1-1 (inclusive)
552 */
553 
554 void do_mini_right_shift(decimal_t *dec, int shift, int beg, int last)
555 {
556  dec1 *from= dec->buf + ROUND_UP(last) - 1;
557  dec1 *end= dec->buf + ROUND_UP(beg + 1) - 1;
558  int c_shift= DIG_PER_DEC1 - shift;
559  DBUG_ASSERT(from < dec->buf + dec->len);
560  DBUG_ASSERT(end >= dec->buf);
561  if (DIG_PER_DEC1 - ((last - 1) % DIG_PER_DEC1 + 1) < shift)
562  *(from + 1)= (*from % powers10[shift]) * powers10[c_shift];
563  for(; from > end; from--)
564  *from= (*from / powers10[shift] +
565  (*(from - 1) % powers10[shift]) * powers10[c_shift]);
566  *from= *from / powers10[shift];
567 }
568 
569 
570 /*
571  Shift of decimal digits in given number (with rounding if it need)
572 
573  SYNOPSIS
574  decimal_shift()
575  dec number to be shifted
576  shift number of decimal positions
577  shift > 0 means shift to left shift
578  shift < 0 meand right shift
579  NOTE
580  In fact it is multipling on 10^shift.
581  RETURN
582  E_DEC_OK OK
583  E_DEC_OVERFLOW operation lead to overflow, number is untoched
584  E_DEC_TRUNCATED number was rounded to fit into buffer
585 */
586 
587 int decimal_shift(decimal_t *dec, int shift)
588 {
589  /* index of first non zero digit (all indexes from 0) */
590  int beg;
591  /* index of position after last decimal digit */
592  int end;
593  /* index of digit position just after point */
594  int point= ROUND_UP(dec->intg) * DIG_PER_DEC1;
595  /* new point position */
596  int new_point= point + shift;
597  /* number of digits in result */
598  int digits_int, digits_frac;
599  /* length of result and new fraction in big digits*/
600  int new_len, new_frac_len;
601  /* return code */
602  int err= E_DEC_OK;
603  int new_front;
604 
605  if (shift == 0)
606  return E_DEC_OK;
607 
608  digits_bounds(dec, &beg, &end);
609 
610  if (beg == end)
611  {
612  decimal_make_zero(dec);
613  return E_DEC_OK;
614  }
615 
616  digits_int= new_point - beg;
617  set_if_bigger(digits_int, 0);
618  digits_frac= end - new_point;
619  set_if_bigger(digits_frac, 0);
620 
621  if ((new_len= ROUND_UP(digits_int) + (new_frac_len= ROUND_UP(digits_frac))) >
622  dec->len)
623  {
624  int lack= new_len - dec->len;
625  int diff;
626 
627  if (new_frac_len < lack)
628  return E_DEC_OVERFLOW; /* lack more then we have in fraction */
629 
630  /* cat off fraction part to allow new number to fit in our buffer */
631  err= E_DEC_TRUNCATED;
632  new_frac_len-= lack;
633  diff= digits_frac - (new_frac_len * DIG_PER_DEC1);
634  /* Make rounding method as parameter? */
635  decimal_round(dec, dec, end - point - diff, HALF_UP);
636  end-= diff;
637  digits_frac= new_frac_len * DIG_PER_DEC1;
638 
639  if (end <= beg)
640  {
641  /*
642  we lost all digits (they will be shifted out of buffer), so we can
643  just return 0
644  */
645  decimal_make_zero(dec);
646  return E_DEC_TRUNCATED;
647  }
648  }
649 
650  if (shift % DIG_PER_DEC1)
651  {
652  int l_mini_shift, r_mini_shift, mini_shift;
653  int do_left;
654  /*
655  Calculate left/right shift to align decimal digits inside our bug
656  digits correctly
657  */
658  if (shift > 0)
659  {
660  l_mini_shift= shift % DIG_PER_DEC1;
661  r_mini_shift= DIG_PER_DEC1 - l_mini_shift;
662  /*
663  It is left shift so prefer left shift, but if we have not place from
664  left, we have to have it from right, because we checked length of
665  result
666  */
667  do_left= l_mini_shift <= beg;
668  DBUG_ASSERT(do_left || (dec->len * DIG_PER_DEC1 - end) >= r_mini_shift);
669  }
670  else
671  {
672  r_mini_shift= (-shift) % DIG_PER_DEC1;
673  l_mini_shift= DIG_PER_DEC1 - r_mini_shift;
674  /* see comment above */
675  do_left= !((dec->len * DIG_PER_DEC1 - end) >= r_mini_shift);
676  DBUG_ASSERT(!do_left || l_mini_shift <= beg);
677  }
678  if (do_left)
679  {
680  do_mini_left_shift(dec, l_mini_shift, beg, end);
681  mini_shift= -l_mini_shift;
682  }
683  else
684  {
685  do_mini_right_shift(dec, r_mini_shift, beg, end);
686  mini_shift= r_mini_shift;
687  }
688  new_point+= mini_shift;
689  /*
690  If number is shifted and correctly aligned in buffer we can
691  finish
692  */
693  if (!(shift+= mini_shift) && (new_point - digits_int) < DIG_PER_DEC1)
694  {
695  dec->intg= digits_int;
696  dec->frac= digits_frac;
697  return err; /* already shifted as it should be */
698  }
699  beg+= mini_shift;
700  end+= mini_shift;
701  }
702 
703  /* if new 'decimal front' is in first digit, we do not need move digits */
704  if ((new_front= (new_point - digits_int)) >= DIG_PER_DEC1 ||
705  new_front < 0)
706  {
707  /* need to move digits */
708  int d_shift;
709  dec1 *to, *barier;
710  if (new_front > 0)
711  {
712  /* move left */
713  d_shift= new_front / DIG_PER_DEC1;
714  to= dec->buf + (ROUND_UP(beg + 1) - 1 - d_shift);
715  barier= dec->buf + (ROUND_UP(end) - 1 - d_shift);
716  DBUG_ASSERT(to >= dec->buf);
717  DBUG_ASSERT(barier + d_shift < dec->buf + dec->len);
718  for(; to <= barier; to++)
719  *to= *(to + d_shift);
720  for(barier+= d_shift; to <= barier; to++)
721  *to= 0;
722  d_shift= -d_shift;
723  }
724  else
725  {
726  /* move right */
727  d_shift= (1 - new_front) / DIG_PER_DEC1;
728  to= dec->buf + ROUND_UP(end) - 1 + d_shift;
729  barier= dec->buf + ROUND_UP(beg + 1) - 1 + d_shift;
730  DBUG_ASSERT(to < dec->buf + dec->len);
731  DBUG_ASSERT(barier - d_shift >= dec->buf);
732  for(; to >= barier; to--)
733  *to= *(to - d_shift);
734  for(barier-= d_shift; to >= barier; to--)
735  *to= 0;
736  }
737  d_shift*= DIG_PER_DEC1;
738  beg+= d_shift;
739  end+= d_shift;
740  new_point+= d_shift;
741  }
742 
743  /*
744  If there are gaps then fill ren with 0.
745 
746  Only one of following 'for' loops will work becouse beg <= end
747  */
748  beg= ROUND_UP(beg + 1) - 1;
749  end= ROUND_UP(end) - 1;
750  DBUG_ASSERT(new_point >= 0);
751 
752  /* We don't want negative new_point below */
753  if (new_point != 0)
754  new_point= ROUND_UP(new_point) - 1;
755 
756  if (new_point > end)
757  {
758  do
759  {
760  dec->buf[new_point]=0;
761  } while (--new_point > end);
762  }
763  else
764  {
765  for (; new_point < beg; new_point++)
766  dec->buf[new_point]= 0;
767  }
768  dec->intg= digits_int;
769  dec->frac= digits_frac;
770  return err;
771 }
772 
773 
774 /*
775  Convert string to decimal
776 
777  SYNOPSIS
778  internal_str2decl()
779  from - value to convert. Doesn't have to be \0 terminated!
780  to - decimal where where the result will be stored
781  to->buf and to->len must be set.
782  end - Pointer to pointer to end of string. Will on return be
783  set to the char after the last used character
784  fixed - use to->intg, to->frac as limits for input number
785 
786  NOTE
787  to->intg and to->frac can be modified even when fixed=1
788  (but only decreased, in this case)
789 
790  RETURN VALUE
791  E_DEC_OK/E_DEC_TRUNCATED/E_DEC_OVERFLOW/E_DEC_BAD_NUM/E_DEC_OOM
792  In case of E_DEC_FATAL_ERROR *to is set to decimal zero
793  (to make error handling easier)
794 */
795 
796 int
797 internal_str2dec(const char *from, decimal_t *to, char **end, my_bool fixed)
798 {
799  const char *s= from, *s1, *endp, *end_of_string= *end;
800  int i, intg, frac, error, intg1, frac1;
801  dec1 x,*buf;
802  sanity(to);
803 
804  error= E_DEC_BAD_NUM; /* In case of bad number */
805  while (s < end_of_string && my_isspace(&my_charset_latin1, *s))
806  s++;
807  if (s == end_of_string)
808  goto fatal_error;
809 
810  if ((to->sign= (*s == '-')))
811  s++;
812  else if (*s == '+')
813  s++;
814 
815  s1=s;
816  while (s < end_of_string && my_isdigit(&my_charset_latin1, *s))
817  s++;
818  intg= (int) (s-s1);
819  if (s < end_of_string && *s=='.')
820  {
821  endp= s+1;
822  while (endp < end_of_string && my_isdigit(&my_charset_latin1, *endp))
823  endp++;
824  frac= (int) (endp - s - 1);
825  }
826  else
827  {
828  frac= 0;
829  endp= s;
830  }
831 
832  *end= (char*) endp;
833 
834  if (frac+intg == 0)
835  goto fatal_error;
836 
837  error= 0;
838  if (fixed)
839  {
840  if (frac > to->frac)
841  {
842  error=E_DEC_TRUNCATED;
843  frac=to->frac;
844  }
845  if (intg > to->intg)
846  {
847  error=E_DEC_OVERFLOW;
848  intg=to->intg;
849  }
850  intg1=ROUND_UP(intg);
851  frac1=ROUND_UP(frac);
852  if (intg1+frac1 > to->len)
853  {
854  error= E_DEC_OOM;
855  goto fatal_error;
856  }
857  }
858  else
859  {
860  intg1=ROUND_UP(intg);
861  frac1=ROUND_UP(frac);
862  FIX_INTG_FRAC_ERROR(to->len, intg1, frac1, error);
863  if (unlikely(error))
864  {
865  frac=frac1*DIG_PER_DEC1;
866  if (error == E_DEC_OVERFLOW)
867  intg=intg1*DIG_PER_DEC1;
868  }
869  }
870  /* Error is guranteed to be set here */
871  to->intg=intg;
872  to->frac=frac;
873 
874  buf=to->buf+intg1;
875  s1=s;
876 
877  for (x=0, i=0; intg; intg--)
878  {
879  x+= (*--s - '0')*powers10[i];
880 
881  if (unlikely(++i == DIG_PER_DEC1))
882  {
883  *--buf=x;
884  x=0;
885  i=0;
886  }
887  }
888  if (i)
889  *--buf=x;
890 
891  buf=to->buf+intg1;
892  for (x=0, i=0; frac; frac--)
893  {
894  x= (*++s1 - '0') + x*10;
895 
896  if (unlikely(++i == DIG_PER_DEC1))
897  {
898  *buf++=x;
899  x=0;
900  i=0;
901  }
902  }
903  if (i)
904  *buf=x*powers10[DIG_PER_DEC1-i];
905 
906  /* Handle exponent */
907  if (endp+1 < end_of_string && (*endp == 'e' || *endp == 'E'))
908  {
909  int str_error;
910  longlong exponent= my_strtoll10(endp+1, (char**) &end_of_string,
911  &str_error);
912 
913  if (end_of_string != endp +1) /* If at least one digit */
914  {
915  *end= (char*) end_of_string;
916  if (str_error > 0)
917  {
918  error= E_DEC_BAD_NUM;
919  goto fatal_error;
920  }
921  if (exponent > INT_MAX/2 || (str_error == 0 && exponent < 0))
922  {
923  error= E_DEC_OVERFLOW;
924  goto fatal_error;
925  }
926  if (exponent < INT_MIN/2 && error != E_DEC_OVERFLOW)
927  {
928  error= E_DEC_TRUNCATED;
929  goto fatal_error;
930  }
931  if (error != E_DEC_OVERFLOW)
932  error= decimal_shift(to, (int) exponent);
933  }
934  }
935  return error;
936 
937 fatal_error:
938  decimal_make_zero(to);
939  return error;
940 }
941 
942 
943 /*
944  Convert decimal to double
945 
946  SYNOPSIS
947  decimal2double()
948  from - value to convert
949  to - result will be stored there
950 
951  RETURN VALUE
952  E_DEC_OK/E_DEC_OVERFLOW/E_DEC_TRUNCATED
953 */
954 
955 int decimal2double(const decimal_t *from, double *to)
956 {
957  char strbuf[FLOATING_POINT_BUFFER], *end;
958  int len= sizeof(strbuf);
959  int rc, error;
960 
961  rc = decimal2string(from, strbuf, &len, 0, 0, 0);
962  end= strbuf + len;
963 
964  DBUG_PRINT("info", ("interm.: %s", strbuf));
965 
966  *to= my_strtod(strbuf, &end, &error);
967 
968  DBUG_PRINT("info", ("result: %f", *to));
969 
970  return (rc != E_DEC_OK) ? rc : (error ? E_DEC_OVERFLOW : E_DEC_OK);
971 }
972 
973 /*
974  Convert double to decimal
975 
976  SYNOPSIS
977  double2decimal()
978  from - value to convert
979  to - result will be stored there
980 
981  RETURN VALUE
982  E_DEC_OK/E_DEC_OVERFLOW/E_DEC_TRUNCATED
983 */
984 
985 int double2decimal(double from, decimal_t *to)
986 {
987  char buff[FLOATING_POINT_BUFFER], *end;
988  int res;
989  DBUG_ENTER("double2decimal");
990  end= buff + my_gcvt(from, MY_GCVT_ARG_DOUBLE, sizeof(buff) - 1, buff, NULL);
991  res= string2decimal(buff, to, &end);
992  DBUG_PRINT("exit", ("res: %d", res));
993  DBUG_RETURN(res);
994 }
995 
996 
997 static int ull2dec(ulonglong from, decimal_t *to)
998 {
999  int intg1, error=E_DEC_OK;
1000  ulonglong x=from;
1001  dec1 *buf;
1002 
1003  sanity(to);
1004 
1005  for (intg1=1; from >= DIG_BASE; intg1++, from/=DIG_BASE) ;
1006  if (unlikely(intg1 > to->len))
1007  {
1008  intg1=to->len;
1009  error=E_DEC_OVERFLOW;
1010  }
1011  to->frac=0;
1012  to->intg=intg1*DIG_PER_DEC1;
1013 
1014  for (buf=to->buf+intg1; intg1; intg1--)
1015  {
1016  ulonglong y=x/DIG_BASE;
1017  *--buf=(dec1)(x-y*DIG_BASE);
1018  x=y;
1019  }
1020  return error;
1021 }
1022 
1023 int ulonglong2decimal(ulonglong from, decimal_t *to)
1024 {
1025  to->sign=0;
1026  return ull2dec(from, to);
1027 }
1028 
1029 int longlong2decimal(longlong from, decimal_t *to)
1030 {
1031  if ((to->sign= from < 0))
1032  return ull2dec(-from, to);
1033  return ull2dec(from, to);
1034 }
1035 
1036 int decimal2ulonglong(decimal_t *from, ulonglong *to)
1037 {
1038  dec1 *buf=from->buf;
1039  ulonglong x=0;
1040  int intg, frac;
1041 
1042  if (from->sign)
1043  {
1044  *to=ULL(0);
1045  return E_DEC_OVERFLOW;
1046  }
1047 
1048  for (intg=from->intg; intg > 0; intg-=DIG_PER_DEC1)
1049  {
1050  ulonglong y=x;
1051  x=x*DIG_BASE + *buf++;
1052  if (unlikely(y > ((ulonglong) ULONGLONG_MAX/DIG_BASE) || x < y))
1053  {
1054  *to=ULONGLONG_MAX;
1055  return E_DEC_OVERFLOW;
1056  }
1057  }
1058  *to=x;
1059  for (frac=from->frac; unlikely(frac > 0); frac-=DIG_PER_DEC1)
1060  if (*buf++)
1061  return E_DEC_TRUNCATED;
1062  return E_DEC_OK;
1063 }
1064 
1065 int decimal2longlong(decimal_t *from, longlong *to)
1066 {
1067  dec1 *buf=from->buf;
1068  longlong x=0;
1069  int intg, frac;
1070 
1071  for (intg=from->intg; intg > 0; intg-=DIG_PER_DEC1)
1072  {
1073  longlong y=x;
1074  /*
1075  Attention: trick!
1076  we're calculating -|from| instead of |from| here
1077  because |LONGLONG_MIN| > LONGLONG_MAX
1078  so we can convert -9223372036854775808 correctly
1079  */
1080  x=x*DIG_BASE - *buf++;
1081  if (unlikely(y < (LONGLONG_MIN/DIG_BASE) || x > y))
1082  {
1083  /*
1084  the decimal is bigger than any possible integer
1085  return border integer depending on the sign
1086  */
1087  *to= from->sign ? LONGLONG_MIN : LONGLONG_MAX;
1088  return E_DEC_OVERFLOW;
1089  }
1090  }
1091  /* boundary case: 9223372036854775808 */
1092  if (unlikely(from->sign==0 && x == LONGLONG_MIN))
1093  {
1094  *to= LONGLONG_MAX;
1095  return E_DEC_OVERFLOW;
1096  }
1097 
1098  *to=from->sign ? x : -x;
1099  for (frac=from->frac; unlikely(frac > 0); frac-=DIG_PER_DEC1)
1100  if (*buf++)
1101  return E_DEC_TRUNCATED;
1102  return E_DEC_OK;
1103 }
1104 
1105 
1106 #define LLDIV_MIN -1000000000000000000LL
1107 #define LLDIV_MAX 1000000000000000000LL
1108 
1115 int decimal2lldiv_t(const decimal_t *from, lldiv_t *to)
1116 {
1117  int int_part= ROUND_UP(from->intg);
1118  int frac_part= ROUND_UP(from->frac);
1119  if (int_part > 2)
1120  {
1121  to->rem= 0;
1122  to->quot= from->sign ? LLDIV_MIN : LLDIV_MAX;
1123  return E_DEC_OVERFLOW;
1124  }
1125  if (int_part == 2)
1126  to->quot= ((longlong) from->buf[0]) * DIG_BASE + from->buf[1];
1127  else if (int_part == 1)
1128  to->quot= from->buf[0];
1129  else
1130  to->quot= 0;
1131  to->rem= frac_part ? from->buf[int_part] : 0;
1132  if (from->sign)
1133  {
1134  to->quot= -to->quot;
1135  to->rem= -to->rem;
1136  }
1137  return 0;
1138 }
1139 
1140 
1152 int double2lldiv_t(double nr, lldiv_t *lld)
1153 {
1154  if (nr > LLDIV_MAX)
1155  {
1156  lld->quot= LLDIV_MAX;
1157  lld->rem= 0;
1158  return E_DEC_OVERFLOW;
1159  }
1160  else if (nr < LLDIV_MIN)
1161  {
1162  lld->quot= LLDIV_MIN;
1163  lld->rem= 0;
1164  return E_DEC_OVERFLOW;
1165  }
1166  /* Truncate fractional part toward zero and store into "quot" */
1167  lld->quot= (longlong) (nr > 0 ? floor(nr) : ceil(nr));
1168  /* Multiply reminder to 10^9 and store into "rem" */
1169  lld->rem= (longlong) rint((nr - (double) lld->quot) * 1000000000);
1170  /*
1171  Sometimes the expression "(double) 0.999999999xxx * (double) 10e9"
1172  gives 1,000,000,000 instead of 999,999,999 due to lack of double precision.
1173  The callers do not expect lld->rem to be greater than 999,999,999.
1174  Let's catch this corner case and put the "nanounit" (e.g. nanosecond)
1175  value in ldd->rem back into the valid range.
1176  */
1177  if (lld->rem > 999999999LL)
1178  lld->rem= 999999999LL;
1179  else if (lld->rem < -999999999LL)
1180  lld->rem= -999999999LL;
1181  return E_DEC_OK;
1182 }
1183 
1184 
1185 
1186 /*
1187  Convert decimal to its binary fixed-length representation
1188  two representations of the same length can be compared with memcmp
1189  with the correct -1/0/+1 result
1190 
1191  SYNOPSIS
1192  decimal2bin()
1193  from - value to convert
1194  to - points to buffer where string representation should be stored
1195  precision/scale - see decimal_bin_size() below
1196 
1197  NOTE
1198  the buffer is assumed to be of the size decimal_bin_size(precision, scale)
1199 
1200  RETURN VALUE
1201  E_DEC_OK/E_DEC_TRUNCATED/E_DEC_OVERFLOW
1202 
1203  DESCRIPTION
1204  for storage decimal numbers are converted to the "binary" format.
1205 
1206  This format has the following properties:
1207  1. length of the binary representation depends on the {precision, scale}
1208  as provided by the caller and NOT on the intg/frac of the decimal to
1209  convert.
1210  2. binary representations of the same {precision, scale} can be compared
1211  with memcmp - with the same result as decimal_cmp() of the original
1212  decimals (not taking into account possible precision loss during
1213  conversion).
1214 
1215  This binary format is as follows:
1216  1. First the number is converted to have a requested precision and scale.
1217  2. Every full DIG_PER_DEC1 digits of intg part are stored in 4 bytes
1218  as is
1219  3. The first intg % DIG_PER_DEC1 digits are stored in the reduced
1220  number of bytes (enough bytes to store this number of digits -
1221  see dig2bytes)
1222  4. same for frac - full decimal_digit_t's are stored as is,
1223  the last frac % DIG_PER_DEC1 digits - in the reduced number of bytes.
1224  5. If the number is negative - every byte is inversed.
1225  5. The very first bit of the resulting byte array is inverted (because
1226  memcmp compares unsigned bytes, see property 2 above)
1227 
1228  Example:
1229 
1230  1234567890.1234
1231 
1232  internally is represented as 3 decimal_digit_t's
1233 
1234  1 234567890 123400000
1235 
1236  (assuming we want a binary representation with precision=14, scale=4)
1237  in hex it's
1238 
1239  00-00-00-01 0D-FB-38-D2 07-5A-EF-40
1240 
1241  now, middle decimal_digit_t is full - it stores 9 decimal digits. It goes
1242  into binary representation as is:
1243 
1244 
1245  ........... 0D-FB-38-D2 ............
1246 
1247  First decimal_digit_t has only one decimal digit. We can store one digit in
1248  one byte, no need to waste four:
1249 
1250  01 0D-FB-38-D2 ............
1251 
1252  now, last digit. It's 123400000. We can store 1234 in two bytes:
1253 
1254  01 0D-FB-38-D2 04-D2
1255 
1256  So, we've packed 12 bytes number in 7 bytes.
1257  And now we invert the highest bit to get the final result:
1258 
1259  81 0D FB 38 D2 04 D2
1260 
1261  And for -1234567890.1234 it would be
1262 
1263  7E F2 04 C7 2D FB 2D
1264 */
1265 int decimal2bin(decimal_t *from, uchar *to, int precision, int frac)
1266 {
1267  dec1 mask=from->sign ? -1 : 0, *buf1=from->buf, *stop1;
1268  int error=E_DEC_OK, intg=precision-frac,
1269  isize1, intg1, intg1x, from_intg,
1270  intg0=intg/DIG_PER_DEC1,
1271  frac0=frac/DIG_PER_DEC1,
1272  intg0x=intg-intg0*DIG_PER_DEC1,
1273  frac0x=frac-frac0*DIG_PER_DEC1,
1274  frac1=from->frac/DIG_PER_DEC1,
1275  frac1x=from->frac-frac1*DIG_PER_DEC1,
1276  isize0=intg0*sizeof(dec1)+dig2bytes[intg0x],
1277  fsize0=frac0*sizeof(dec1)+dig2bytes[frac0x],
1278  fsize1=frac1*sizeof(dec1)+dig2bytes[frac1x];
1279  const int orig_isize0= isize0;
1280  const int orig_fsize0= fsize0;
1281  uchar *orig_to= to;
1282 
1283  buf1= remove_leading_zeroes(from, &from_intg);
1284 
1285  if (unlikely(from_intg+fsize1==0))
1286  {
1287  mask=0; /* just in case */
1288  intg=1;
1289  buf1=&mask;
1290  }
1291 
1292  intg1=from_intg/DIG_PER_DEC1;
1293  intg1x=from_intg-intg1*DIG_PER_DEC1;
1294  isize1=intg1*sizeof(dec1)+dig2bytes[intg1x];
1295 
1296  if (intg < from_intg)
1297  {
1298  buf1+=intg1-intg0+(intg1x>0)-(intg0x>0);
1299  intg1=intg0; intg1x=intg0x;
1300  error=E_DEC_OVERFLOW;
1301  }
1302  else if (isize0 > isize1)
1303  {
1304  while (isize0-- > isize1)
1305  *to++= (char)mask;
1306  }
1307  if (fsize0 < fsize1)
1308  {
1309  frac1=frac0; frac1x=frac0x;
1310  error=E_DEC_TRUNCATED;
1311  }
1312  else if (fsize0 > fsize1 && frac1x)
1313  {
1314  if (frac0 == frac1)
1315  {
1316  frac1x=frac0x;
1317  fsize0= fsize1;
1318  }
1319  else
1320  {
1321  frac1++;
1322  frac1x=0;
1323  }
1324  }
1325 
1326  /* intg1x part */
1327  if (intg1x)
1328  {
1329  int i=dig2bytes[intg1x];
1330  dec1 x=(*buf1++ % powers10[intg1x]) ^ mask;
1331  switch (i)
1332  {
1333  case 1: mi_int1store(to, x); break;
1334  case 2: mi_int2store(to, x); break;
1335  case 3: mi_int3store(to, x); break;
1336  case 4: mi_int4store(to, x); break;
1337  default: DBUG_ASSERT(0);
1338  }
1339  to+=i;
1340  }
1341 
1342  /* intg1+frac1 part */
1343  for (stop1=buf1+intg1+frac1; buf1 < stop1; to+=sizeof(dec1))
1344  {
1345  dec1 x=*buf1++ ^ mask;
1346  DBUG_ASSERT(sizeof(dec1) == 4);
1347  mi_int4store(to, x);
1348  }
1349 
1350  /* frac1x part */
1351  if (frac1x)
1352  {
1353  dec1 x;
1354  int i=dig2bytes[frac1x],
1355  lim=(frac1 < frac0 ? DIG_PER_DEC1 : frac0x);
1356  while (frac1x < lim && dig2bytes[frac1x] == i)
1357  frac1x++;
1358  x=(*buf1 / powers10[DIG_PER_DEC1 - frac1x]) ^ mask;
1359  switch (i)
1360  {
1361  case 1: mi_int1store(to, x); break;
1362  case 2: mi_int2store(to, x); break;
1363  case 3: mi_int3store(to, x); break;
1364  case 4: mi_int4store(to, x); break;
1365  default: DBUG_ASSERT(0);
1366  }
1367  to+=i;
1368  }
1369  if (fsize0 > fsize1)
1370  {
1371  uchar *to_end= orig_to + orig_fsize0 + orig_isize0;
1372 
1373  while (fsize0-- > fsize1 && to < to_end)
1374  *to++= (uchar)mask;
1375  }
1376  orig_to[0]^= 0x80;
1377 
1378  /* Check that we have written the whole decimal and nothing more */
1379  DBUG_ASSERT(to == orig_to + orig_fsize0 + orig_isize0);
1380  return error;
1381 }
1382 
1383 /*
1384  Restores decimal from its binary fixed-length representation
1385 
1386  SYNOPSIS
1387  bin2decimal()
1388  from - value to convert
1389  to - result
1390  precision/scale - see decimal_bin_size() below
1391 
1392  NOTE
1393  see decimal2bin()
1394  the buffer is assumed to be of the size decimal_bin_size(precision, scale)
1395 
1396  RETURN VALUE
1397  E_DEC_OK/E_DEC_TRUNCATED/E_DEC_OVERFLOW
1398 */
1399 
1400 int bin2decimal(const uchar *from, decimal_t *to, int precision, int scale)
1401 {
1402  int error=E_DEC_OK, intg=precision-scale,
1403  intg0=intg/DIG_PER_DEC1, frac0=scale/DIG_PER_DEC1,
1404  intg0x=intg-intg0*DIG_PER_DEC1, frac0x=scale-frac0*DIG_PER_DEC1,
1405  intg1=intg0+(intg0x>0), frac1=frac0+(frac0x>0);
1406  dec1 *buf=to->buf, mask=(*from & 0x80) ? 0 : -1;
1407  const uchar *stop;
1408  uchar *d_copy;
1409  int bin_size= decimal_bin_size(precision, scale);
1410 
1411  sanity(to);
1412  d_copy= (uchar*) my_alloca(bin_size);
1413  memcpy(d_copy, from, bin_size);
1414  d_copy[0]^= 0x80;
1415  from= d_copy;
1416 
1417  FIX_INTG_FRAC_ERROR(to->len, intg1, frac1, error);
1418  if (unlikely(error))
1419  {
1420  if (intg1 < intg0+(intg0x>0))
1421  {
1422  from+=dig2bytes[intg0x]+sizeof(dec1)*(intg0-intg1);
1423  frac0=frac0x=intg0x=0;
1424  intg0=intg1;
1425  }
1426  else
1427  {
1428  frac0x=0;
1429  frac0=frac1;
1430  }
1431  }
1432 
1433  to->sign=(mask != 0);
1434  to->intg=intg0*DIG_PER_DEC1+intg0x;
1435  to->frac=frac0*DIG_PER_DEC1+frac0x;
1436 
1437  if (intg0x)
1438  {
1439  int i=dig2bytes[intg0x];
1440  dec1 UNINIT_VAR(x);
1441  switch (i)
1442  {
1443  case 1: x=mi_sint1korr(from); break;
1444  case 2: x=mi_sint2korr(from); break;
1445  case 3: x=mi_sint3korr(from); break;
1446  case 4: x=mi_sint4korr(from); break;
1447  default: DBUG_ASSERT(0);
1448  }
1449  from+=i;
1450  *buf=x ^ mask;
1451  if (((ulonglong)*buf) >= (ulonglong) powers10[intg0x+1])
1452  goto err;
1453  if (buf > to->buf || *buf != 0)
1454  buf++;
1455  else
1456  to->intg-=intg0x;
1457  }
1458  for (stop=from+intg0*sizeof(dec1); from < stop; from+=sizeof(dec1))
1459  {
1460  DBUG_ASSERT(sizeof(dec1) == 4);
1461  *buf=mi_sint4korr(from) ^ mask;
1462  if (((uint32)*buf) > DIG_MAX)
1463  goto err;
1464  if (buf > to->buf || *buf != 0)
1465  buf++;
1466  else
1467  to->intg-=DIG_PER_DEC1;
1468  }
1469  DBUG_ASSERT(to->intg >=0);
1470  for (stop=from+frac0*sizeof(dec1); from < stop; from+=sizeof(dec1))
1471  {
1472  DBUG_ASSERT(sizeof(dec1) == 4);
1473  *buf=mi_sint4korr(from) ^ mask;
1474  if (((uint32)*buf) > DIG_MAX)
1475  goto err;
1476  buf++;
1477  }
1478  if (frac0x)
1479  {
1480  int i=dig2bytes[frac0x];
1481  dec1 UNINIT_VAR(x);
1482  switch (i)
1483  {
1484  case 1: x=mi_sint1korr(from); break;
1485  case 2: x=mi_sint2korr(from); break;
1486  case 3: x=mi_sint3korr(from); break;
1487  case 4: x=mi_sint4korr(from); break;
1488  default: DBUG_ASSERT(0);
1489  }
1490  *buf=(x ^ mask) * powers10[DIG_PER_DEC1 - frac0x];
1491  if (((uint32)*buf) > DIG_MAX)
1492  goto err;
1493  buf++;
1494  }
1495  my_afree(d_copy);
1496 
1497  /*
1498  No digits? We have read the number zero, of unspecified precision.
1499  Make it a proper zero, with non-zero precision.
1500  */
1501  if (to->intg == 0 && to->frac == 0)
1502  decimal_make_zero(to);
1503  return error;
1504 
1505 err:
1506  my_afree(d_copy);
1507  decimal_make_zero(to);
1508  return(E_DEC_BAD_NUM);
1509 }
1510 
1511 /*
1512  Returns the size of array to hold a decimal with given precision and scale
1513 
1514  RETURN VALUE
1515  size in dec1
1516  (multiply by sizeof(dec1) to get the size if bytes)
1517 */
1518 
1519 int decimal_size(int precision, int scale)
1520 {
1521  DBUG_ASSERT(scale >= 0 && precision > 0 && scale <= precision);
1522  return ROUND_UP(precision-scale)+ROUND_UP(scale);
1523 }
1524 
1525 /*
1526  Returns the size of array to hold a binary representation of a decimal
1527 
1528  RETURN VALUE
1529  size in bytes
1530 */
1531 
1532 int decimal_bin_size(int precision, int scale)
1533 {
1534  int intg=precision-scale,
1535  intg0=intg/DIG_PER_DEC1, frac0=scale/DIG_PER_DEC1,
1536  intg0x=intg-intg0*DIG_PER_DEC1, frac0x=scale-frac0*DIG_PER_DEC1;
1537 
1538  DBUG_ASSERT(scale >= 0 && precision > 0 && scale <= precision);
1539  return intg0*sizeof(dec1)+dig2bytes[intg0x]+
1540  frac0*sizeof(dec1)+dig2bytes[frac0x];
1541 }
1542 
1543 /*
1544  Rounds the decimal to "scale" digits
1545 
1546  SYNOPSIS
1547  decimal_round()
1548  from - decimal to round,
1549  to - result buffer. from==to is allowed
1550  scale - to what position to round. can be negative!
1551  mode - round to nearest even or truncate
1552 
1553  NOTES
1554  scale can be negative !
1555  one TRUNCATED error (line XXX below) isn't treated very logical :(
1556 
1557  RETURN VALUE
1558  E_DEC_OK/E_DEC_TRUNCATED
1559 */
1560 
1561 int
1562 decimal_round(const decimal_t *from, decimal_t *to, int scale,
1563  decimal_round_mode mode)
1564 {
1565  int frac0=scale>0 ? ROUND_UP(scale) : (scale + 1)/DIG_PER_DEC1,
1566  frac1=ROUND_UP(from->frac), UNINIT_VAR(round_digit),
1567  intg0=ROUND_UP(from->intg), error=E_DEC_OK, len=to->len;
1568 
1569  dec1 *buf0=from->buf, *buf1=to->buf, x, y, carry=0;
1570  int first_dig;
1571 
1572  sanity(to);
1573 
1574  switch (mode) {
1575  case HALF_UP:
1576  case HALF_EVEN: round_digit=5; break;
1577  case CEILING: round_digit= from->sign ? 10 : 0; break;
1578  case FLOOR: round_digit= from->sign ? 0 : 10; break;
1579  case TRUNCATE: round_digit=10; break;
1580  default: DBUG_ASSERT(0);
1581  }
1582 
1583  /*
1584  For my_decimal we always use len == DECIMAL_BUFF_LENGTH == 9
1585  For internal testing here (ifdef MAIN) we always use len == 100/4
1586  */
1587  DBUG_ASSERT(from->len == to->len);
1588 
1589  if (unlikely(frac0+intg0 > len))
1590  {
1591  frac0=len-intg0;
1592  scale=frac0*DIG_PER_DEC1;
1593  error=E_DEC_TRUNCATED;
1594  }
1595 
1596  if (scale+from->intg < 0)
1597  {
1598  decimal_make_zero(to);
1599  return E_DEC_OK;
1600  }
1601 
1602  if (to != from)
1603  {
1604  dec1 *p0= buf0 + intg0 + MY_MAX(frac1, frac0);
1605  dec1 *p1= buf1 + intg0 + MY_MAX(frac1, frac0);
1606 
1607  DBUG_ASSERT(p0 - buf0 <= len);
1608  DBUG_ASSERT(p1 - buf1 <= len);
1609 
1610  while (buf0 < p0)
1611  *(--p1) = *(--p0);
1612 
1613  buf0=to->buf;
1614  buf1=to->buf;
1615  to->sign=from->sign;
1616  to->intg= MY_MIN(intg0, len) * DIG_PER_DEC1;
1617  }
1618 
1619  if (frac0 > frac1)
1620  {
1621  buf1+=intg0+frac1;
1622  while (frac0-- > frac1)
1623  *buf1++=0;
1624  goto done;
1625  }
1626 
1627  if (scale >= from->frac)
1628  goto done; /* nothing to do */
1629 
1630  buf0+=intg0+frac0-1;
1631  buf1+=intg0+frac0-1;
1632  if (scale == frac0*DIG_PER_DEC1)
1633  {
1634  int do_inc= FALSE;
1635  DBUG_ASSERT(frac0+intg0 >= 0);
1636  switch (round_digit) {
1637  case 0:
1638  {
1639  dec1 *p0= buf0 + (frac1-frac0);
1640  for (; p0 > buf0; p0--)
1641  {
1642  if (*p0)
1643  {
1644  do_inc= TRUE;
1645  break;
1646  }
1647  }
1648  break;
1649  }
1650  case 5:
1651  {
1652  x= buf0[1]/DIG_MASK;
1653  do_inc= (x>5) || ((x == 5) &&
1654  (mode == HALF_UP || (frac0+intg0 > 0 && *buf0 & 1)));
1655  break;
1656  }
1657  default:
1658  break;
1659  }
1660  if (do_inc)
1661  {
1662  if (frac0+intg0>0)
1663  (*buf1)++;
1664  else
1665  *(++buf1)=DIG_BASE;
1666  }
1667  else if (frac0+intg0==0)
1668  {
1669  decimal_make_zero(to);
1670  return E_DEC_OK;
1671  }
1672  }
1673  else
1674  {
1675  /* TODO - fix this code as it won't work for CEILING mode */
1676  int pos=frac0*DIG_PER_DEC1-scale-1;
1677  DBUG_ASSERT(frac0+intg0 > 0);
1678  x=*buf1 / powers10[pos];
1679  y=x % 10;
1680  if (y > round_digit ||
1681  (round_digit == 5 && y == 5 && (mode == HALF_UP || (x/10) & 1)))
1682  x+=10;
1683  *buf1=powers10[pos]*(x-y);
1684  }
1685  /*
1686  In case we're rounding e.g. 1.5e9 to 2.0e9, the decimal_digit_t's inside
1687  the buffer are as follows.
1688 
1689  Before <1, 5e8>
1690  After <2, 5e8>
1691 
1692  Hence we need to set the 2nd field to 0.
1693  The same holds if we round 1.5e-9 to 2e-9.
1694  */
1695  if (frac0 < frac1)
1696  {
1697  dec1 *buf= to->buf + ((scale == 0 && intg0 == 0) ? 1 : intg0 + frac0);
1698  dec1 *end= to->buf + len;
1699 
1700  while (buf < end)
1701  *buf++=0;
1702  }
1703  if (*buf1 >= DIG_BASE)
1704  {
1705  carry=1;
1706  *buf1-=DIG_BASE;
1707  while (carry && --buf1 >= to->buf)
1708  ADD(*buf1, *buf1, 0, carry);
1709  if (unlikely(carry))
1710  {
1711  /* shifting the number to create space for new digit */
1712  if (frac0+intg0 >= len)
1713  {
1714  frac0--;
1715  scale=frac0*DIG_PER_DEC1;
1716  error=E_DEC_TRUNCATED; /* XXX */
1717  }
1718  for (buf1=to->buf + intg0 + MY_MAX(frac0, 0); buf1 > to->buf; buf1--)
1719  {
1720  /* Avoid out-of-bounds write. */
1721  if (buf1 < to->buf + len)
1722  buf1[0]=buf1[-1];
1723  else
1724  error= E_DEC_OVERFLOW;
1725  }
1726  *buf1=1;
1727  /* We cannot have more than 9 * 9 = 81 digits. */
1728  if (to->intg < len * DIG_PER_DEC1)
1729  to->intg++;
1730  else
1731  error= E_DEC_OVERFLOW;
1732  }
1733  }
1734  else
1735  {
1736  for (;;)
1737  {
1738  if (likely(*buf1))
1739  break;
1740  if (buf1-- == to->buf)
1741  {
1742  /* making 'zero' with the proper scale */
1743  dec1 *p0= to->buf + frac0 + 1;
1744  to->intg=1;
1745  to->frac= MY_MAX(scale, 0);
1746  to->sign= 0;
1747  for (buf1= to->buf; buf1<p0; buf1++)
1748  *buf1= 0;
1749  return E_DEC_OK;
1750  }
1751  }
1752  }
1753 
1754  /* Here we check 999.9 -> 1000 case when we need to increase intg */
1755  first_dig= to->intg % DIG_PER_DEC1;
1756  if (first_dig && (*buf1 >= powers10[first_dig]))
1757  to->intg++;
1758 
1759  if (scale<0)
1760  scale=0;
1761 
1762 done:
1763  DBUG_ASSERT(to->intg <= (len * DIG_PER_DEC1));
1764  to->frac=scale;
1765  return error;
1766 }
1767 
1768 /*
1769  Returns the size of the result of the operation
1770 
1771  SYNOPSIS
1772  decimal_result_size()
1773  from1 - operand of the unary operation or first operand of the
1774  binary operation
1775  from2 - second operand of the binary operation
1776  op - operation. one char '+', '-', '*', '/' are allowed
1777  others may be added later
1778  param - extra param to the operation. unused for '+', '-', '*'
1779  scale increment for '/'
1780 
1781  NOTE
1782  returned valued may be larger than the actual buffer requred
1783  in the operation, as decimal_result_size, by design, operates on
1784  precision/scale values only and not on the actual decimal number
1785 
1786  RETURN VALUE
1787  size of to->buf array in dec1 elements. to get size in bytes
1788  multiply by sizeof(dec1)
1789 */
1790 
1791 int decimal_result_size(decimal_t *from1, decimal_t *from2, char op, int param)
1792 {
1793  switch (op) {
1794  case '-':
1795  return ROUND_UP(MY_MAX(from1->intg, from2->intg)) +
1796  ROUND_UP(MY_MAX(from1->frac, from2->frac));
1797  case '+':
1798  return ROUND_UP(MY_MAX(from1->intg, from2->intg)+1) +
1799  ROUND_UP(MY_MAX(from1->frac, from2->frac));
1800  case '*':
1801  return ROUND_UP(from1->intg+from2->intg)+
1802  ROUND_UP(from1->frac)+ROUND_UP(from2->frac);
1803  case '/':
1804  return ROUND_UP(from1->intg+from2->intg+1+from1->frac+from2->frac+param);
1805  default: DBUG_ASSERT(0);
1806  }
1807  return -1; /* shut up the warning */
1808 }
1809 
1810 static int do_add(const decimal_t *from1, const decimal_t *from2, decimal_t *to)
1811 {
1812  int intg1=ROUND_UP(from1->intg), intg2=ROUND_UP(from2->intg),
1813  frac1=ROUND_UP(from1->frac), frac2=ROUND_UP(from2->frac),
1814  frac0= MY_MAX(frac1, frac2), intg0= MY_MAX(intg1, intg2), error;
1815  dec1 *buf1, *buf2, *buf0, *stop, *stop2, x, carry;
1816 
1817  sanity(to);
1818 
1819  /* is there a need for extra word because of carry ? */
1820  x=intg1 > intg2 ? from1->buf[0] :
1821  intg2 > intg1 ? from2->buf[0] :
1822  from1->buf[0] + from2->buf[0] ;
1823  if (unlikely(x > DIG_MAX-1)) /* yes, there is */
1824  {
1825  intg0++;
1826  to->buf[0]=0; /* safety */
1827  }
1828 
1829  FIX_INTG_FRAC_ERROR(to->len, intg0, frac0, error);
1830  if (unlikely(error == E_DEC_OVERFLOW))
1831  {
1832  max_decimal(to->len * DIG_PER_DEC1, 0, to);
1833  return error;
1834  }
1835 
1836  buf0=to->buf+intg0+frac0;
1837 
1838  to->sign=from1->sign;
1839  to->frac= MY_MAX(from1->frac, from2->frac);
1840  to->intg=intg0*DIG_PER_DEC1;
1841  if (unlikely(error))
1842  {
1843  set_if_smaller(to->frac, frac0*DIG_PER_DEC1);
1844  set_if_smaller(frac1, frac0);
1845  set_if_smaller(frac2, frac0);
1846  set_if_smaller(intg1, intg0);
1847  set_if_smaller(intg2, intg0);
1848  }
1849 
1850  /* part 1 - max(frac) ... min (frac) */
1851  if (frac1 > frac2)
1852  {
1853  buf1=from1->buf+intg1+frac1;
1854  stop=from1->buf+intg1+frac2;
1855  buf2=from2->buf+intg2+frac2;
1856  stop2=from1->buf+(intg1 > intg2 ? intg1-intg2 : 0);
1857  }
1858  else
1859  {
1860  buf1=from2->buf+intg2+frac2;
1861  stop=from2->buf+intg2+frac1;
1862  buf2=from1->buf+intg1+frac1;
1863  stop2=from2->buf+(intg2 > intg1 ? intg2-intg1 : 0);
1864  }
1865  while (buf1 > stop)
1866  *--buf0=*--buf1;
1867 
1868  /* part 2 - min(frac) ... min(intg) */
1869  carry=0;
1870  while (buf1 > stop2)
1871  {
1872  ADD(*--buf0, *--buf1, *--buf2, carry);
1873  }
1874 
1875  /* part 3 - min(intg) ... max(intg) */
1876  buf1= intg1 > intg2 ? ((stop=from1->buf)+intg1-intg2) :
1877  ((stop=from2->buf)+intg2-intg1) ;
1878  while (buf1 > stop)
1879  {
1880  ADD(*--buf0, *--buf1, 0, carry);
1881  }
1882 
1883  if (unlikely(carry))
1884  *--buf0=1;
1885  DBUG_ASSERT(buf0 == to->buf || buf0 == to->buf+1);
1886 
1887  return error;
1888 }
1889 
1890 /* to=from1-from2.
1891  if to==0, return -1/0/+1 - the result of the comparison */
1892 static int do_sub(const decimal_t *from1, const decimal_t *from2, decimal_t *to)
1893 {
1894  int intg1=ROUND_UP(from1->intg), intg2=ROUND_UP(from2->intg),
1895  frac1=ROUND_UP(from1->frac), frac2=ROUND_UP(from2->frac);
1896  int frac0= MY_MAX(frac1, frac2), error;
1897  dec1 *buf1, *buf2, *buf0, *stop1, *stop2, *start1, *start2, carry=0;
1898 
1899  /* let carry:=1 if from2 > from1 */
1900  start1=buf1=from1->buf; stop1=buf1+intg1;
1901  start2=buf2=from2->buf; stop2=buf2+intg2;
1902  if (unlikely(*buf1 == 0))
1903  {
1904  while (buf1 < stop1 && *buf1 == 0)
1905  buf1++;
1906  start1=buf1;
1907  intg1= (int) (stop1-buf1);
1908  }
1909  if (unlikely(*buf2 == 0))
1910  {
1911  while (buf2 < stop2 && *buf2 == 0)
1912  buf2++;
1913  start2=buf2;
1914  intg2= (int) (stop2-buf2);
1915  }
1916  if (intg2 > intg1)
1917  carry=1;
1918  else if (intg2 == intg1)
1919  {
1920  dec1 *end1= stop1 + (frac1 - 1);
1921  dec1 *end2= stop2 + (frac2 - 1);
1922  while (unlikely((buf1 <= end1) && (*end1 == 0)))
1923  end1--;
1924  while (unlikely((buf2 <= end2) && (*end2 == 0)))
1925  end2--;
1926  frac1= (int) (end1 - stop1) + 1;
1927  frac2= (int) (end2 - stop2) + 1;
1928  while (buf1 <=end1 && buf2 <= end2 && *buf1 == *buf2)
1929  buf1++, buf2++;
1930  if (buf1 <= end1)
1931  {
1932  if (buf2 <= end2)
1933  carry= *buf2 > *buf1;
1934  else
1935  carry= 0;
1936  }
1937  else
1938  {
1939  if (buf2 <= end2)
1940  carry=1;
1941  else /* short-circuit everything: from1 == from2 */
1942  {
1943  if (to == 0) /* decimal_cmp() */
1944  return 0;
1945  decimal_make_zero(to);
1946  return E_DEC_OK;
1947  }
1948  }
1949  }
1950 
1951  if (to == 0) /* decimal_cmp() */
1952  return carry == from1->sign ? 1 : -1;
1953 
1954  sanity(to);
1955 
1956  to->sign=from1->sign;
1957 
1958  /* ensure that always from1 > from2 (and intg1 >= intg2) */
1959  if (carry)
1960  {
1961  swap_variables(const decimal_t *, from1, from2);
1962  swap_variables(dec1 *,start1, start2);
1963  swap_variables(int,intg1,intg2);
1964  swap_variables(int,frac1,frac2);
1965  to->sign= 1 - to->sign;
1966  }
1967 
1968  FIX_INTG_FRAC_ERROR(to->len, intg1, frac0, error);
1969  buf0=to->buf+intg1+frac0;
1970 
1971  to->frac= MY_MAX(from1->frac, from2->frac);
1972  to->intg=intg1*DIG_PER_DEC1;
1973  if (unlikely(error))
1974  {
1975  set_if_smaller(to->frac, frac0*DIG_PER_DEC1);
1976  set_if_smaller(frac1, frac0);
1977  set_if_smaller(frac2, frac0);
1978  set_if_smaller(intg2, intg1);
1979  }
1980  carry=0;
1981 
1982  /* part 1 - max(frac) ... min (frac) */
1983  if (frac1 > frac2)
1984  {
1985  buf1=start1+intg1+frac1;
1986  stop1=start1+intg1+frac2;
1987  buf2=start2+intg2+frac2;
1988  while (frac0-- > frac1)
1989  *--buf0=0;
1990  while (buf1 > stop1)
1991  *--buf0=*--buf1;
1992  }
1993  else
1994  {
1995  buf1=start1+intg1+frac1;
1996  buf2=start2+intg2+frac2;
1997  stop2=start2+intg2+frac1;
1998  while (frac0-- > frac2)
1999  *--buf0=0;
2000  while (buf2 > stop2)
2001  {
2002  SUB(*--buf0, 0, *--buf2, carry);
2003  }
2004  }
2005 
2006  /* part 2 - min(frac) ... intg2 */
2007  while (buf2 > start2)
2008  {
2009  SUB(*--buf0, *--buf1, *--buf2, carry);
2010  }
2011 
2012  /* part 3 - intg2 ... intg1 */
2013  while (carry && buf1 > start1)
2014  {
2015  SUB(*--buf0, *--buf1, 0, carry);
2016  }
2017 
2018  while (buf1 > start1)
2019  *--buf0=*--buf1;
2020 
2021  while (buf0 > to->buf)
2022  *--buf0=0;
2023 
2024  return error;
2025 }
2026 
2027 int decimal_intg(const decimal_t *from)
2028 {
2029  int res;
2030  remove_leading_zeroes(from, &res);
2031  return res;
2032 }
2033 
2034 int decimal_add(const decimal_t *from1, const decimal_t *from2, decimal_t *to)
2035 {
2036  if (likely(from1->sign == from2->sign))
2037  return do_add(from1, from2, to);
2038  return do_sub(from1, from2, to);
2039 }
2040 
2041 int decimal_sub(const decimal_t *from1, const decimal_t *from2, decimal_t *to)
2042 {
2043  if (likely(from1->sign == from2->sign))
2044  return do_sub(from1, from2, to);
2045  return do_add(from1, from2, to);
2046 }
2047 
2048 int decimal_cmp(const decimal_t *from1, const decimal_t *from2)
2049 {
2050  if (likely(from1->sign == from2->sign))
2051  return do_sub(from1, from2, 0);
2052  return from1->sign > from2->sign ? -1 : 1;
2053 }
2054 
2055 int decimal_is_zero(const decimal_t *from)
2056 {
2057  dec1 *buf1=from->buf,
2058  *end=buf1+ROUND_UP(from->intg)+ROUND_UP(from->frac);
2059  while (buf1 < end)
2060  if (*buf1++)
2061  return 0;
2062  return 1;
2063 }
2064 
2065 /*
2066  multiply two decimals
2067 
2068  SYNOPSIS
2069  decimal_mul()
2070  from1, from2 - factors
2071  to - product
2072 
2073  RETURN VALUE
2074  E_DEC_OK/E_DEC_TRUNCATED/E_DEC_OVERFLOW;
2075 
2076  NOTES
2077  in this implementation, with sizeof(dec1)=4 we have DIG_PER_DEC1=9,
2078  and 63-digit number will take only 7 dec1 words (basically a 7-digit
2079  "base 999999999" number). Thus there's no need in fast multiplication
2080  algorithms, 7-digit numbers can be multiplied with a naive O(n*n)
2081  method.
2082 
2083  XXX if this library is to be used with huge numbers of thousands of
2084  digits, fast multiplication must be implemented.
2085 */
2086 int decimal_mul(const decimal_t *from1, const decimal_t *from2, decimal_t *to)
2087 {
2088  int intg1=ROUND_UP(from1->intg), intg2=ROUND_UP(from2->intg),
2089  frac1=ROUND_UP(from1->frac), frac2=ROUND_UP(from2->frac),
2090  intg0=ROUND_UP(from1->intg+from2->intg),
2091  frac0=frac1+frac2, error, iii, jjj, d_to_move;
2092  dec1 *buf1=from1->buf+intg1, *buf2=from2->buf+intg2, *buf0,
2093  *start2, *stop2, *stop1, *start0, carry;
2094 
2095  sanity(to);
2096 
2097  iii= intg0; /* save 'ideal' values */
2098  jjj= frac0;
2099  FIX_INTG_FRAC_ERROR(to->len, intg0, frac0, error); /* bound size */
2100  to->sign= from1->sign != from2->sign;
2101  to->frac= from1->frac + from2->frac; /* store size in digits */
2102  set_if_smaller(to->frac, NOT_FIXED_DEC);
2103  to->intg=intg0*DIG_PER_DEC1;
2104 
2105  if (unlikely(error))
2106  {
2107  set_if_smaller(to->frac, frac0*DIG_PER_DEC1);
2108  set_if_smaller(to->intg, intg0*DIG_PER_DEC1);
2109  if (unlikely(iii > intg0)) /* bounded integer-part */
2110  {
2111  iii-=intg0;
2112  jjj= iii >> 1;
2113  intg1-= jjj;
2114  intg2-=iii-jjj;
2115  frac1=frac2=0; /* frac0 is already 0 here */
2116  }
2117  else /* bounded fract part */
2118  {
2119  jjj-=frac0;
2120  iii=jjj >> 1;
2121  if (frac1 <= frac2)
2122  {
2123  frac1-= iii;
2124  frac2-=jjj-iii;
2125  }
2126  else
2127  {
2128  frac2-= iii;
2129  frac1-=jjj-iii;
2130  }
2131  }
2132  }
2133  start0=to->buf+intg0+frac0-1;
2134  start2=buf2+frac2-1;
2135  stop1=buf1-intg1;
2136  stop2=buf2-intg2;
2137 
2138  memset(to->buf, 0, (intg0+frac0)*sizeof(dec1));
2139 
2140  for (buf1+=frac1-1; buf1 >= stop1; buf1--, start0--)
2141  {
2142  carry=0;
2143  for (buf0=start0, buf2=start2; buf2 >= stop2; buf2--, buf0--)
2144  {
2145  dec1 hi, lo;
2146  dec2 p= ((dec2)*buf1) * ((dec2)*buf2);
2147  hi=(dec1)(p/DIG_BASE);
2148  lo=(dec1)(p-((dec2)hi)*DIG_BASE);
2149  ADD2(*buf0, *buf0, lo, carry);
2150  carry+=hi;
2151  }
2152  if (carry)
2153  {
2154  if (buf0 < to->buf)
2155  return E_DEC_OVERFLOW;
2156  ADD2(*buf0, *buf0, 0, carry);
2157  }
2158  for (buf0--; carry; buf0--)
2159  {
2160  if (buf0 < to->buf)
2161  return E_DEC_OVERFLOW;
2162  ADD(*buf0, *buf0, 0, carry);
2163  }
2164  }
2165 
2166  /* Now we have to check for -0.000 case */
2167  if (to->sign)
2168  {
2169  dec1 *buf= to->buf;
2170  dec1 *end= to->buf + intg0 + frac0;
2171  DBUG_ASSERT(buf != end);
2172  for (;;)
2173  {
2174  if (*buf)
2175  break;
2176  if (++buf == end)
2177  {
2178  /* We got decimal zero */
2179  decimal_make_zero(to);
2180  break;
2181  }
2182  }
2183  }
2184  buf1= to->buf;
2185  d_to_move= intg0 + ROUND_UP(to->frac);
2186  while (!*buf1 && (to->intg > DIG_PER_DEC1))
2187  {
2188  buf1++;
2189  to->intg-= DIG_PER_DEC1;
2190  d_to_move--;
2191  }
2192  if (to->buf < buf1)
2193  {
2194  dec1 *cur_d= to->buf;
2195  for (; d_to_move--; cur_d++, buf1++)
2196  *cur_d= *buf1;
2197  }
2198  return error;
2199 }
2200 
2201 /*
2202  naive division algorithm (Knuth's Algorithm D in 4.3.1) -
2203  it's ok for short numbers
2204  also we're using alloca() to allocate a temporary buffer
2205 
2206  XXX if this library is to be used with huge numbers of thousands of
2207  digits, fast division must be implemented and alloca should be
2208  changed to malloc (or at least fallback to malloc if alloca() fails)
2209  but then, decimal_mul() should be rewritten too :(
2210 */
2211 static int do_div_mod(const decimal_t *from1, const decimal_t *from2,
2212  decimal_t *to, decimal_t *mod, int scale_incr)
2213 {
2214  int frac1=ROUND_UP(from1->frac)*DIG_PER_DEC1, prec1=from1->intg+frac1,
2215  frac2=ROUND_UP(from2->frac)*DIG_PER_DEC1, prec2=from2->intg+frac2,
2216  UNINIT_VAR(error), i, intg0, frac0, len1, len2, dintg, div_mod=(!mod);
2217  dec1 *buf0, *buf1=from1->buf, *buf2=from2->buf, *tmp1,
2218  *start2, *stop2, *stop1, *stop0, norm2, carry, *start1, dcarry;
2219  dec2 norm_factor, x, guess, y;
2220 
2221  if (mod)
2222  to=mod;
2223 
2224  sanity(to);
2225 
2226  /* removing all the leading zeroes */
2227  i= ((prec2 - 1) % DIG_PER_DEC1) + 1;
2228  while (prec2 > 0 && *buf2 == 0)
2229  {
2230  prec2-= i;
2231  i= DIG_PER_DEC1;
2232  buf2++;
2233  }
2234  if (prec2 <= 0) /* short-circuit everything: from2 == 0 */
2235  return E_DEC_DIV_ZERO;
2236  for (i= (prec2 - 1) % DIG_PER_DEC1; *buf2 < powers10[i--]; prec2--) ;
2237  DBUG_ASSERT(prec2 > 0);
2238 
2239  i=((prec1-1) % DIG_PER_DEC1)+1;
2240  while (prec1 > 0 && *buf1 == 0)
2241  {
2242  prec1-=i;
2243  i=DIG_PER_DEC1;
2244  buf1++;
2245  }
2246  if (prec1 <= 0)
2247  { /* short-circuit everything: from1 == 0 */
2248  decimal_make_zero(to);
2249  return E_DEC_OK;
2250  }
2251  for (i=(prec1-1) % DIG_PER_DEC1; *buf1 < powers10[i--]; prec1--) ;
2252  DBUG_ASSERT(prec1 > 0);
2253 
2254  /* let's fix scale_incr, taking into account frac1,frac2 increase */
2255  if ((scale_incr-= frac1 - from1->frac + frac2 - from2->frac) < 0)
2256  scale_incr=0;
2257 
2258  dintg=(prec1-frac1)-(prec2-frac2)+(*buf1 >= *buf2);
2259  if (dintg < 0)
2260  {
2261  dintg/=DIG_PER_DEC1;
2262  intg0=0;
2263  }
2264  else
2265  intg0=ROUND_UP(dintg);
2266  if (mod)
2267  {
2268  /* we're calculating N1 % N2.
2269  The result will have
2270  frac=max(frac1, frac2), as for subtraction
2271  intg=intg2
2272  */
2273  to->sign=from1->sign;
2274  to->frac= MY_MAX(from1->frac, from2->frac);
2275  frac0=0;
2276  }
2277  else
2278  {
2279  /*
2280  we're calculating N1/N2. N1 is in the buf1, has prec1 digits
2281  N2 is in the buf2, has prec2 digits. Scales are frac1 and
2282  frac2 accordingly.
2283  Thus, the result will have
2284  frac = ROUND_UP(frac1+frac2+scale_incr)
2285  and
2286  intg = (prec1-frac1) - (prec2-frac2) + 1
2287  prec = intg+frac
2288  */
2289  frac0=ROUND_UP(frac1+frac2+scale_incr);
2290  FIX_INTG_FRAC_ERROR(to->len, intg0, frac0, error);
2291  to->sign=from1->sign != from2->sign;
2292  to->intg=intg0*DIG_PER_DEC1;
2293  to->frac=frac0*DIG_PER_DEC1;
2294  }
2295  buf0=to->buf;
2296  stop0=buf0+intg0+frac0;
2297  if (likely(div_mod))
2298  while (dintg++ < 0 && buf0 < &to->buf[to->len])
2299  {
2300  *buf0++=0;
2301  }
2302 
2303  len1=(i=ROUND_UP(prec1))+ROUND_UP(2*frac2+scale_incr+1) + 1;
2304  set_if_bigger(len1, 3);
2305  if (!(tmp1=(dec1 *)my_alloca(len1*sizeof(dec1))))
2306  return E_DEC_OOM;
2307  memcpy(tmp1, buf1, i*sizeof(dec1));
2308  memset(tmp1+i, 0, (len1-i)*sizeof(dec1));
2309 
2310  start1=tmp1;
2311  stop1=start1+len1;
2312  start2=buf2;
2313  stop2=buf2+ROUND_UP(prec2)-1;
2314 
2315  /* removing end zeroes */
2316  while (*stop2 == 0 && stop2 >= start2)
2317  stop2--;
2318  len2= (int) (stop2++ - start2);
2319 
2320  /*
2321  calculating norm2 (normalized *start2) - we need *start2 to be large
2322  (at least > DIG_BASE/2), but unlike Knuth's Alg. D we don't want to
2323  normalize input numbers (as we don't make a copy of the divisor).
2324  Thus we normalize first dec1 of buf2 only, and we'll normalize *start1
2325  on the fly for the purpose of guesstimation only.
2326  It's also faster, as we're saving on normalization of buf2
2327  */
2328  norm_factor=DIG_BASE/(*start2+1);
2329  norm2=(dec1)(norm_factor*start2[0]);
2330  if (likely(len2>0))
2331  norm2+=(dec1)(norm_factor*start2[1]/DIG_BASE);
2332 
2333  if (*start1 < *start2)
2334  dcarry=*start1++;
2335  else
2336  dcarry=0;
2337 
2338  /* main loop */
2339  for (; buf0 < stop0; buf0++)
2340  {
2341  /* short-circuit, if possible */
2342  if (unlikely(dcarry == 0 && *start1 < *start2))
2343  guess=0;
2344  else
2345  {
2346  /* D3: make a guess */
2347  x=start1[0]+((dec2)dcarry)*DIG_BASE;
2348  y=start1[1];
2349  guess=(norm_factor*x+norm_factor*y/DIG_BASE)/norm2;
2350  if (unlikely(guess >= DIG_BASE))
2351  guess=DIG_BASE-1;
2352  if (likely(len2>0))
2353  {
2354  /* hmm, this is a suspicious trick - I removed normalization here */
2355  if (start2[1]*guess > (x-guess*start2[0])*DIG_BASE+y)
2356  guess--;
2357  if (unlikely(start2[1]*guess > (x-guess*start2[0])*DIG_BASE+y))
2358  guess--;
2359  DBUG_ASSERT(start2[1]*guess <= (x-guess*start2[0])*DIG_BASE+y);
2360  }
2361 
2362  /* D4: multiply and subtract */
2363  buf2=stop2;
2364  buf1=start1+len2;
2365  DBUG_ASSERT(buf1 < stop1);
2366  for (carry=0; buf2 > start2; buf1--)
2367  {
2368  dec1 hi, lo;
2369  x=guess * (*--buf2);
2370  hi=(dec1)(x/DIG_BASE);
2371  lo=(dec1)(x-((dec2)hi)*DIG_BASE);
2372  SUB2(*buf1, *buf1, lo, carry);
2373  carry+=hi;
2374  }
2375  carry= dcarry < carry;
2376 
2377  /* D5: check the remainder */
2378  if (unlikely(carry))
2379  {
2380  /* D6: correct the guess */
2381  guess--;
2382  buf2=stop2;
2383  buf1=start1+len2;
2384  for (carry=0; buf2 > start2; buf1--)
2385  {
2386  ADD(*buf1, *buf1, *--buf2, carry);
2387  }
2388  }
2389  }
2390  if (likely(div_mod))
2391  {
2392  DBUG_ASSERT(buf0 < to->buf + to->len);
2393  *buf0=(dec1)guess;
2394  }
2395  dcarry= *start1;
2396  start1++;
2397  }
2398  if (mod)
2399  {
2400  /*
2401  now the result is in tmp1, it has
2402  intg=prec1-frac1
2403  frac=max(frac1, frac2)=to->frac
2404  */
2405  if (dcarry)
2406  *--start1=dcarry;
2407  buf0=to->buf;
2408  intg0=(int) (ROUND_UP(prec1-frac1)-(start1-tmp1));
2409  frac0=ROUND_UP(to->frac);
2410  error=E_DEC_OK;
2411  if (unlikely(frac0==0 && intg0==0))
2412  {
2413  decimal_make_zero(to);
2414  goto done;
2415  }
2416  if (intg0<=0)
2417  {
2418  if (unlikely(-intg0 >= to->len))
2419  {
2420  decimal_make_zero(to);
2421  error=E_DEC_TRUNCATED;
2422  goto done;
2423  }
2424  stop1=start1+frac0;
2425  frac0+=intg0;
2426  to->intg=0;
2427  while (intg0++ < 0)
2428  *buf0++=0;
2429  }
2430  else
2431  {
2432  if (unlikely(intg0 > to->len))
2433  {
2434  frac0=0;
2435  intg0=to->len;
2436  error=E_DEC_OVERFLOW;
2437  goto done;
2438  }
2439  DBUG_ASSERT(intg0 <= ROUND_UP(from2->intg));
2440  stop1=start1+frac0+intg0;
2441  to->intg= MY_MIN(intg0 * DIG_PER_DEC1, from2->intg);
2442  }
2443  if (unlikely(intg0+frac0 > to->len))
2444  {
2445  stop1-=frac0+intg0-to->len;
2446  frac0=to->len-intg0;
2447  to->frac=frac0*DIG_PER_DEC1;
2448  error=E_DEC_TRUNCATED;
2449  }
2450  DBUG_ASSERT(buf0 + (stop1 - start1) <= to->buf + to->len);
2451  while (start1 < stop1)
2452  *buf0++=*start1++;
2453  }
2454 done:
2455  my_afree(tmp1);
2456  tmp1= remove_leading_zeroes(to, &to->intg);
2457  if(to->buf != tmp1)
2458  memmove(to->buf, tmp1,
2459  (ROUND_UP(to->intg) + ROUND_UP(to->frac)) * sizeof(dec1));
2460  return error;
2461 }
2462 
2463 /*
2464  division of two decimals
2465 
2466  SYNOPSIS
2467  decimal_div()
2468  from1 - dividend
2469  from2 - divisor
2470  to - quotient
2471 
2472  RETURN VALUE
2473  E_DEC_OK/E_DEC_TRUNCATED/E_DEC_OVERFLOW/E_DEC_DIV_ZERO;
2474 
2475  NOTES
2476  see do_div_mod()
2477 */
2478 
2479 int
2480 decimal_div(const decimal_t *from1, const decimal_t *from2, decimal_t *to,
2481  int scale_incr)
2482 {
2483  return do_div_mod(from1, from2, to, 0, scale_incr);
2484 }
2485 
2486 /*
2487  modulus
2488 
2489  SYNOPSIS
2490  decimal_mod()
2491  from1 - dividend
2492  from2 - divisor
2493  to - modulus
2494 
2495  RETURN VALUE
2496  E_DEC_OK/E_DEC_TRUNCATED/E_DEC_OVERFLOW/E_DEC_DIV_ZERO;
2497 
2498  NOTES
2499  see do_div_mod()
2500 
2501  DESCRIPTION
2502  the modulus R in R = M mod N
2503 
2504  is defined as
2505 
2506  0 <= |R| < |M|
2507  sign R == sign M
2508  R = M - k*N, where k is integer
2509 
2510  thus, there's no requirement for M or N to be integers
2511 */
2512 
2513 int decimal_mod(const decimal_t *from1, const decimal_t *from2, decimal_t *to)
2514 {
2515  return do_div_mod(from1, from2, 0, to, 0);
2516 }
2517 
2518 #ifdef MAIN
2519 /*
2520  The main() program has been converted into a unit test.
2521  */
2522 #endif