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