NumericString.h 15 KB

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