1
// Protocol Buffers - Google's data interchange format
2
// Copyright 2008 Google Inc. All rights reserved.
3
// http://code.google.com/p/protobuf/
5
// Redistribution and use in source and binary forms, with or without
6
// modification, are permitted provided that the following conditions are
9
// * Redistributions of source code must retain the above copyright
10
// notice, this list of conditions and the following disclaimer.
11
// * Redistributions in binary form must reproduce the above
12
// copyright notice, this list of conditions and the following disclaimer
13
// in the documentation and/or other materials provided with the
15
// * Neither the name of Google Inc. nor the names of its
16
// contributors may be used to endorse or promote products derived from
17
// this software without specific prior written permission.
19
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
// from google3/strings/strutil.cc
33
#include <google/protobuf/stubs/strutil.h>
35
#include <float.h> // FLT_DIG and DBL_DIG
42
// MSVC has only _snprintf, not snprintf.
44
// MinGW has both snprintf and _snprintf, but they appear to be different
45
// functions. The former is buggy. When invoked like so:
47
// snprintf(buffer, 32, "%.*g\n", FLT_DIG, 1.23e10f);
48
// it prints "1.23000e+10". This is plainly wrong: %g should never print
49
// trailing zeros after the decimal point. For some reason this bug only
50
// occurs with some input values, not all. In any case, _snprintf does the
51
// right thing, so we use it.
52
#define snprintf _snprintf
58
inline bool IsNaN(double value) {
59
// NaN is never equal to anything, even itself.
60
return value != value;
63
// These are defined as macros on some platforms. #undef them so that we can
68
// The definitions of these in ctype.h change based on locale. Since our
69
// string manipulation is all in relation to the protocol buffer and C++
70
// languages, we always want to use the C locale. So, we re-define these
71
// exactly as we want them.
72
inline bool isxdigit(char c) {
73
return ('0' <= c && c <= '9') ||
74
('a' <= c && c <= 'f') ||
75
('A' <= c && c <= 'F');
78
inline bool isprint(char c) {
79
return c >= 0x20 && c <= 0x7E;
82
// ----------------------------------------------------------------------
84
// Replaces any occurrence of the character 'remove' (or the characters
85
// in 'remove') with the character 'replacewith'.
86
// ----------------------------------------------------------------------
87
void StripString(string* s, const char* remove, char replacewith) {
88
const char * str_start = s->c_str();
89
const char * str = str_start;
90
for (str = strpbrk(str, remove);
92
str = strpbrk(str + 1, remove)) {
93
(*s)[str - str_start] = replacewith;
97
// ----------------------------------------------------------------------
99
// Replace the "old" pattern with the "new" pattern in a string,
100
// and append the result to "res". If replace_all is false,
101
// it only replaces the first instance of "old."
102
// ----------------------------------------------------------------------
104
void StringReplace(const string& s, const string& oldsub,
105
const string& newsub, bool replace_all,
107
if (oldsub.empty()) {
108
res->append(s); // if empty, append the given string.
112
string::size_type start_pos = 0;
113
string::size_type pos;
115
pos = s.find(oldsub, start_pos);
116
if (pos == string::npos) {
119
res->append(s, start_pos, pos - start_pos);
121
start_pos = pos + oldsub.size(); // start searching again after the "old"
122
} while (replace_all);
123
res->append(s, start_pos, s.length() - start_pos);
126
// ----------------------------------------------------------------------
128
// Give me a string and two patterns "old" and "new", and I replace
129
// the first instance of "old" in the string with "new", if it
130
// exists. If "global" is true; call this repeatedly until it
131
// fails. RETURN a new string, regardless of whether the replacement
133
// ----------------------------------------------------------------------
135
string StringReplace(const string& s, const string& oldsub,
136
const string& newsub, bool replace_all) {
138
StringReplace(s, oldsub, newsub, replace_all, &ret);
142
// ----------------------------------------------------------------------
143
// SplitStringUsing()
144
// Split a string using a character delimiter. Append the components
147
// Note: For multi-character delimiters, this routine will split on *ANY* of
148
// the characters in the string, not the entire string as a single delimiter.
149
// ----------------------------------------------------------------------
150
template <typename ITR>
152
void SplitStringToIteratorUsing(const string& full,
155
// Optimize the common case where delim is a single character.
156
if (delim[0] != '\0' && delim[1] == '\0') {
158
const char* p = full.data();
159
const char* end = p + full.size();
164
const char* start = p;
165
while (++p != end && *p != c);
166
*result++ = string(start, p - start);
172
string::size_type begin_index, end_index;
173
begin_index = full.find_first_not_of(delim);
174
while (begin_index != string::npos) {
175
end_index = full.find_first_of(delim, begin_index);
176
if (end_index == string::npos) {
177
*result++ = full.substr(begin_index);
180
*result++ = full.substr(begin_index, (end_index - begin_index));
181
begin_index = full.find_first_not_of(delim, end_index);
185
void SplitStringUsing(const string& full,
187
vector<string>* result) {
188
back_insert_iterator< vector<string> > it(*result);
189
SplitStringToIteratorUsing(full, delim, it);
192
// ----------------------------------------------------------------------
194
// This merges a vector of string components with delim inserted
195
// as separaters between components.
197
// ----------------------------------------------------------------------
198
template <class ITERATOR>
199
static void JoinStringsIterator(const ITERATOR& start,
203
GOOGLE_CHECK(result != NULL);
205
int delim_length = strlen(delim);
207
// Precompute resulting length so we can reserve() memory in one shot.
209
for (ITERATOR iter = start; iter != end; ++iter) {
211
length += delim_length;
213
length += iter->size();
215
result->reserve(length);
217
// Now combine everything.
218
for (ITERATOR iter = start; iter != end; ++iter) {
220
result->append(delim, delim_length);
222
result->append(iter->data(), iter->size());
226
void JoinStrings(const vector<string>& components,
229
JoinStringsIterator(components.begin(), components.end(), delim, result);
232
// ----------------------------------------------------------------------
233
// UnescapeCEscapeSequences()
234
// This does all the unescaping that C does: \ooo, \r, \n, etc
235
// Returns length of resulting string.
236
// The implementation of \x parses any positive number of hex digits,
237
// but it is an error if the value requires more than 8 bits, and the
238
// result is truncated to 8 bits.
240
// The second call stores its errors in a supplied string vector.
241
// If the string vector pointer is NULL, it reports the errors with LOG().
242
// ----------------------------------------------------------------------
244
#define IS_OCTAL_DIGIT(c) (((c) >= '0') && ((c) <= '7'))
246
inline int hex_digit_to_int(char c) {
248
assert('0' == 0x30 && 'A' == 0x41 && 'a' == 0x61);
250
int x = static_cast<unsigned char>(c);
257
// Protocol buffers doesn't ever care about errors, but I don't want to remove
259
#define LOG_STRING(LEVEL, VECTOR) GOOGLE_LOG_IF(LEVEL, false)
261
int UnescapeCEscapeSequences(const char* source, char* dest) {
262
return UnescapeCEscapeSequences(source, dest, NULL);
265
int UnescapeCEscapeSequences(const char* source, char* dest,
266
vector<string> *errors) {
267
GOOGLE_DCHECK(errors == NULL) << "Error reporting not implemented.";
270
const char* p = source;
272
// Small optimization for case where source = dest and there's no escaping
273
while ( p == d && *p != '\0' && *p != '\\' )
280
switch ( *++p ) { // skip past the '\\'
282
LOG_STRING(ERROR, errors) << "String cannot end with \\";
284
return d - dest; // we're done with p
285
case 'a': *d++ = '\a'; break;
286
case 'b': *d++ = '\b'; break;
287
case 'f': *d++ = '\f'; break;
288
case 'n': *d++ = '\n'; break;
289
case 'r': *d++ = '\r'; break;
290
case 't': *d++ = '\t'; break;
291
case 'v': *d++ = '\v'; break;
292
case '\\': *d++ = '\\'; break;
293
case '?': *d++ = '\?'; break; // \? Who knew?
294
case '\'': *d++ = '\''; break;
295
case '"': *d++ = '\"'; break;
296
case '0': case '1': case '2': case '3': // octal digit: 1 to 3 digits
297
case '4': case '5': case '6': case '7': {
299
if ( IS_OCTAL_DIGIT(p[1]) )
300
ch = ch * 8 + *++p - '0';
301
if ( IS_OCTAL_DIGIT(p[1]) ) // safe (and easy) to do this twice
302
ch = ch * 8 + *++p - '0'; // now points at last digit
306
case 'x': case 'X': {
307
if (!isxdigit(p[1])) {
309
LOG_STRING(ERROR, errors) << "String cannot end with \\x";
311
LOG_STRING(ERROR, errors) <<
312
"\\x cannot be followed by non-hex digit: \\" << *p << p[1];
317
const char *hex_start = p;
318
while (isxdigit(p[1])) // arbitrarily many hex digits
319
ch = (ch << 4) + hex_digit_to_int(*++p);
321
LOG_STRING(ERROR, errors) << "Value of " <<
322
"\\" << string(hex_start, p+1-hex_start) << " exceeds 8 bits";
326
#if 0 // TODO(kenton): Support \u and \U? Requires runetochar().
328
// \uhhhh => convert 4 hex digits to UTF-8
330
const char *hex_start = p;
331
for (int i = 0; i < 4; ++i) {
332
if (isxdigit(p[1])) { // Look one char ahead.
333
rune = (rune << 4) + hex_digit_to_int(*++p); // Advance p.
335
LOG_STRING(ERROR, errors)
336
<< "\\u must be followed by 4 hex digits: \\"
337
<< string(hex_start, p+1-hex_start);
341
d += runetochar(d, &rune);
345
// \Uhhhhhhhh => convert 8 hex digits to UTF-8
347
const char *hex_start = p;
348
for (int i = 0; i < 8; ++i) {
349
if (isxdigit(p[1])) { // Look one char ahead.
350
// Don't change rune until we're sure this
351
// is within the Unicode limit, but do advance p.
352
char32 newrune = (rune << 4) + hex_digit_to_int(*++p);
353
if (newrune > 0x10FFFF) {
354
LOG_STRING(ERROR, errors)
356
<< string(hex_start, p + 1 - hex_start)
357
<< " exceeds Unicode limit (0x10FFFF)";
363
LOG_STRING(ERROR, errors)
364
<< "\\U must be followed by 8 hex digits: \\"
365
<< string(hex_start, p+1-hex_start);
369
d += runetochar(d, &rune);
374
LOG_STRING(ERROR, errors) << "Unknown escape sequence: \\" << *p;
376
p++; // read past letter we escaped
383
// ----------------------------------------------------------------------
384
// UnescapeCEscapeString()
385
// This does the same thing as UnescapeCEscapeSequences, but creates
386
// a new string. The caller does not need to worry about allocating
387
// a dest buffer. This should be used for non performance critical
388
// tasks such as printing debug messages. It is safe for src and dest
391
// The second call stores its errors in a supplied string vector.
392
// If the string vector pointer is NULL, it reports the errors with LOG().
394
// In the first and second calls, the length of dest is returned. In the
395
// the third call, the new string is returned.
396
// ----------------------------------------------------------------------
397
int UnescapeCEscapeString(const string& src, string* dest) {
398
return UnescapeCEscapeString(src, dest, NULL);
401
int UnescapeCEscapeString(const string& src, string* dest,
402
vector<string> *errors) {
403
scoped_array<char> unescaped(new char[src.size() + 1]);
404
int len = UnescapeCEscapeSequences(src.c_str(), unescaped.get(), errors);
406
dest->assign(unescaped.get(), len);
410
string UnescapeCEscapeString(const string& src) {
411
scoped_array<char> unescaped(new char[src.size() + 1]);
412
int len = UnescapeCEscapeSequences(src.c_str(), unescaped.get(), NULL);
413
return string(unescaped.get(), len);
416
// ----------------------------------------------------------------------
418
// CHexEscapeString()
419
// Copies 'src' to 'dest', escaping dangerous characters using
420
// C-style escape sequences. This is very useful for preparing query
421
// flags. 'src' and 'dest' should not overlap. The 'Hex' version uses
422
// hexadecimal rather than octal sequences.
423
// Returns the number of bytes written to 'dest' (not including the \0)
424
// or -1 if there was insufficient space.
426
// Currently only \n, \r, \t, ", ', \ and !isprint() chars are escaped.
427
// ----------------------------------------------------------------------
428
int CEscapeInternal(const char* src, int src_len, char* dest,
429
int dest_len, bool use_hex, bool utf8_safe) {
430
const char* src_end = src + src_len;
432
bool last_hex_escape = false; // true if last output char was \xNN
434
for (; src < src_end; src++) {
435
if (dest_len - used < 2) // Need space for two letter escape
438
bool is_hex_escape = false;
440
case '\n': dest[used++] = '\\'; dest[used++] = 'n'; break;
441
case '\r': dest[used++] = '\\'; dest[used++] = 'r'; break;
442
case '\t': dest[used++] = '\\'; dest[used++] = 't'; break;
443
case '\"': dest[used++] = '\\'; dest[used++] = '\"'; break;
444
case '\'': dest[used++] = '\\'; dest[used++] = '\''; break;
445
case '\\': dest[used++] = '\\'; dest[used++] = '\\'; break;
447
// Note that if we emit \xNN and the src character after that is a hex
448
// digit then that digit must be escaped too to prevent it being
449
// interpreted as part of the character code by C.
450
if ((!utf8_safe || static_cast<uint8>(*src) < 0x80) &&
452
(last_hex_escape && isxdigit(*src)))) {
453
if (dest_len - used < 4) // need space for 4 letter escape
455
sprintf(dest + used, (use_hex ? "\\x%02x" : "\\%03o"),
456
static_cast<uint8>(*src));
457
is_hex_escape = use_hex;
460
dest[used++] = *src; break;
463
last_hex_escape = is_hex_escape;
466
if (dest_len - used < 1) // make sure that there is room for \0
469
dest[used] = '\0'; // doesn't count towards return value though
473
int CEscapeString(const char* src, int src_len, char* dest, int dest_len) {
474
return CEscapeInternal(src, src_len, dest, dest_len, false, false);
477
// ----------------------------------------------------------------------
480
// Copies 'src' to result, escaping dangerous characters using
481
// C-style escape sequences. This is very useful for preparing query
482
// flags. 'src' and 'dest' should not overlap. The 'Hex' version
483
// hexadecimal rather than octal sequences.
485
// Currently only \n, \r, \t, ", ', \ and !isprint() chars are escaped.
486
// ----------------------------------------------------------------------
487
string CEscape(const string& src) {
488
const int dest_length = src.size() * 4 + 1; // Maximum possible expansion
489
scoped_array<char> dest(new char[dest_length]);
490
const int len = CEscapeInternal(src.data(), src.size(),
491
dest.get(), dest_length, false, false);
492
GOOGLE_DCHECK_GE(len, 0);
493
return string(dest.get(), len);
498
string Utf8SafeCEscape(const string& src) {
499
const int dest_length = src.size() * 4 + 1; // Maximum possible expansion
500
scoped_array<char> dest(new char[dest_length]);
501
const int len = CEscapeInternal(src.data(), src.size(),
502
dest.get(), dest_length, false, true);
503
GOOGLE_DCHECK_GE(len, 0);
504
return string(dest.get(), len);
507
string CHexEscape(const string& src) {
508
const int dest_length = src.size() * 4 + 1; // Maximum possible expansion
509
scoped_array<char> dest(new char[dest_length]);
510
const int len = CEscapeInternal(src.data(), src.size(),
511
dest.get(), dest_length, true, false);
512
GOOGLE_DCHECK_GE(len, 0);
513
return string(dest.get(), len);
516
} // namespace strings
518
// ----------------------------------------------------------------------
520
// strtou32_adaptor()
521
// Implementation of strto[u]l replacements that have identical
522
// overflow and underflow characteristics for both ILP-32 and LP-64
523
// platforms, including errno preservation in error-free calls.
524
// ----------------------------------------------------------------------
526
int32 strto32_adaptor(const char *nptr, char **endptr, int base) {
527
const int saved_errno = errno;
529
const long result = strtol(nptr, endptr, base);
530
if (errno == ERANGE && result == LONG_MIN) {
532
} else if (errno == ERANGE && result == LONG_MAX) {
534
} else if (errno == 0 && result < kint32min) {
537
} else if (errno == 0 && result > kint32max) {
543
return static_cast<int32>(result);
546
uint32 strtou32_adaptor(const char *nptr, char **endptr, int base) {
547
const int saved_errno = errno;
549
const unsigned long result = strtoul(nptr, endptr, base);
550
if (errno == ERANGE && result == ULONG_MAX) {
552
} else if (errno == 0 && result > kuint32max) {
558
return static_cast<uint32>(result);
561
// ----------------------------------------------------------------------
563
// FastInt64ToBuffer()
565
// FastHex64ToBuffer()
566
// FastHex32ToBuffer()
567
// ----------------------------------------------------------------------
569
// Offset into buffer where FastInt64ToBuffer places the end of string
570
// null character. Also used by FastInt64ToBufferLeft.
571
static const int kFastInt64ToBufferOffset = 21;
573
char *FastInt64ToBuffer(int64 i, char* buffer) {
574
// We could collapse the positive and negative sections, but that
575
// would be slightly slower for positive numbers...
576
// 22 bytes is enough to store -2**64, -18446744073709551616.
577
char* p = buffer + kFastInt64ToBufferOffset;
586
// On different platforms, % and / have different behaviors for
587
// negative numbers, so we need to jump through hoops to make sure
588
// we don't divide negative numbers.
595
// Make sure we aren't at MIN_INT, in which case we can't say i = -i
599
// Undo what we did a moment ago
611
// Offset into buffer where FastInt32ToBuffer places the end of string
612
// null character. Also used by FastInt32ToBufferLeft
613
static const int kFastInt32ToBufferOffset = 11;
615
// Yes, this is a duplicate of FastInt64ToBuffer. But, we need this for the
616
// compiler to generate 32 bit arithmetic instructions. It's much faster, at
617
// least with 32 bit binaries.
618
char *FastInt32ToBuffer(int32 i, char* buffer) {
619
// We could collapse the positive and negative sections, but that
620
// would be slightly slower for positive numbers...
621
// 12 bytes is enough to store -2**32, -4294967296.
622
char* p = buffer + kFastInt32ToBufferOffset;
631
// On different platforms, % and / have different behaviors for
632
// negative numbers, so we need to jump through hoops to make sure
633
// we don't divide negative numbers.
640
// Make sure we aren't at MIN_INT, in which case we can't say i = -i
644
// Undo what we did a moment ago
656
char *FastHexToBuffer(int i, char* buffer) {
657
GOOGLE_CHECK(i >= 0) << "FastHexToBuffer() wants non-negative integers, not " << i;
659
static const char *hexdigits = "0123456789abcdef";
660
char *p = buffer + 21;
663
*p-- = hexdigits[i & 15]; // mod by 16
664
i >>= 4; // divide by 16
669
char *InternalFastHexToBuffer(uint64 value, char* buffer, int num_byte) {
670
static const char *hexdigits = "0123456789abcdef";
671
buffer[num_byte] = '\0';
672
for (int i = num_byte - 1; i >= 0; i--) {
673
buffer[i] = hexdigits[uint32(value) & 0xf];
679
char *FastHex64ToBuffer(uint64 value, char* buffer) {
680
return InternalFastHexToBuffer(value, buffer, 16);
683
char *FastHex32ToBuffer(uint32 value, char* buffer) {
684
return InternalFastHexToBuffer(value, buffer, 8);
687
static inline char* PlaceNum(char* p, int num, char prev_sep) {
688
*p-- = '0' + num % 10;
689
*p-- = '0' + num / 10;
694
// ----------------------------------------------------------------------
695
// FastInt32ToBufferLeft()
696
// FastUInt32ToBufferLeft()
697
// FastInt64ToBufferLeft()
698
// FastUInt64ToBufferLeft()
700
// Like the Fast*ToBuffer() functions above, these are intended for speed.
701
// Unlike the Fast*ToBuffer() functions, however, these functions write
702
// their output to the beginning of the buffer (hence the name, as the
703
// output is left-aligned). The caller is responsible for ensuring that
704
// the buffer has enough space to hold the output.
706
// Returns a pointer to the end of the string (i.e. the null character
707
// terminating the string).
708
// ----------------------------------------------------------------------
710
static const char two_ASCII_digits[100][2] = {
711
{'0','0'}, {'0','1'}, {'0','2'}, {'0','3'}, {'0','4'},
712
{'0','5'}, {'0','6'}, {'0','7'}, {'0','8'}, {'0','9'},
713
{'1','0'}, {'1','1'}, {'1','2'}, {'1','3'}, {'1','4'},
714
{'1','5'}, {'1','6'}, {'1','7'}, {'1','8'}, {'1','9'},
715
{'2','0'}, {'2','1'}, {'2','2'}, {'2','3'}, {'2','4'},
716
{'2','5'}, {'2','6'}, {'2','7'}, {'2','8'}, {'2','9'},
717
{'3','0'}, {'3','1'}, {'3','2'}, {'3','3'}, {'3','4'},
718
{'3','5'}, {'3','6'}, {'3','7'}, {'3','8'}, {'3','9'},
719
{'4','0'}, {'4','1'}, {'4','2'}, {'4','3'}, {'4','4'},
720
{'4','5'}, {'4','6'}, {'4','7'}, {'4','8'}, {'4','9'},
721
{'5','0'}, {'5','1'}, {'5','2'}, {'5','3'}, {'5','4'},
722
{'5','5'}, {'5','6'}, {'5','7'}, {'5','8'}, {'5','9'},
723
{'6','0'}, {'6','1'}, {'6','2'}, {'6','3'}, {'6','4'},
724
{'6','5'}, {'6','6'}, {'6','7'}, {'6','8'}, {'6','9'},
725
{'7','0'}, {'7','1'}, {'7','2'}, {'7','3'}, {'7','4'},
726
{'7','5'}, {'7','6'}, {'7','7'}, {'7','8'}, {'7','9'},
727
{'8','0'}, {'8','1'}, {'8','2'}, {'8','3'}, {'8','4'},
728
{'8','5'}, {'8','6'}, {'8','7'}, {'8','8'}, {'8','9'},
729
{'9','0'}, {'9','1'}, {'9','2'}, {'9','3'}, {'9','4'},
730
{'9','5'}, {'9','6'}, {'9','7'}, {'9','8'}, {'9','9'}
733
char* FastUInt32ToBufferLeft(uint32 u, char* buffer) {
735
const char *ASCII_digits = NULL;
736
// The idea of this implementation is to trim the number of divides to as few
737
// as possible by using multiplication and subtraction rather than mod (%),
738
// and by outputting two digits at a time rather than one.
739
// The huge-number case is first, in the hopes that the compiler will output
740
// that case in one branch-free block of code, and only output conditional
741
// branches into it from below.
742
if (u >= 1000000000) { // >= 1,000,000,000
743
digits = u / 100000000; // 100,000,000
744
ASCII_digits = two_ASCII_digits[digits];
745
buffer[0] = ASCII_digits[0];
746
buffer[1] = ASCII_digits[1];
749
u -= digits * 100000000; // 100,000,000
751
digits = u / 1000000; // 1,000,000
752
ASCII_digits = two_ASCII_digits[digits];
753
buffer[0] = ASCII_digits[0];
754
buffer[1] = ASCII_digits[1];
757
u -= digits * 1000000; // 1,000,000
759
digits = u / 10000; // 10,000
760
ASCII_digits = two_ASCII_digits[digits];
761
buffer[0] = ASCII_digits[0];
762
buffer[1] = ASCII_digits[1];
765
u -= digits * 10000; // 10,000
768
ASCII_digits = two_ASCII_digits[digits];
769
buffer[0] = ASCII_digits[0];
770
buffer[1] = ASCII_digits[1];
776
ASCII_digits = two_ASCII_digits[digits];
777
buffer[0] = ASCII_digits[0];
778
buffer[1] = ASCII_digits[1];
787
if (u >= 10) goto lt100;
788
*buffer++ = '0' + digits;
791
if (u < 10000) { // 10,000
792
if (u >= 1000) goto lt10_000;
794
*buffer++ = '0' + digits;
797
if (u < 1000000) { // 1,000,000
798
if (u >= 100000) goto lt1_000_000;
799
digits = u / 10000; // 10,000
800
*buffer++ = '0' + digits;
803
if (u < 100000000) { // 100,000,000
804
if (u >= 10000000) goto lt100_000_000;
805
digits = u / 1000000; // 1,000,000
806
*buffer++ = '0' + digits;
809
// we already know that u < 1,000,000,000
810
digits = u / 100000000; // 100,000,000
811
*buffer++ = '0' + digits;
812
goto sublt100_000_000;
815
char* FastInt32ToBufferLeft(int32 i, char* buffer) {
821
return FastUInt32ToBufferLeft(u, buffer);
824
char* FastUInt64ToBufferLeft(uint64 u64, char* buffer) {
826
const char *ASCII_digits = NULL;
828
uint32 u = static_cast<uint32>(u64);
829
if (u == u64) return FastUInt32ToBufferLeft(u, buffer);
831
uint64 top_11_digits = u64 / 1000000000;
832
buffer = FastUInt64ToBufferLeft(top_11_digits, buffer);
833
u = u64 - (top_11_digits * 1000000000);
835
digits = u / 10000000; // 10,000,000
836
GOOGLE_DCHECK_LT(digits, 100);
837
ASCII_digits = two_ASCII_digits[digits];
838
buffer[0] = ASCII_digits[0];
839
buffer[1] = ASCII_digits[1];
841
u -= digits * 10000000; // 10,000,000
842
digits = u / 100000; // 100,000
843
ASCII_digits = two_ASCII_digits[digits];
844
buffer[0] = ASCII_digits[0];
845
buffer[1] = ASCII_digits[1];
847
u -= digits * 100000; // 100,000
848
digits = u / 1000; // 1,000
849
ASCII_digits = two_ASCII_digits[digits];
850
buffer[0] = ASCII_digits[0];
851
buffer[1] = ASCII_digits[1];
853
u -= digits * 1000; // 1,000
855
ASCII_digits = two_ASCII_digits[digits];
856
buffer[0] = ASCII_digits[0];
857
buffer[1] = ASCII_digits[1];
861
*buffer++ = '0' + digits;
866
char* FastInt64ToBufferLeft(int64 i, char* buffer) {
872
return FastUInt64ToBufferLeft(u, buffer);
875
// ----------------------------------------------------------------------
877
// Description: converts an integer to a string.
879
// Return value: string
880
// ----------------------------------------------------------------------
882
string SimpleItoa(int i) {
883
char buffer[kFastToBufferSize];
884
return (sizeof(i) == 4) ?
885
FastInt32ToBuffer(i, buffer) :
886
FastInt64ToBuffer(i, buffer);
889
string SimpleItoa(unsigned int i) {
890
char buffer[kFastToBufferSize];
891
return string(buffer, (sizeof(i) == 4) ?
892
FastUInt32ToBufferLeft(i, buffer) :
893
FastUInt64ToBufferLeft(i, buffer));
896
string SimpleItoa(long i) {
897
char buffer[kFastToBufferSize];
898
return (sizeof(i) == 4) ?
899
FastInt32ToBuffer(i, buffer) :
900
FastInt64ToBuffer(i, buffer);
903
string SimpleItoa(unsigned long i) {
904
char buffer[kFastToBufferSize];
905
return string(buffer, (sizeof(i) == 4) ?
906
FastUInt32ToBufferLeft(i, buffer) :
907
FastUInt64ToBufferLeft(i, buffer));
910
string SimpleItoa(long long i) {
911
char buffer[kFastToBufferSize];
912
return (sizeof(i) == 4) ?
913
FastInt32ToBuffer(i, buffer) :
914
FastInt64ToBuffer(i, buffer);
917
string SimpleItoa(unsigned long long i) {
918
char buffer[kFastToBufferSize];
919
return string(buffer, (sizeof(i) == 4) ?
920
FastUInt32ToBufferLeft(i, buffer) :
921
FastUInt64ToBufferLeft(i, buffer));
924
// ----------------------------------------------------------------------
929
// We want to print the value without losing precision, but we also do
930
// not want to print more digits than necessary. This turns out to be
931
// trickier than it sounds. Numbers like 0.2 cannot be represented
932
// exactly in binary. If we print 0.2 with a very large precision,
933
// e.g. "%.50g", we get "0.2000000000000000111022302462515654042363167".
934
// On the other hand, if we set the precision too low, we lose
935
// significant digits when printing numbers that actually need them.
936
// It turns out there is no precision value that does the right thing
939
// Our strategy is to first try printing with a precision that is never
940
// over-precise, then parse the result with strtod() to see if it
941
// matches. If not, we print again with a precision that will always
942
// give a precise result, but may use more digits than necessary.
944
// An arguably better strategy would be to use the algorithm described
945
// in "How to Print Floating-Point Numbers Accurately" by Steele &
946
// White, e.g. as implemented by David M. Gay's dtoa(). It turns out,
947
// however, that the following implementation is about as fast as
948
// DMG's code. Furthermore, DMG's code locks mutexes, which means it
949
// will not scale well on multi-core machines. DMG's code is slightly
950
// more accurate (in that it will never use more digits than
951
// necessary), but this is probably irrelevant for most users.
953
// Rob Pike and Ken Thompson also have an implementation of dtoa() in
954
// third_party/fmt/fltfmt.cc. Their implementation is similar to this
955
// one in that it makes guesses and then uses strtod() to check them.
956
// Their implementation is faster because they use their own code to
957
// generate the digits in the first place rather than use snprintf(),
958
// thus avoiding format string parsing overhead. However, this makes
959
// it considerably more complicated than the following implementation,
960
// and it is embedded in a larger library. If speed turns out to be
961
// an issue, we could re-implement this in terms of their
963
// ----------------------------------------------------------------------
965
string SimpleDtoa(double value) {
966
char buffer[kDoubleToBufferSize];
967
return DoubleToBuffer(value, buffer);
970
string SimpleFtoa(float value) {
971
char buffer[kFloatToBufferSize];
972
return FloatToBuffer(value, buffer);
975
static inline bool IsValidFloatChar(char c) {
976
return ('0' <= c && c <= '9') ||
977
c == 'e' || c == 'E' ||
978
c == '+' || c == '-';
981
void DelocalizeRadix(char* buffer) {
982
// Fast check: if the buffer has a normal decimal point, assume no
983
// translation is needed.
984
if (strchr(buffer, '.') != NULL) return;
986
// Find the first unknown character.
987
while (IsValidFloatChar(*buffer)) ++buffer;
989
if (*buffer == '\0') {
990
// No radix character found.
994
// We are now pointing at the locale-specific radix character. Replace it
999
if (!IsValidFloatChar(*buffer) && *buffer != '\0') {
1000
// It appears the radix was a multi-byte character. We need to remove the
1002
char* target = buffer;
1003
do { ++buffer; } while (!IsValidFloatChar(*buffer) && *buffer != '\0');
1004
memmove(target, buffer, strlen(buffer) + 1);
1008
char* DoubleToBuffer(double value, char* buffer) {
1009
// DBL_DIG is 15 for IEEE-754 doubles, which are used on almost all
1010
// platforms these days. Just in case some system exists where DBL_DIG
1011
// is significantly larger -- and risks overflowing our buffer -- we have
1013
GOOGLE_COMPILE_ASSERT(DBL_DIG < 20, DBL_DIG_is_too_big);
1015
if (value == numeric_limits<double>::infinity()) {
1016
strcpy(buffer, "inf");
1018
} else if (value == -numeric_limits<double>::infinity()) {
1019
strcpy(buffer, "-inf");
1021
} else if (IsNaN(value)) {
1022
strcpy(buffer, "nan");
1026
int snprintf_result =
1027
snprintf(buffer, kDoubleToBufferSize, "%.*g", DBL_DIG, value);
1029
// The snprintf should never overflow because the buffer is significantly
1030
// larger than the precision we asked for.
1031
GOOGLE_DCHECK(snprintf_result > 0 && snprintf_result < kDoubleToBufferSize);
1033
// We need to make parsed_value volatile in order to force the compiler to
1034
// write it out to the stack. Otherwise, it may keep the value in a
1035
// register, and if it does that, it may keep it as a long double instead
1036
// of a double. This long double may have extra bits that make it compare
1037
// unequal to "value" even though it would be exactly equal if it were
1038
// truncated to a double.
1039
volatile double parsed_value = strtod(buffer, NULL);
1040
if (parsed_value != value) {
1041
int snprintf_result =
1042
snprintf(buffer, kDoubleToBufferSize, "%.*g", DBL_DIG+2, value);
1044
// Should never overflow; see above.
1045
GOOGLE_DCHECK(snprintf_result > 0 && snprintf_result < kDoubleToBufferSize);
1048
DelocalizeRadix(buffer);
1052
bool safe_strtof(const char* str, float* value) {
1054
errno = 0; // errno only gets set on errors
1055
#if defined(_WIN32) || defined (__hpux) // has no strtof()
1056
*value = strtod(str, &endptr);
1058
*value = strtof(str, &endptr);
1060
return *str != 0 && *endptr == 0 && errno == 0;
1063
char* FloatToBuffer(float value, char* buffer) {
1064
// FLT_DIG is 6 for IEEE-754 floats, which are used on almost all
1065
// platforms these days. Just in case some system exists where FLT_DIG
1066
// is significantly larger -- and risks overflowing our buffer -- we have
1068
GOOGLE_COMPILE_ASSERT(FLT_DIG < 10, FLT_DIG_is_too_big);
1070
if (value == numeric_limits<double>::infinity()) {
1071
strcpy(buffer, "inf");
1073
} else if (value == -numeric_limits<double>::infinity()) {
1074
strcpy(buffer, "-inf");
1076
} else if (IsNaN(value)) {
1077
strcpy(buffer, "nan");
1081
int snprintf_result =
1082
snprintf(buffer, kFloatToBufferSize, "%.*g", FLT_DIG, value);
1084
// The snprintf should never overflow because the buffer is significantly
1085
// larger than the precision we asked for.
1086
GOOGLE_DCHECK(snprintf_result > 0 && snprintf_result < kFloatToBufferSize);
1089
if (!safe_strtof(buffer, &parsed_value) || parsed_value != value) {
1090
int snprintf_result =
1091
snprintf(buffer, kFloatToBufferSize, "%.*g", FLT_DIG+2, value);
1093
// Should never overflow; see above.
1094
GOOGLE_DCHECK(snprintf_result > 0 && snprintf_result < kFloatToBufferSize);
1097
DelocalizeRadix(buffer);
1101
// ----------------------------------------------------------------------
1103
// This code will make you cry.
1104
// ----------------------------------------------------------------------
1106
// Returns a string identical to *input except that the character pointed to
1107
// by radix_pos (which should be '.') is replaced with the locale-specific
1109
string LocalizeRadix(const char* input, const char* radix_pos) {
1110
// Determine the locale-specific radix character by calling sprintf() to
1111
// print the number 1.5, then stripping off the digits. As far as I can
1112
// tell, this is the only portable, thread-safe way to get the C library
1113
// to divuldge the locale's radix character. No, localeconv() is NOT
1116
int size = sprintf(temp, "%.1f", 1.5);
1117
GOOGLE_CHECK_EQ(temp[0], '1');
1118
GOOGLE_CHECK_EQ(temp[size-1], '5');
1119
GOOGLE_CHECK_LE(size, 6);
1121
// Now replace the '.' in the input with it.
1123
result.reserve(strlen(input) + size - 3);
1124
result.append(input, radix_pos);
1125
result.append(temp + 1, size - 2);
1126
result.append(radix_pos + 1);
1130
double NoLocaleStrtod(const char* text, char** original_endptr) {
1131
// We cannot simply set the locale to "C" temporarily with setlocale()
1132
// as this is not thread-safe. Instead, we try to parse in the current
1133
// locale first. If parsing stops at a '.' character, then this is a
1134
// pretty good hint that we're actually in some other locale in which
1135
// '.' is not the radix character.
1138
double result = strtod(text, &temp_endptr);
1139
if (original_endptr != NULL) *original_endptr = temp_endptr;
1140
if (*temp_endptr != '.') return result;
1142
// Parsing halted on a '.'. Perhaps we're in a different locale? Let's
1143
// try to replace the '.' with a locale-specific radix character and
1145
string localized = LocalizeRadix(text, temp_endptr);
1146
const char* localized_cstr = localized.c_str();
1147
char* localized_endptr;
1148
result = strtod(localized_cstr, &localized_endptr);
1149
if ((localized_endptr - localized_cstr) >
1150
(temp_endptr - text)) {
1151
// This attempt got further, so replacing the decimal must have helped.
1152
// Update original_endptr to point at the right location.
1153
if (original_endptr != NULL) {
1154
// size_diff is non-zero if the localized radix has multiple bytes.
1155
int size_diff = localized.size() - strlen(text);
1156
// const_cast is necessary to match the strtod() interface.
1157
*original_endptr = const_cast<char*>(
1158
text + (localized_endptr - localized_cstr - size_diff));
1165
} // namespace protobuf
1166
} // namespace google