MySQL 5.6.14 Source Code Document
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
decimal_utils.cpp
1 /*
2  Copyright 2010 Sun Microsystems, Inc.
3  All rights reserved. Use is subject to license terms.
4 
5  This program is free software; you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published by
7  the Free Software Foundation; version 2 of the License.
8 
9  This program is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  GNU General Public License for more details.
13 
14  You should have received a copy of the GNU General Public License
15  along with this program; if not, write to the Free Software
16  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
17 */
18 /*
19  * decimal_utils.cpp
20  */
21 
22 #include "my_global.h"
23 #include "m_string.h"
24 C_MODE_START
25 #include "decimal.h"
26 C_MODE_END
27 
28 #include "decimal_utils.hpp"
29 
30 int decimal_str2bin(const char *str, int str_len,
31  int prec, int scale,
32  void *bin, int bin_len)
33 {
34  register int retval; /* return value from str2dec() */
35  decimal_t dec; /* intermediate representation */
36  decimal_digit_t digits[9]; /* for dec->buf */
37  char *end = (char *) str + str_len;
38 
39  assert(str != 0);
40  assert(bin != 0);
41  if(prec < 1) return E_DEC_BAD_PREC;
42  if((scale < 0) || (scale > prec)) return E_DEC_BAD_SCALE;
43 
44  if(decimal_bin_size(prec, scale) > bin_len)
45  return E_DEC_OOM;
46 
47  dec.len = 9; /* big enough for any decimal */
48  dec.buf = digits;
49 
50  retval = string2decimal(str, &dec, &end);
51  if(retval != E_DEC_OK) return retval;
52 
53  return decimal2bin(&dec, (unsigned char *) bin, prec, scale);
54 }
55 
56 int decimal_bin2str(const void *bin, int bin_len,
57  int prec, int scale,
58  char *str, int str_len)
59 {
60  register int retval; /* return from bin2decimal() */
61  decimal_t dec; /* intermediate representation */
62  decimal_digit_t digits[9]; /* for dec->buf */
63  int to_len;
64 
65  assert(bin != 0);
66  assert(str != 0);
67  if(prec < 1) return E_DEC_BAD_PREC;
68  if((scale < 0) || (scale > prec)) return E_DEC_BAD_SCALE;
69 
70  dec.len = 9; /* big enough for any decimal */
71  dec.buf = digits;
72 
73  // Note: bin_len is unused -- bin2decimal() does not take a length
74  retval = bin2decimal((const uchar *) bin, &dec, prec, scale);
75  if(retval != E_DEC_OK) return retval;
76 
77  to_len = decimal_string_size(&dec);
78  if(to_len > str_len) return E_DEC_OOM;
79 
80  return decimal2string(&dec, str, &to_len, 0, 0, 0);
81 }