fpconv.c 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. /* fpconv - Floating point conversion routines
  2. *
  3. * Copyright (c) 2011-2012 Mark Pulford <mark@kyne.com.au>
  4. *
  5. * Permission is hereby granted, free of charge, to any person obtaining
  6. * a copy of this software and associated documentation files (the
  7. * "Software"), to deal in the Software without restriction, including
  8. * without limitation the rights to use, copy, modify, merge, publish,
  9. * distribute, sublicense, and/or sell copies of the Software, and to
  10. * permit persons to whom the Software is furnished to do so, subject to
  11. * the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be
  14. * included in all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  18. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  19. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  20. * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  21. * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  22. * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. */
  24. /* JSON uses a '.' decimal separator. strtod() / sprintf() under C libraries
  25. * with locale support will break when the decimal separator is a comma.
  26. *
  27. * fpconv_* will around these issues with a translation buffer if required.
  28. */
  29. #include <stdio.h>
  30. #include <stdlib.h>
  31. #include <assert.h>
  32. #include <string.h>
  33. #include "fpconv.h"
  34. /* Lua CJSON assumes the locale is the same for all threads within a
  35. * process and doesn't change after initialisation.
  36. *
  37. * This avoids the need for per thread storage or expensive checks
  38. * for call. */
  39. static char locale_decimal_point = '.';
  40. /* In theory multibyte decimal_points are possible, but
  41. * Lua CJSON only supports UTF-8 and known locales only have
  42. * single byte decimal points ([.,]).
  43. *
  44. * localconv() may not be thread safe (=>crash), and nl_langinfo() is
  45. * not supported on some platforms. Use sprintf() instead - if the
  46. * locale does change, at least Lua CJSON won't crash. */
  47. static void fpconv_update_locale()
  48. {
  49. char buf[8];
  50. snprintf(buf, sizeof(buf), "%g", 0.5);
  51. /* Failing this test might imply the platform has a buggy dtoa
  52. * implementation or wide characters */
  53. if (buf[0] != '0' || buf[2] != '5' || buf[3] != 0) {
  54. fprintf(stderr, "Error: wide characters found or printf() bug.");
  55. abort();
  56. }
  57. locale_decimal_point = buf[1];
  58. }
  59. /* Check for a valid number character: [-+0-9a-yA-Y.]
  60. * Eg: -0.6e+5, infinity, 0xF0.F0pF0
  61. *
  62. * Used to find the probable end of a number. It doesn't matter if
  63. * invalid characters are counted - strtod() will find the valid
  64. * number if it exists. The risk is that slightly more memory might
  65. * be allocated before a parse error occurs. */
  66. static inline int valid_number_character(char ch)
  67. {
  68. char lower_ch;
  69. if ('0' <= ch && ch <= '9')
  70. return 1;
  71. if (ch == '-' || ch == '+' || ch == '.')
  72. return 1;
  73. /* Hex digits, exponent (e), base (p), "infinity",.. */
  74. lower_ch = ch | 0x20;
  75. if ('a' <= lower_ch && lower_ch <= 'y')
  76. return 1;
  77. return 0;
  78. }
  79. /* Calculate the size of the buffer required for a strtod locale
  80. * conversion. */
  81. static int strtod_buffer_size(const char *s)
  82. {
  83. const char *p = s;
  84. while (valid_number_character(*p))
  85. p++;
  86. return p - s;
  87. }
  88. /* Similar to strtod(), but must be passed the current locale's decimal point
  89. * character. Guaranteed to be called at the start of any valid number in a string */
  90. double fpconv_strtod(const char *nptr, char **endptr)
  91. {
  92. char localbuf[FPCONV_G_FMT_BUFSIZE];
  93. char *buf, *endbuf, *dp;
  94. int buflen;
  95. double value;
  96. /* System strtod() is fine when decimal point is '.' */
  97. if (locale_decimal_point == '.')
  98. return strtod(nptr, endptr);
  99. buflen = strtod_buffer_size(nptr);
  100. if (!buflen) {
  101. /* No valid characters found, standard strtod() return */
  102. *endptr = (char *)nptr;
  103. return 0;
  104. }
  105. /* Duplicate number into buffer */
  106. if (buflen >= FPCONV_G_FMT_BUFSIZE) {
  107. /* Handle unusually large numbers */
  108. buf = malloc(buflen + 1);
  109. if (!buf) {
  110. fprintf(stderr, "Out of memory");
  111. abort();
  112. }
  113. } else {
  114. /* This is the common case.. */
  115. buf = localbuf;
  116. }
  117. memcpy(buf, nptr, buflen);
  118. buf[buflen] = 0;
  119. /* Update decimal point character if found */
  120. dp = strchr(buf, '.');
  121. if (dp)
  122. *dp = locale_decimal_point;
  123. value = strtod(buf, &endbuf);
  124. *endptr = (char *)&nptr[endbuf - buf];
  125. if (buflen >= FPCONV_G_FMT_BUFSIZE)
  126. free(buf);
  127. return value;
  128. }
  129. /* "fmt" must point to a buffer of at least 6 characters */
  130. static void set_number_format(char *fmt, int precision)
  131. {
  132. int d1, d2, i;
  133. assert(1 <= precision && precision <= 14);
  134. /* Create printf format (%.14g) from precision */
  135. d1 = precision / 10;
  136. d2 = precision % 10;
  137. fmt[0] = '%';
  138. fmt[1] = '.';
  139. i = 2;
  140. if (d1) {
  141. fmt[i++] = '0' + d1;
  142. }
  143. fmt[i++] = '0' + d2;
  144. fmt[i++] = 'g';
  145. fmt[i] = 0;
  146. }
  147. /* Assumes there is always at least 32 characters available in the target buffer */
  148. int fpconv_g_fmt(char *str, double num, int precision)
  149. {
  150. char buf[FPCONV_G_FMT_BUFSIZE];
  151. char fmt[6];
  152. int len;
  153. char *b;
  154. set_number_format(fmt, precision);
  155. /* Pass through when decimal point character is dot. */
  156. if (locale_decimal_point == '.')
  157. return snprintf(str, FPCONV_G_FMT_BUFSIZE, fmt, num);
  158. /* snprintf() to a buffer then translate for other decimal point characters */
  159. len = snprintf(buf, FPCONV_G_FMT_BUFSIZE, fmt, num);
  160. /* Copy into target location. Translate decimal point if required */
  161. b = buf;
  162. do {
  163. *str++ = (*b == locale_decimal_point ? '.' : *b);
  164. } while(*b++);
  165. return len;
  166. }
  167. void fpconv_init()
  168. {
  169. fpconv_update_locale();
  170. }
  171. /* vi:ai et sw=4 ts=4:
  172. */