NumericString.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. //
  2. // NumericString.h
  3. //
  4. // $Id: //poco/1.4/Foundation/include/Poco/NumericString.h#1 $
  5. //
  6. // Library: Foundation
  7. // Package: Core
  8. // Module: NumericString
  9. //
  10. // Numeric string utility functions.
  11. //
  12. // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
  13. // and Contributors.
  14. //
  15. // SPDX-License-Identifier: BSL-1.0
  16. //
  17. #ifndef Foundation_NumericString_INCLUDED
  18. #define Foundation_NumericString_INCLUDED
  19. #include "Poco/Foundation.h"
  20. #include "Poco/Buffer.h"
  21. #include "Poco/FPEnvironment.h"
  22. #ifdef min
  23. #undef min
  24. #endif
  25. #ifdef max
  26. #undef max
  27. #endif
  28. #include <limits>
  29. #include <cmath>
  30. #if !defined(POCO_NO_LOCALE)
  31. #include <locale>
  32. #endif
  33. // binary numbers are supported, thus 64 (bits) + 1 (string terminating zero)
  34. #define POCO_MAX_INT_STRING_LEN 65
  35. // value from strtod.cc (double_conversion::kMaxSignificantDecimalDigits)
  36. #define POCO_MAX_FLT_STRING_LEN 780
  37. #define POCO_FLT_INF "inf"
  38. #define POCO_FLT_NAN "nan"
  39. #define POCO_FLT_EXP 'e'
  40. namespace Poco {
  41. inline char decimalSeparator()
  42. /// Returns decimal separator from global locale or
  43. /// default '.' for platforms where locale is unavailable.
  44. {
  45. #if !defined(POCO_NO_LOCALE)
  46. return std::use_facet<std::numpunct<char> >(std::locale()).decimal_point();
  47. #else
  48. return '.';
  49. #endif
  50. }
  51. inline char thousandSeparator()
  52. /// Returns thousand separator from global locale or
  53. /// default ',' for platforms where locale is unavailable.
  54. {
  55. #if !defined(POCO_NO_LOCALE)
  56. return std::use_facet<std::numpunct<char> >(std::locale()).thousands_sep();
  57. #else
  58. return ',';
  59. #endif
  60. }
  61. //
  62. // String to Number Conversions
  63. //
  64. template <typename I>
  65. bool strToInt(const char* pStr, I& result, short base, char thSep = ',')
  66. /// Converts zero-terminated character array to integer number;
  67. /// Thousand separators are recognized for base10 and current locale;
  68. /// it is silently skipped but not verified for correct positioning.
  69. /// Function returns true if succesful. If parsing was unsuccesful,
  70. /// the return value is false with the result value undetermined.
  71. {
  72. if (!pStr) return false;
  73. while (isspace(*pStr)) ++pStr;
  74. if (*pStr == '\0') return false;
  75. short sign = 1;
  76. if ((base == 10) && (*pStr == '-'))
  77. {
  78. // Unsigned types can't be negative so abort parsing
  79. if (std::numeric_limits<I>::min() >= 0) return false;
  80. sign = -1;
  81. ++pStr;
  82. }
  83. else if (*pStr == '+') ++pStr;
  84. // parser states:
  85. const char STATE_SIGNIFICANT_DIGITS = 1;
  86. char state = 0;
  87. result = 0;
  88. I limitCheck = std::numeric_limits<I>::max() / base;
  89. for (; *pStr != '\0'; ++pStr)
  90. {
  91. switch (*pStr)
  92. {
  93. case 'x': case 'X':
  94. if (base != 0x10) return false;
  95. case '0':
  96. if (state < STATE_SIGNIFICANT_DIGITS) break;
  97. case '1': case '2': case '3': case '4':
  98. case '5': case '6': case '7':
  99. if (state < STATE_SIGNIFICANT_DIGITS) state = STATE_SIGNIFICANT_DIGITS;
  100. if (result > limitCheck) return false;
  101. result = result * base + (*pStr - '0');
  102. break;
  103. case '8': case '9':
  104. if ((base == 10) || (base == 0x10))
  105. {
  106. if (state < STATE_SIGNIFICANT_DIGITS) state = STATE_SIGNIFICANT_DIGITS;
  107. if (result > limitCheck) return false;
  108. result = result * base + (*pStr - '0');
  109. }
  110. else return false;
  111. break;
  112. case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
  113. if (base != 0x10) return false;
  114. if (state < STATE_SIGNIFICANT_DIGITS) state = STATE_SIGNIFICANT_DIGITS;
  115. if (result > limitCheck) return false;
  116. result = result * base + (10 + *pStr - 'a');
  117. break;
  118. case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
  119. if (base != 0x10) return false;
  120. if (state < STATE_SIGNIFICANT_DIGITS) state = STATE_SIGNIFICANT_DIGITS;
  121. if (result > limitCheck) return false;
  122. result = result * base + (10 + *pStr - 'A');
  123. break;
  124. case 'U':
  125. case 'u':
  126. case 'L':
  127. case 'l':
  128. goto done;
  129. case '.':
  130. if ((base == 10) && (thSep == '.')) break;
  131. else return false;
  132. case ',':
  133. if ((base == 10) && (thSep == ',')) break;
  134. else return false;
  135. case ' ':
  136. if ((base == 10) && (thSep == ' ')) break;
  137. case '\t':
  138. case '\n':
  139. case '\v':
  140. case '\f':
  141. case '\r':
  142. goto done;
  143. default:
  144. return false;
  145. }
  146. }
  147. done:
  148. if ((sign < 0) && (base == 10)) result *= sign;
  149. return true;
  150. }
  151. template <typename I>
  152. bool strToInt(const std::string& str, I& result, short base, char thSep = ',')
  153. /// Converts string to integer number;
  154. /// This is a wrapper function, for details see see the
  155. /// bool strToInt(const char*, I&, short, char) implementation.
  156. {
  157. return strToInt(str.c_str(), result, base, thSep);
  158. }
  159. //
  160. // Number to String Conversions
  161. //
  162. namespace Impl {
  163. class Ptr
  164. /// Utility char pointer wrapper class.
  165. /// Class ensures increment/decrement remain within boundaries.
  166. {
  167. public:
  168. Ptr(char* ptr, std::size_t offset): _beg(ptr), _cur(ptr), _end(ptr + offset)
  169. {
  170. }
  171. char*& operator ++ () // prefix
  172. {
  173. check(_cur + 1);
  174. return ++_cur;
  175. }
  176. char* operator ++ (int) // postfix
  177. {
  178. check(_cur + 1);
  179. char* tmp = _cur++;
  180. return tmp;
  181. }
  182. char*& operator -- () // prefix
  183. {
  184. check(_cur - 1);
  185. return --_cur;
  186. }
  187. char* operator -- (int) // postfix
  188. {
  189. check(_cur - 1);
  190. char* tmp = _cur--;
  191. return tmp;
  192. }
  193. char*& operator += (int incr)
  194. {
  195. check(_cur + incr);
  196. return _cur += incr;
  197. }
  198. char*& operator -= (int decr)
  199. {
  200. check(_cur - decr);
  201. return _cur -= decr;
  202. }
  203. operator char* () const
  204. {
  205. return _cur;
  206. }
  207. std::size_t span() const
  208. {
  209. return _end - _beg;
  210. }
  211. private:
  212. void check(char* ptr)
  213. {
  214. if (ptr > _end) throw RangeException();
  215. }
  216. const char* _beg;
  217. char* _cur;
  218. const char* _end;
  219. };
  220. } // namespace Impl
  221. template <typename T>
  222. bool intToStr(T value,
  223. unsigned short base,
  224. char* result,
  225. std::size_t& size,
  226. bool prefix = false,
  227. int width = -1,
  228. char fill = ' ',
  229. char thSep = 0)
  230. /// Converts integer to string. Numeric bases from binary to hexadecimal are supported.
  231. /// If width is non-zero, it pads the return value with fill character to the specified width.
  232. /// When padding is zero character ('0'), it is prepended to the number itself; all other
  233. /// paddings are prepended to the formatted result with minus sign or base prefix included
  234. /// If prefix is true and base is octal or hexadecimal, respective prefix ('0' for octal,
  235. /// "0x" for hexadecimal) is prepended. For all other bases, prefix argument is ignored.
  236. /// Formatted string has at least [width] total length.
  237. {
  238. if (base < 2 || base > 0x10)
  239. {
  240. *result = '\0';
  241. return false;
  242. }
  243. Impl::Ptr ptr(result, size);
  244. int thCount = 0;
  245. T tmpVal;
  246. do
  247. {
  248. tmpVal = value;
  249. value /= base;
  250. *ptr++ = "FEDCBA9876543210123456789ABCDEF"[15 + (tmpVal - value * base)];
  251. if (thSep && (base == 10) && (++thCount == 3))
  252. {
  253. *ptr++ = thSep;
  254. thCount = 0;
  255. }
  256. } while (value);
  257. if ('0' == fill)
  258. {
  259. if (tmpVal < 0) --width;
  260. if (prefix && base == 010) --width;
  261. if (prefix && base == 0x10) width -= 2;
  262. while ((ptr - result) < width) *ptr++ = fill;
  263. }
  264. if (prefix && base == 010) *ptr++ = '0';
  265. else if (prefix && base == 0x10)
  266. {
  267. *ptr++ = 'x';
  268. *ptr++ = '0';
  269. }
  270. if (tmpVal < 0) *ptr++ = '-';
  271. if ('0' != fill)
  272. {
  273. while ((ptr - result) < width) *ptr++ = fill;
  274. }
  275. size = ptr - result;
  276. poco_assert_dbg (size <= ptr.span());
  277. poco_assert_dbg ((-1 == width) || (size >= size_t(width)));
  278. *ptr-- = '\0';
  279. char* ptrr = result;
  280. char tmp;
  281. while(ptrr < ptr)
  282. {
  283. tmp = *ptr;
  284. *ptr-- = *ptrr;
  285. *ptrr++ = tmp;
  286. }
  287. return true;
  288. }
  289. template <typename T>
  290. bool uIntToStr(T value,
  291. unsigned short base,
  292. char* result,
  293. std::size_t& size,
  294. bool prefix = false,
  295. int width = -1,
  296. char fill = ' ',
  297. char thSep = 0)
  298. /// Converts unsigned integer to string. Numeric bases from binary to hexadecimal are supported.
  299. /// If width is non-zero, it pads the return value with fill character to the specified width.
  300. /// When padding is zero character ('0'), it is prepended to the number itself; all other
  301. /// paddings are prepended to the formatted result with minus sign or base prefix included
  302. /// If prefix is true and base is octal or hexadecimal, respective prefix ('0' for octal,
  303. /// "0x" for hexadecimal) is prepended. For all other bases, prefix argument is ignored.
  304. /// Formatted string has at least [width] total length.
  305. {
  306. if (base < 2 || base > 0x10)
  307. {
  308. *result = '\0';
  309. return false;
  310. }
  311. Impl::Ptr ptr(result, size);
  312. int thCount = 0;
  313. T tmpVal;
  314. do
  315. {
  316. tmpVal = value;
  317. value /= base;
  318. *ptr++ = "FEDCBA9876543210123456789ABCDEF"[15 + (tmpVal - value * base)];
  319. if (thSep && (base == 10) && (++thCount == 3))
  320. {
  321. *ptr++ = thSep;
  322. thCount = 0;
  323. }
  324. } while (value);
  325. if ('0' == fill)
  326. {
  327. if (prefix && base == 010) --width;
  328. if (prefix && base == 0x10) width -= 2;
  329. while ((ptr - result) < width) *ptr++ = fill;
  330. }
  331. if (prefix && base == 010) *ptr++ = '0';
  332. else if (prefix && base == 0x10)
  333. {
  334. *ptr++ = 'x';
  335. *ptr++ = '0';
  336. }
  337. if ('0' != fill)
  338. {
  339. while ((ptr - result) < width) *ptr++ = fill;
  340. }
  341. size = ptr - result;
  342. poco_assert_dbg (size <= ptr.span());
  343. poco_assert_dbg ((-1 == width) || (size >= size_t(width)));
  344. *ptr-- = '\0';
  345. char* ptrr = result;
  346. char tmp;
  347. while(ptrr < ptr)
  348. {
  349. tmp = *ptr;
  350. *ptr-- = *ptrr;
  351. *ptrr++ = tmp;
  352. }
  353. return true;
  354. }
  355. template <typename T>
  356. bool intToStr (T number, unsigned short base, std::string& result, bool prefix = false, int width = -1, char fill = ' ', char thSep = 0)
  357. /// Converts integer to string; This is a wrapper function, for details see see the
  358. /// bool intToStr(T, unsigned short, char*, int, int, char, char) implementation.
  359. {
  360. char res[POCO_MAX_INT_STRING_LEN] = {0};
  361. std::size_t size = POCO_MAX_INT_STRING_LEN;
  362. bool ret = intToStr(number, base, res, size, prefix, width, fill, thSep);
  363. result.assign(res, size);
  364. return ret;
  365. }
  366. template <typename T>
  367. bool uIntToStr (T number, unsigned short base, std::string& result, bool prefix = false, int width = -1, char fill = ' ', char thSep = 0)
  368. /// Converts unsigned integer to string; This is a wrapper function, for details see see the
  369. /// bool uIntToStr(T, unsigned short, char*, int, int, char, char) implementation.
  370. {
  371. char res[POCO_MAX_INT_STRING_LEN] = {0};
  372. std::size_t size = POCO_MAX_INT_STRING_LEN;
  373. bool ret = uIntToStr(number, base, res, size, prefix, width, fill, thSep);
  374. result.assign(res, size);
  375. return ret;
  376. }
  377. //
  378. // Wrappers for double-conversion library (http://code.google.com/p/double-conversion/).
  379. //
  380. // Library is the implementation of the algorithm described in Florian Loitsch's paper:
  381. // http://florian.loitsch.com/publications/dtoa-pldi2010.pdf
  382. //
  383. Foundation_API void floatToStr(char* buffer,
  384. int bufferSize,
  385. float value,
  386. int lowDec = -std::numeric_limits<double>::digits10,
  387. int highDec = std::numeric_limits<double>::digits10);
  388. /// Converts a float value to string. Converted string must be shorter than bufferSize.
  389. /// Conversion is done by computing the shortest string of digits that correctly represents
  390. /// the input number. Depending on lowDec and highDec values, the function returns
  391. /// decimal or exponential representation.
  392. Foundation_API std::string& floatToStr(std::string& str,
  393. float value,
  394. int precision = -1,
  395. int width = 0,
  396. char thSep = 0,
  397. char decSep = 0);
  398. /// Converts a float value, assigns it to the supplied string and returns the reference.
  399. /// This function calls floatToStr(char*, int, float, int, int) and formats the result according to
  400. /// precision (total number of digits after the decimal point, -1 means ignore precision argument)
  401. /// and width (total length of formatted string).
  402. Foundation_API void doubleToStr(char* buffer,
  403. int bufferSize,
  404. double value,
  405. int lowDec = -std::numeric_limits<double>::digits10,
  406. int highDec = std::numeric_limits<double>::digits10);
  407. /// Converts a double value to string. Converted string must be shorter than bufferSize.
  408. /// Conversion is done by computing the shortest string of digits that correctly represents
  409. /// the input number. Depending on lowDec and highDec values, the function returns
  410. /// decimal or exponential representation.
  411. Foundation_API std::string& doubleToStr(std::string& str,
  412. double value,
  413. int precision = -1,
  414. int width = 0,
  415. char thSep = 0,
  416. char decSep = 0);
  417. /// Converts a double value, assigns it to the supplied string and returns the reference.
  418. /// This function calls doubleToStr(char*, int, float, int, int) and formats the result according to
  419. /// precision (total number of digits after the decimal point, -1 means ignore precision argument)
  420. /// and width (total length of formatted string).
  421. Foundation_API float strToFloat(const char* str);
  422. /// Converts the string of characters into single-precision floating point number.
  423. /// Function uses double_convesrion::DoubleToStringConverter to do the conversion.
  424. Foundation_API bool strToFloat(const std::string&, float& result, char decSep = '.', char thSep = ',');
  425. /// Converts the string of characters into single-precision floating point number.
  426. /// The conversion result is assigned to the result parameter.
  427. /// If decimal separator and/or thousand separator are different from defaults, they should be
  428. /// supplied to ensure proper conversion.
  429. ///
  430. /// Returns true if succesful, false otherwise.
  431. Foundation_API double strToDouble(const char* str);
  432. /// Converts the string of characters into double-precision floating point number.
  433. Foundation_API bool strToDouble(const std::string& str, double& result, char decSep = '.', char thSep = ',');
  434. /// Converts the string of characters into double-precision floating point number.
  435. /// The conversion result is assigned to the result parameter.
  436. /// If decimal separator and/or thousand separator are different from defaults, they should be
  437. /// supplied to ensure proper conversion.
  438. ///
  439. /// Returns true if succesful, false otherwise.
  440. //
  441. // end double-conversion functions declarations
  442. //
  443. } // namespace Poco
  444. #endif // Foundation_NumericString_INCLUDED