NumberToString.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. #ifndef NUMBERTOSTRING_H
  2. #define NUMBERTOSTRING_H
  3. #include <limits>
  4. #include "JSONDebug.h"
  5. #ifdef JSON_LESS_MEMORY
  6. #include "JSONMemory.h"
  7. #endif
  8. #include "JSONSharedString.h"
  9. #include <cstdio>
  10. #ifdef JSON_STRICT
  11. #include <cmath>
  12. #endif
  13. template <unsigned int GETLENSIZE>
  14. struct getLenSize{
  15. char tmp[GETLENSIZE == 16]; // compile time assertion
  16. enum {GETLEN = 41};
  17. };
  18. template<>
  19. struct getLenSize<1>{
  20. enum {GETLEN = 5};
  21. };
  22. template <>
  23. struct getLenSize<2>{
  24. enum {GETLEN = 7};
  25. };
  26. template <>
  27. struct getLenSize<4>{
  28. enum {GETLEN = 12};
  29. };
  30. template <>
  31. struct getLenSize<8>{
  32. enum {GETLEN = 22};
  33. };
  34. static inline bool _floatsAreEqual(const json_number & one, const json_number & two) json_pure;
  35. static inline bool _floatsAreEqual(const json_number & one, const json_number & two) json_nothrow {
  36. return (one > two) ? (one - two) < JSON_FLOAT_THRESHHOLD : (one - two) > -JSON_FLOAT_THRESHHOLD;
  37. }
  38. #ifdef JSON_LESS_MEMORY
  39. #define num_str_result s.ptr
  40. #endif
  41. class NumberToString {
  42. public:
  43. template<typename T>
  44. static json_string _itoa(T val) json_nothrow {
  45. #ifdef JSON_LESS_MEMORY
  46. json_auto<json_char> s(getLenSize<sizeof(T)>::GETLEN);
  47. #else
  48. json_char num_str_result[getLenSize<sizeof(T)>::GETLEN];
  49. #endif
  50. num_str_result[getLenSize<sizeof(T)>::GETLEN - 1] = JSON_TEXT('\0'); //null terminator
  51. json_char * runner = &num_str_result[getLenSize<sizeof(T)>::GETLEN - 2];
  52. bool negative;
  53. START_MEM_SCOPE
  54. long value = (long)val;
  55. //first thing, check if it's negative, if so, make it positive
  56. if (value < 0){
  57. value = -value;
  58. negative = true;
  59. } else {
  60. negative = false;
  61. }
  62. //create the string
  63. do {
  64. *runner-- = (json_char)(value % 10) + JSON_TEXT('0');
  65. } while(value /= 10);
  66. END_MEM_SCOPE
  67. //if it's negative, add the negation
  68. if (negative){
  69. *runner = JSON_TEXT('-');
  70. return json_string(runner);
  71. }
  72. return json_string(runner + 1);
  73. }
  74. #ifndef JSON_LIBRARY
  75. template<typename T>
  76. static json_string _uitoa(T val) json_nothrow {
  77. #ifdef JSON_LESS_MEMORY
  78. json_auto<json_char> s(getLenSize<sizeof(T)>::GETLEN);
  79. #else
  80. json_char num_str_result[getLenSize<sizeof(T)>::GETLEN];
  81. #endif
  82. num_str_result[getLenSize<sizeof(T)>::GETLEN - 1] = JSON_TEXT('\0'); //null terminator
  83. json_char * runner = &num_str_result[getLenSize<sizeof(T)>::GETLEN - 2];
  84. //create the string
  85. START_MEM_SCOPE
  86. unsigned long value = (unsigned long)val;
  87. do {
  88. *runner-- = (json_char)(value % 10) + JSON_TEXT('0');
  89. } while(value /= 10);
  90. END_MEM_SCOPE
  91. return json_string(runner + 1);
  92. }
  93. #endif
  94. #ifdef JSON_ISO_STRICT
  95. #define EXTRA_LONG
  96. #define FLOAT_STRING "%f"
  97. #define LFLOAT_STRING L"%f"
  98. #else
  99. #define EXTRA_LONG long
  100. #define FLOAT_STRING "%Lf"
  101. #define LFLOAT_STRING L"%Lf"
  102. #endif
  103. static json_string _ftoa(json_number value) json_nothrow {
  104. #ifndef JSON_LIBRARY
  105. //ScopeCoverage(_ftoa_coverage, 6);
  106. if (json_unlikely(value >= 0.0 && _floatsAreEqual(value, (json_number)((unsigned EXTRA_LONG long)value)))){
  107. return _uitoa<unsigned EXTRA_LONG long>((unsigned EXTRA_LONG long)value);
  108. } else
  109. #else
  110. //ScopeCoverage(_ftoa_coverage, 5);
  111. #endif
  112. if (json_unlikely(_floatsAreEqual(value, (json_number)((long EXTRA_LONG)value)))){
  113. return _itoa<long EXTRA_LONG>((long EXTRA_LONG)value);
  114. }
  115. #ifdef JSON_LESS_MEMORY
  116. json_auto<json_char> s(64);
  117. #else
  118. json_char num_str_result[64];
  119. #endif
  120. #ifdef JSON_UNICODE
  121. std::swprintf(num_str_result, 63, LFLOAT_STRING, (EXTRA_LONG double)value);
  122. #else
  123. //Thanks to Salvor Hardin for this Visual C++ fix
  124. #ifdef _MSC_VER
  125. _snprintf_s(num_str_result, 63, 63, FLOAT_STRING, (EXTRA_LONG double)value); //yes, 63 appears twice using _snprintf_s()
  126. #else
  127. snprintf(num_str_result, 63, FLOAT_STRING, (EXTRA_LONG double)value);
  128. #endif
  129. #endif
  130. //strip the trailing zeros
  131. for(json_char * pos = &num_str_result[0]; *pos; ++pos){
  132. if (json_unlikely(*pos == '.')){ //only care about after the decimal
  133. for(json_char * runner = pos + 1; *runner; ++runner){
  134. if (json_likely(*runner != JSON_TEXT('0'))){
  135. pos = runner + 1; //have to go to the end 1.0001
  136. }
  137. }
  138. *pos = JSON_TEXT('\0');
  139. break;
  140. }
  141. }
  142. return json_string(num_str_result);
  143. }
  144. #if defined(JSON_SAFE) || defined(JSON_DEBUG)
  145. static bool isNumeric(const json_string & str) json_nothrow {
  146. const json_char * p = str.c_str();
  147. bool decimal = false;
  148. bool scientific = false;
  149. #ifdef JSON_STRICT
  150. bool leadingzero = false;
  151. #endif
  152. //first letter is weird
  153. switch(*p){
  154. case JSON_TEXT('\0'):
  155. return false;
  156. #ifndef JSON_STRICT
  157. case JSON_TEXT('.'):
  158. decimal = true;
  159. break;
  160. case JSON_TEXT('+'):
  161. #endif
  162. case JSON_TEXT('-'):
  163. switch (*(p + 1)){
  164. case JSON_TEXT('.'):
  165. case JSON_TEXT('e'):
  166. case JSON_TEXT('E'):
  167. case JSON_TEXT('\0'):
  168. return false;
  169. case JSON_TEXT('0'):
  170. #ifdef JSON_STRICT
  171. switch(*(p + 2)){
  172. case JSON_TEXT('.'):
  173. case JSON_TEXT('e'):
  174. case JSON_TEXT('E'):
  175. leadingzero = false;
  176. break;
  177. case JSON_TEXT('\0'):
  178. return true;
  179. default:
  180. leadingzero = true;
  181. break;
  182. }
  183. #endif
  184. ++p;
  185. break;
  186. default:
  187. break;
  188. }
  189. break;
  190. case JSON_TEXT('1'):
  191. case JSON_TEXT('2'):
  192. case JSON_TEXT('3'):
  193. case JSON_TEXT('4'):
  194. case JSON_TEXT('5'):
  195. case JSON_TEXT('6'):
  196. case JSON_TEXT('7'):
  197. case JSON_TEXT('8'):
  198. case JSON_TEXT('9'):
  199. break;
  200. case JSON_TEXT('0'):
  201. ++p;
  202. #ifdef JSON_STRICT
  203. leadingzero = true;
  204. #endif
  205. switch(*p){
  206. case JSON_TEXT('.'):
  207. decimal = true;
  208. break;
  209. case JSON_TEXT('e'):
  210. case JSON_TEXT('E'):
  211. #ifdef JSON_STRICT
  212. leadingzero = false; //not leading, just a zero
  213. #endif
  214. scientific = true;
  215. ++p;
  216. switch(*p){
  217. case JSON_TEXT('\0'):
  218. return false;
  219. case JSON_TEXT('-'):
  220. case JSON_TEXT('+'):
  221. #ifndef JSON_STRICT
  222. case JSON_TEXT('0'): //cant have a leading zero in scrict
  223. #endif
  224. case JSON_TEXT('1'):
  225. case JSON_TEXT('2'):
  226. case JSON_TEXT('3'):
  227. case JSON_TEXT('4'):
  228. case JSON_TEXT('5'):
  229. case JSON_TEXT('6'):
  230. case JSON_TEXT('7'):
  231. case JSON_TEXT('8'):
  232. case JSON_TEXT('9'):
  233. break;
  234. default:
  235. return false;
  236. }
  237. break;
  238. #ifndef JSON_STRICT
  239. case JSON_TEXT('x'):
  240. return (str.find_first_not_of(JSON_TEXT("0123456789ABCDEFabcdef"), 2) == json_string::npos);
  241. case JSON_TEXT('1'):
  242. case JSON_TEXT('2'):
  243. case JSON_TEXT('3'):
  244. case JSON_TEXT('4'):
  245. case JSON_TEXT('5'):
  246. case JSON_TEXT('6'):
  247. case JSON_TEXT('7'):
  248. return (str.find_first_not_of(JSON_TEXT("01234567"), 1) == json_string::npos);
  249. #endif
  250. case JSON_TEXT('\0'): //just 0
  251. return true;
  252. default:
  253. return false;
  254. }
  255. break;
  256. default:
  257. return false;
  258. }
  259. ++p;
  260. //next digits
  261. while (*p){
  262. switch(*p){
  263. case JSON_TEXT('.'):
  264. if (json_unlikely(decimal)){
  265. return false; //multiple decimals
  266. }
  267. if (json_unlikely(scientific)){
  268. return false;
  269. }
  270. decimal = true;
  271. break;
  272. case JSON_TEXT('e'):
  273. case JSON_TEXT('E'):
  274. if (json_unlikely(scientific)){
  275. return false;
  276. }
  277. scientific = true;
  278. ++p;
  279. switch(*p){
  280. case JSON_TEXT('\0'):
  281. return false;
  282. case JSON_TEXT('-'):
  283. case JSON_TEXT('+'):
  284. if (!isdigit(*(p + 1))){
  285. return false;
  286. }
  287. #ifdef JSON_STRICT
  288. if (*(p + 1) == JSON_TEXT('0')){ //no leading zeros on scientific notations
  289. return false;
  290. }
  291. #endif
  292. break;
  293. #ifndef JSON_STRICT
  294. case JSON_TEXT('0'): //cant have a leading zero in scrict
  295. #endif
  296. case JSON_TEXT('1'):
  297. case JSON_TEXT('2'):
  298. case JSON_TEXT('3'):
  299. case JSON_TEXT('4'):
  300. case JSON_TEXT('5'):
  301. case JSON_TEXT('6'):
  302. case JSON_TEXT('7'):
  303. case JSON_TEXT('8'):
  304. case JSON_TEXT('9'):
  305. break;
  306. default:
  307. return false;
  308. }
  309. break;
  310. case JSON_TEXT('0'):
  311. case JSON_TEXT('1'):
  312. case JSON_TEXT('2'):
  313. case JSON_TEXT('3'):
  314. case JSON_TEXT('4'):
  315. case JSON_TEXT('5'):
  316. case JSON_TEXT('6'):
  317. case JSON_TEXT('7'):
  318. case JSON_TEXT('8'):
  319. case JSON_TEXT('9'):
  320. break;
  321. default:
  322. return false;
  323. }
  324. ++p;
  325. }
  326. #ifdef JSON_STRICT
  327. if (leadingzero && !decimal){
  328. return false;
  329. }
  330. #endif
  331. return true;
  332. }
  333. #endif
  334. #ifdef JSON_STRICT
  335. //much faster because no octal or hex support
  336. static json_number _atof (const json_char * num){
  337. json_number sign = (json_number)1.0;
  338. //sign
  339. if (*num==JSON_TEXT('-')){
  340. sign = -1.0;
  341. ++num;
  342. } else {
  343. }
  344. //skip leading zero if one
  345. #if defined(JSON_SAFE) || defined(JSON_DEBUG)
  346. bool _leadingzeros = *num == JSON_TEXT('0');
  347. bool _leadingdigits = false;
  348. #endif
  349. if (*num == JSON_TEXT('0')){
  350. ++num;
  351. }
  352. #ifdef JSON_STRICT
  353. else if (json_likely(*num < JSON_TEXT('1') || *num > JSON_TEXT('9'))){
  354. return std::numeric_limits<json_number>::signaling_NaN();
  355. }
  356. #endif
  357. JSON_ASSERT_SAFE(*num != JSON_TEXT('0'), JSON_TEXT("multiple leading zeros"), return std::numeric_limits<json_number>::signaling_NaN(); );
  358. // Number
  359. json_number n = (json_number)0.0;
  360. if (json_likely(*num >= JSON_TEXT('1') && *num <= JSON_TEXT('9'))){
  361. #if defined(JSON_SAFE) || defined(JSON_DEBUG)
  362. _leadingdigits = true;
  363. #endif
  364. do {
  365. n = (n * 10.0) + (*num++ - JSON_TEXT('0'));
  366. } while (*num >= JSON_TEXT('0') && *num <= JSON_TEXT('9'));
  367. } else {
  368. JSON_ASSERT_SAFE(
  369. (*num) == JSON_TEXT('.') || //.xxx
  370. (*num) == JSON_TEXT('e') || //0Exxx
  371. (*num) == JSON_TEXT('E') || //0exxx
  372. (*num) == JSON_TEXT('\0') //end of the number, just zero
  373. , JSON_TEXT("first digit not a number, e, period, or terminator"), return std::numeric_limits<json_number>::signaling_NaN(); );
  374. }
  375. // Fractional part
  376. json_number scale = (json_number)0.0;
  377. if (*num == JSON_TEXT('.')) {
  378. JSON_ASSERT_SAFE(_leadingzeros || _leadingdigits, JSON_TEXT("period without leading anything"), return std::numeric_limits<json_number>::signaling_NaN(); );
  379. ++num;
  380. for(; *num >= JSON_TEXT('0') && *num <= JSON_TEXT('9');){
  381. n = (n * 10.0) + (*num++ - JSON_TEXT('0'));
  382. --scale;
  383. };
  384. } else {
  385. JSON_ASSERT_SAFE(!_leadingzeros || n == 0, JSON_TEXT("leading zero on an int"), return std::numeric_limits<json_number>::signaling_NaN(); );
  386. JSON_ASSERT_SAFE(
  387. (*num) == JSON_TEXT('e') || //0Exxx
  388. (*num) == JSON_TEXT('E') || //0exxx
  389. (*num) == JSON_TEXT('\0') //end of the number, just zero
  390. , JSON_TEXT("next char not an e or terminator"), return std::numeric_limits<json_number>::signaling_NaN(); );
  391. }
  392. // Exponent
  393. int subscale = 0, signsubscale = 1;
  394. if (json_unlikely(*num == JSON_TEXT('e') || *num == JSON_TEXT('E'))){
  395. ++num;
  396. switch(*num){
  397. case JSON_TEXT('+'):
  398. ++num;
  399. break;
  400. case JSON_TEXT('-'):
  401. signsubscale = -1;
  402. ++num;
  403. JSON_ASSERT_SAFE(*num != JSON_TEXT('0'), JSON_TEXT("negative cant be followed by leading zero even after E"), return std::numeric_limits<json_number>::signaling_NaN(); );
  404. break;
  405. default:
  406. break;
  407. }
  408. JSON_ASSERT_SAFE(*num != JSON_TEXT('\0'), JSON_TEXT("no exponent for scientific notation"), return std::numeric_limits<json_number>::signaling_NaN(); );
  409. while (*num >= JSON_TEXT('0') && *num <= JSON_TEXT('9')){
  410. subscale=(subscale * 10) + (*num++ - JSON_TEXT('0'));
  411. }
  412. }
  413. JSON_ASSERT_SAFE(*num == JSON_TEXT('\0'), JSON_TEXT("done with number, not at terminator"), return std::numeric_limits<json_number>::signaling_NaN(); );
  414. return sign * n * pow((json_number)10.0, scale + subscale * signsubscale); // number = +/- number.fraction * 10^+/- exponent
  415. }
  416. #endif
  417. };
  418. #endif