1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc. All rights reserved.
3 // https://developers.google.com/protocol-buffers/
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
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
14 // distribution.
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.
18 //
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.
30
31 // from google3/strings/strutil.h
32
33 #ifndef GOOGLE_PROTOBUF_STUBS_STRUTIL_H__
34 #define GOOGLE_PROTOBUF_STUBS_STRUTIL_H__
35
36 #include <stdlib.h>
37 #include <vector>
38 #include <google/protobuf/stubs/common.h>
39 #include <google/protobuf/stubs/stringpiece.h>
40
41 #include <google/protobuf/port_def.inc>
42
43 namespace google {
44 namespace protobuf {
45
46 #if defined(_MSC_VER) && _MSC_VER < 1800
47 #define strtoll _strtoi64
48 #define strtoull _strtoui64
49 #elif defined(__DECCXX) && defined(__osf__)
50 // HP C++ on Tru64 does not have strtoll, but strtol is already 64-bit.
51 #define strtoll strtol
52 #define strtoull strtoul
53 #endif
54
55 // ----------------------------------------------------------------------
56 // ascii_isalnum()
57 // Check if an ASCII character is alphanumeric. We can't use ctype's
58 // isalnum() because it is affected by locale. This function is applied
59 // to identifiers in the protocol buffer language, not to natural-language
60 // strings, so locale should not be taken into account.
61 // ascii_isdigit()
62 // Like above, but only accepts digits.
63 // ascii_isspace()
64 // Check if the character is a space character.
65 // ----------------------------------------------------------------------
66
ascii_isalnum(char c)67 inline bool ascii_isalnum(char c) {
68 return ('a' <= c && c <= 'z') ||
69 ('A' <= c && c <= 'Z') ||
70 ('0' <= c && c <= '9');
71 }
72
ascii_isdigit(char c)73 inline bool ascii_isdigit(char c) {
74 return ('0' <= c && c <= '9');
75 }
76
ascii_isspace(char c)77 inline bool ascii_isspace(char c) {
78 return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' ||
79 c == '\r';
80 }
81
ascii_isupper(char c)82 inline bool ascii_isupper(char c) {
83 return c >= 'A' && c <= 'Z';
84 }
85
ascii_islower(char c)86 inline bool ascii_islower(char c) {
87 return c >= 'a' && c <= 'z';
88 }
89
ascii_toupper(char c)90 inline char ascii_toupper(char c) {
91 return ascii_islower(c) ? c - ('a' - 'A') : c;
92 }
93
ascii_tolower(char c)94 inline char ascii_tolower(char c) {
95 return ascii_isupper(c) ? c + ('a' - 'A') : c;
96 }
97
hex_digit_to_int(char c)98 inline int hex_digit_to_int(char c) {
99 /* Assume ASCII. */
100 int x = static_cast<unsigned char>(c);
101 if (x > '9') {
102 x += 9;
103 }
104 return x & 0xf;
105 }
106
107 // ----------------------------------------------------------------------
108 // HasPrefixString()
109 // Check if a string begins with a given prefix.
110 // StripPrefixString()
111 // Given a string and a putative prefix, returns the string minus the
112 // prefix string if the prefix matches, otherwise the original
113 // string.
114 // ----------------------------------------------------------------------
HasPrefixString(const string & str,const string & prefix)115 inline bool HasPrefixString(const string& str,
116 const string& prefix) {
117 return str.size() >= prefix.size() &&
118 str.compare(0, prefix.size(), prefix) == 0;
119 }
120
StripPrefixString(const string & str,const string & prefix)121 inline string StripPrefixString(const string& str, const string& prefix) {
122 if (HasPrefixString(str, prefix)) {
123 return str.substr(prefix.size());
124 } else {
125 return str;
126 }
127 }
128
129 // ----------------------------------------------------------------------
130 // HasSuffixString()
131 // Return true if str ends in suffix.
132 // StripSuffixString()
133 // Given a string and a putative suffix, returns the string minus the
134 // suffix string if the suffix matches, otherwise the original
135 // string.
136 // ----------------------------------------------------------------------
HasSuffixString(const string & str,const string & suffix)137 inline bool HasSuffixString(const string& str,
138 const string& suffix) {
139 return str.size() >= suffix.size() &&
140 str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
141 }
142
StripSuffixString(const string & str,const string & suffix)143 inline string StripSuffixString(const string& str, const string& suffix) {
144 if (HasSuffixString(str, suffix)) {
145 return str.substr(0, str.size() - suffix.size());
146 } else {
147 return str;
148 }
149 }
150
151 // ----------------------------------------------------------------------
152 // ReplaceCharacters
153 // Replaces any occurrence of the character 'remove' (or the characters
154 // in 'remove') with the character 'replacewith'.
155 // Good for keeping html characters or protocol characters (\t) out
156 // of places where they might cause a problem.
157 // StripWhitespace
158 // Removes whitespaces from both ends of the given string.
159 // ----------------------------------------------------------------------
160 PROTOBUF_EXPORT void ReplaceCharacters(string* s, const char* remove,
161 char replacewith);
162 PROTOBUF_EXPORT void StripString(string* s, const char* remove,
163 char replacewith);
164
165 PROTOBUF_EXPORT void StripWhitespace(string* s);
166
167 // ----------------------------------------------------------------------
168 // LowerString()
169 // UpperString()
170 // ToUpper()
171 // Convert the characters in "s" to lowercase or uppercase. ASCII-only:
172 // these functions intentionally ignore locale because they are applied to
173 // identifiers used in the Protocol Buffer language, not to natural-language
174 // strings.
175 // ----------------------------------------------------------------------
176
LowerString(string * s)177 inline void LowerString(string * s) {
178 string::iterator end = s->end();
179 for (string::iterator i = s->begin(); i != end; ++i) {
180 // tolower() changes based on locale. We don't want this!
181 if ('A' <= *i && *i <= 'Z') *i += 'a' - 'A';
182 }
183 }
184
UpperString(string * s)185 inline void UpperString(string * s) {
186 string::iterator end = s->end();
187 for (string::iterator i = s->begin(); i != end; ++i) {
188 // toupper() changes based on locale. We don't want this!
189 if ('a' <= *i && *i <= 'z') *i += 'A' - 'a';
190 }
191 }
192
ToUpper(const string & s)193 inline string ToUpper(const string& s) {
194 string out = s;
195 UpperString(&out);
196 return out;
197 }
198
199 // ----------------------------------------------------------------------
200 // StringReplace()
201 // Give me a string and two patterns "old" and "new", and I replace
202 // the first instance of "old" in the string with "new", if it
203 // exists. RETURN a new string, regardless of whether the replacement
204 // happened or not.
205 // ----------------------------------------------------------------------
206
207 PROTOBUF_EXPORT string StringReplace(const string& s, const string& oldsub,
208 const string& newsub, bool replace_all);
209
210 // ----------------------------------------------------------------------
211 // SplitStringUsing()
212 // Split a string using a character delimiter. Append the components
213 // to 'result'. If there are consecutive delimiters, this function skips
214 // over all of them.
215 // ----------------------------------------------------------------------
216 PROTOBUF_EXPORT void SplitStringUsing(const string& full, const char* delim,
217 std::vector<string>* res);
218
219 // Split a string using one or more byte delimiters, presented
220 // as a nul-terminated c string. Append the components to 'result'.
221 // If there are consecutive delimiters, this function will return
222 // corresponding empty strings. If you want to drop the empty
223 // strings, try SplitStringUsing().
224 //
225 // If "full" is the empty string, yields an empty string as the only value.
226 // ----------------------------------------------------------------------
227 PROTOBUF_EXPORT void SplitStringAllowEmpty(const string& full,
228 const char* delim,
229 std::vector<string>* result);
230
231 // ----------------------------------------------------------------------
232 // Split()
233 // Split a string using a character delimiter.
234 // ----------------------------------------------------------------------
235 inline std::vector<string> Split(
236 const string& full, const char* delim, bool skip_empty = true) {
237 std::vector<string> result;
238 if (skip_empty) {
239 SplitStringUsing(full, delim, &result);
240 } else {
241 SplitStringAllowEmpty(full, delim, &result);
242 }
243 return result;
244 }
245
246 // ----------------------------------------------------------------------
247 // JoinStrings()
248 // These methods concatenate a vector of strings into a C++ string, using
249 // the C-string "delim" as a separator between components. There are two
250 // flavors of the function, one flavor returns the concatenated string,
251 // another takes a pointer to the target string. In the latter case the
252 // target string is cleared and overwritten.
253 // ----------------------------------------------------------------------
254 PROTOBUF_EXPORT void JoinStrings(const std::vector<string>& components,
255 const char* delim, string* result);
256
JoinStrings(const std::vector<string> & components,const char * delim)257 inline string JoinStrings(const std::vector<string>& components,
258 const char* delim) {
259 string result;
260 JoinStrings(components, delim, &result);
261 return result;
262 }
263
264 // ----------------------------------------------------------------------
265 // UnescapeCEscapeSequences()
266 // Copies "source" to "dest", rewriting C-style escape sequences
267 // -- '\n', '\r', '\\', '\ooo', etc -- to their ASCII
268 // equivalents. "dest" must be sufficiently large to hold all
269 // the characters in the rewritten string (i.e. at least as large
270 // as strlen(source) + 1 should be safe, since the replacements
271 // are always shorter than the original escaped sequences). It's
272 // safe for source and dest to be the same. RETURNS the length
273 // of dest.
274 //
275 // It allows hex sequences \xhh, or generally \xhhhhh with an
276 // arbitrary number of hex digits, but all of them together must
277 // specify a value of a single byte (e.g. \x0045 is equivalent
278 // to \x45, and \x1234 is erroneous).
279 //
280 // It also allows escape sequences of the form \uhhhh (exactly four
281 // hex digits, upper or lower case) or \Uhhhhhhhh (exactly eight
282 // hex digits, upper or lower case) to specify a Unicode code
283 // point. The dest array will contain the UTF8-encoded version of
284 // that code-point (e.g., if source contains \u2019, then dest will
285 // contain the three bytes 0xE2, 0x80, and 0x99).
286 //
287 // Errors: In the first form of the call, errors are reported with
288 // LOG(ERROR). The same is true for the second form of the call if
289 // the pointer to the string std::vector is nullptr; otherwise, error
290 // messages are stored in the std::vector. In either case, the effect on
291 // the dest array is not defined, but rest of the source will be
292 // processed.
293 // ----------------------------------------------------------------------
294
295 PROTOBUF_EXPORT int UnescapeCEscapeSequences(const char* source, char* dest);
296 PROTOBUF_EXPORT int UnescapeCEscapeSequences(const char* source, char* dest,
297 std::vector<string>* errors);
298
299 // ----------------------------------------------------------------------
300 // UnescapeCEscapeString()
301 // This does the same thing as UnescapeCEscapeSequences, but creates
302 // a new string. The caller does not need to worry about allocating
303 // a dest buffer. This should be used for non performance critical
304 // tasks such as printing debug messages. It is safe for src and dest
305 // to be the same.
306 //
307 // The second call stores its errors in a supplied string vector.
308 // If the string vector pointer is nullptr, it reports the errors with LOG().
309 //
310 // In the first and second calls, the length of dest is returned. In the
311 // the third call, the new string is returned.
312 // ----------------------------------------------------------------------
313
314 PROTOBUF_EXPORT int UnescapeCEscapeString(const string& src, string* dest);
315 PROTOBUF_EXPORT int UnescapeCEscapeString(const string& src, string* dest,
316 std::vector<string>* errors);
317 PROTOBUF_EXPORT string UnescapeCEscapeString(const string& src);
318
319 // ----------------------------------------------------------------------
320 // CEscape()
321 // Escapes 'src' using C-style escape sequences and returns the resulting
322 // string.
323 //
324 // Escaped chars: \n, \r, \t, ", ', \, and !isprint().
325 // ----------------------------------------------------------------------
326 PROTOBUF_EXPORT string CEscape(const string& src);
327
328 // ----------------------------------------------------------------------
329 // CEscapeAndAppend()
330 // Escapes 'src' using C-style escape sequences, and appends the escaped
331 // string to 'dest'.
332 // ----------------------------------------------------------------------
333 PROTOBUF_EXPORT void CEscapeAndAppend(StringPiece src, string* dest);
334
335 namespace strings {
336 // Like CEscape() but does not escape bytes with the upper bit set.
337 PROTOBUF_EXPORT string Utf8SafeCEscape(const string& src);
338
339 // Like CEscape() but uses hex (\x) escapes instead of octals.
340 PROTOBUF_EXPORT string CHexEscape(const string& src);
341 } // namespace strings
342
343 // ----------------------------------------------------------------------
344 // strto32()
345 // strtou32()
346 // strto64()
347 // strtou64()
348 // Architecture-neutral plug compatible replacements for strtol() and
349 // strtoul(). Long's have different lengths on ILP-32 and LP-64
350 // platforms, so using these is safer, from the point of view of
351 // overflow behavior, than using the standard libc functions.
352 // ----------------------------------------------------------------------
353 PROTOBUF_EXPORT int32 strto32_adaptor(const char* nptr, char** endptr,
354 int base);
355 PROTOBUF_EXPORT uint32 strtou32_adaptor(const char* nptr, char** endptr,
356 int base);
357
strto32(const char * nptr,char ** endptr,int base)358 inline int32 strto32(const char *nptr, char **endptr, int base) {
359 if (sizeof(int32) == sizeof(long))
360 return strtol(nptr, endptr, base);
361 else
362 return strto32_adaptor(nptr, endptr, base);
363 }
364
strtou32(const char * nptr,char ** endptr,int base)365 inline uint32 strtou32(const char *nptr, char **endptr, int base) {
366 if (sizeof(uint32) == sizeof(unsigned long))
367 return strtoul(nptr, endptr, base);
368 else
369 return strtou32_adaptor(nptr, endptr, base);
370 }
371
372 // For now, long long is 64-bit on all the platforms we care about, so these
373 // functions can simply pass the call to strto[u]ll.
strto64(const char * nptr,char ** endptr,int base)374 inline int64 strto64(const char *nptr, char **endptr, int base) {
375 GOOGLE_COMPILE_ASSERT(sizeof(int64) == sizeof(long long),
376 sizeof_int64_is_not_sizeof_long_long);
377 return strtoll(nptr, endptr, base);
378 }
379
strtou64(const char * nptr,char ** endptr,int base)380 inline uint64 strtou64(const char *nptr, char **endptr, int base) {
381 GOOGLE_COMPILE_ASSERT(sizeof(uint64) == sizeof(unsigned long long),
382 sizeof_uint64_is_not_sizeof_long_long);
383 return strtoull(nptr, endptr, base);
384 }
385
386 // ----------------------------------------------------------------------
387 // safe_strtob()
388 // safe_strto32()
389 // safe_strtou32()
390 // safe_strto64()
391 // safe_strtou64()
392 // safe_strtof()
393 // safe_strtod()
394 // ----------------------------------------------------------------------
395 PROTOBUF_EXPORT bool safe_strtob(StringPiece str, bool* value);
396
397 PROTOBUF_EXPORT bool safe_strto32(const string& str, int32* value);
398 PROTOBUF_EXPORT bool safe_strtou32(const string& str, uint32* value);
safe_strto32(const char * str,int32 * value)399 inline bool safe_strto32(const char* str, int32* value) {
400 return safe_strto32(string(str), value);
401 }
safe_strto32(StringPiece str,int32 * value)402 inline bool safe_strto32(StringPiece str, int32* value) {
403 return safe_strto32(str.ToString(), value);
404 }
safe_strtou32(const char * str,uint32 * value)405 inline bool safe_strtou32(const char* str, uint32* value) {
406 return safe_strtou32(string(str), value);
407 }
safe_strtou32(StringPiece str,uint32 * value)408 inline bool safe_strtou32(StringPiece str, uint32* value) {
409 return safe_strtou32(str.ToString(), value);
410 }
411
412 PROTOBUF_EXPORT bool safe_strto64(const string& str, int64* value);
413 PROTOBUF_EXPORT bool safe_strtou64(const string& str, uint64* value);
safe_strto64(const char * str,int64 * value)414 inline bool safe_strto64(const char* str, int64* value) {
415 return safe_strto64(string(str), value);
416 }
safe_strto64(StringPiece str,int64 * value)417 inline bool safe_strto64(StringPiece str, int64* value) {
418 return safe_strto64(str.ToString(), value);
419 }
safe_strtou64(const char * str,uint64 * value)420 inline bool safe_strtou64(const char* str, uint64* value) {
421 return safe_strtou64(string(str), value);
422 }
safe_strtou64(StringPiece str,uint64 * value)423 inline bool safe_strtou64(StringPiece str, uint64* value) {
424 return safe_strtou64(str.ToString(), value);
425 }
426
427 PROTOBUF_EXPORT bool safe_strtof(const char* str, float* value);
428 PROTOBUF_EXPORT bool safe_strtod(const char* str, double* value);
safe_strtof(const string & str,float * value)429 inline bool safe_strtof(const string& str, float* value) {
430 return safe_strtof(str.c_str(), value);
431 }
safe_strtod(const string & str,double * value)432 inline bool safe_strtod(const string& str, double* value) {
433 return safe_strtod(str.c_str(), value);
434 }
safe_strtof(StringPiece str,float * value)435 inline bool safe_strtof(StringPiece str, float* value) {
436 return safe_strtof(str.ToString(), value);
437 }
safe_strtod(StringPiece str,double * value)438 inline bool safe_strtod(StringPiece str, double* value) {
439 return safe_strtod(str.ToString(), value);
440 }
441
442 // ----------------------------------------------------------------------
443 // FastIntToBuffer()
444 // FastHexToBuffer()
445 // FastHex64ToBuffer()
446 // FastHex32ToBuffer()
447 // FastTimeToBuffer()
448 // These are intended for speed. FastIntToBuffer() assumes the
449 // integer is non-negative. FastHexToBuffer() puts output in
450 // hex rather than decimal. FastTimeToBuffer() puts the output
451 // into RFC822 format.
452 //
453 // FastHex64ToBuffer() puts a 64-bit unsigned value in hex-format,
454 // padded to exactly 16 bytes (plus one byte for '\0')
455 //
456 // FastHex32ToBuffer() puts a 32-bit unsigned value in hex-format,
457 // padded to exactly 8 bytes (plus one byte for '\0')
458 //
459 // All functions take the output buffer as an arg.
460 // They all return a pointer to the beginning of the output,
461 // which may not be the beginning of the input buffer.
462 // ----------------------------------------------------------------------
463
464 // Suggested buffer size for FastToBuffer functions. Also works with
465 // DoubleToBuffer() and FloatToBuffer().
466 static const int kFastToBufferSize = 32;
467
468 PROTOBUF_EXPORT char* FastInt32ToBuffer(int32 i, char* buffer);
469 PROTOBUF_EXPORT char* FastInt64ToBuffer(int64 i, char* buffer);
470 char* FastUInt32ToBuffer(uint32 i, char* buffer); // inline below
471 char* FastUInt64ToBuffer(uint64 i, char* buffer); // inline below
472 PROTOBUF_EXPORT char* FastHexToBuffer(int i, char* buffer);
473 PROTOBUF_EXPORT char* FastHex64ToBuffer(uint64 i, char* buffer);
474 PROTOBUF_EXPORT char* FastHex32ToBuffer(uint32 i, char* buffer);
475
476 // at least 22 bytes long
FastIntToBuffer(int i,char * buffer)477 inline char* FastIntToBuffer(int i, char* buffer) {
478 return (sizeof(i) == 4 ?
479 FastInt32ToBuffer(i, buffer) : FastInt64ToBuffer(i, buffer));
480 }
FastUIntToBuffer(unsigned int i,char * buffer)481 inline char* FastUIntToBuffer(unsigned int i, char* buffer) {
482 return (sizeof(i) == 4 ?
483 FastUInt32ToBuffer(i, buffer) : FastUInt64ToBuffer(i, buffer));
484 }
FastLongToBuffer(long i,char * buffer)485 inline char* FastLongToBuffer(long i, char* buffer) {
486 return (sizeof(i) == 4 ?
487 FastInt32ToBuffer(i, buffer) : FastInt64ToBuffer(i, buffer));
488 }
FastULongToBuffer(unsigned long i,char * buffer)489 inline char* FastULongToBuffer(unsigned long i, char* buffer) {
490 return (sizeof(i) == 4 ?
491 FastUInt32ToBuffer(i, buffer) : FastUInt64ToBuffer(i, buffer));
492 }
493
494 // ----------------------------------------------------------------------
495 // FastInt32ToBufferLeft()
496 // FastUInt32ToBufferLeft()
497 // FastInt64ToBufferLeft()
498 // FastUInt64ToBufferLeft()
499 //
500 // Like the Fast*ToBuffer() functions above, these are intended for speed.
501 // Unlike the Fast*ToBuffer() functions, however, these functions write
502 // their output to the beginning of the buffer (hence the name, as the
503 // output is left-aligned). The caller is responsible for ensuring that
504 // the buffer has enough space to hold the output.
505 //
506 // Returns a pointer to the end of the string (i.e. the null character
507 // terminating the string).
508 // ----------------------------------------------------------------------
509
510 PROTOBUF_EXPORT char* FastInt32ToBufferLeft(int32 i, char* buffer);
511 PROTOBUF_EXPORT char* FastUInt32ToBufferLeft(uint32 i, char* buffer);
512 PROTOBUF_EXPORT char* FastInt64ToBufferLeft(int64 i, char* buffer);
513 PROTOBUF_EXPORT char* FastUInt64ToBufferLeft(uint64 i, char* buffer);
514
515 // Just define these in terms of the above.
FastUInt32ToBuffer(uint32 i,char * buffer)516 inline char* FastUInt32ToBuffer(uint32 i, char* buffer) {
517 FastUInt32ToBufferLeft(i, buffer);
518 return buffer;
519 }
FastUInt64ToBuffer(uint64 i,char * buffer)520 inline char* FastUInt64ToBuffer(uint64 i, char* buffer) {
521 FastUInt64ToBufferLeft(i, buffer);
522 return buffer;
523 }
524
SimpleBtoa(bool value)525 inline string SimpleBtoa(bool value) {
526 return value ? "true" : "false";
527 }
528
529 // ----------------------------------------------------------------------
530 // SimpleItoa()
531 // Description: converts an integer to a string.
532 //
533 // Return value: string
534 // ----------------------------------------------------------------------
535 PROTOBUF_EXPORT string SimpleItoa(int i);
536 PROTOBUF_EXPORT string SimpleItoa(unsigned int i);
537 PROTOBUF_EXPORT string SimpleItoa(long i);
538 PROTOBUF_EXPORT string SimpleItoa(unsigned long i);
539 PROTOBUF_EXPORT string SimpleItoa(long long i);
540 PROTOBUF_EXPORT string SimpleItoa(unsigned long long i);
541
542 // ----------------------------------------------------------------------
543 // SimpleDtoa()
544 // SimpleFtoa()
545 // DoubleToBuffer()
546 // FloatToBuffer()
547 // Description: converts a double or float to a string which, if
548 // passed to NoLocaleStrtod(), will produce the exact same original double
549 // (except in case of NaN; all NaNs are considered the same value).
550 // We try to keep the string short but it's not guaranteed to be as
551 // short as possible.
552 //
553 // DoubleToBuffer() and FloatToBuffer() write the text to the given
554 // buffer and return it. The buffer must be at least
555 // kDoubleToBufferSize bytes for doubles and kFloatToBufferSize
556 // bytes for floats. kFastToBufferSize is also guaranteed to be large
557 // enough to hold either.
558 //
559 // Return value: string
560 // ----------------------------------------------------------------------
561 PROTOBUF_EXPORT string SimpleDtoa(double value);
562 PROTOBUF_EXPORT string SimpleFtoa(float value);
563
564 PROTOBUF_EXPORT char* DoubleToBuffer(double i, char* buffer);
565 PROTOBUF_EXPORT char* FloatToBuffer(float i, char* buffer);
566
567 // In practice, doubles should never need more than 24 bytes and floats
568 // should never need more than 14 (including null terminators), but we
569 // overestimate to be safe.
570 static const int kDoubleToBufferSize = 32;
571 static const int kFloatToBufferSize = 24;
572
573 namespace strings {
574
575 enum PadSpec {
576 NO_PAD = 1,
577 ZERO_PAD_2,
578 ZERO_PAD_3,
579 ZERO_PAD_4,
580 ZERO_PAD_5,
581 ZERO_PAD_6,
582 ZERO_PAD_7,
583 ZERO_PAD_8,
584 ZERO_PAD_9,
585 ZERO_PAD_10,
586 ZERO_PAD_11,
587 ZERO_PAD_12,
588 ZERO_PAD_13,
589 ZERO_PAD_14,
590 ZERO_PAD_15,
591 ZERO_PAD_16,
592 };
593
594 struct Hex {
595 uint64 value;
596 enum PadSpec spec;
597 template <class Int>
598 explicit Hex(Int v, PadSpec s = NO_PAD)
specHex599 : spec(s) {
600 // Prevent sign-extension by casting integers to
601 // their unsigned counterparts.
602 #ifdef LANG_CXX11
603 static_assert(
604 sizeof(v) == 1 || sizeof(v) == 2 || sizeof(v) == 4 || sizeof(v) == 8,
605 "Unknown integer type");
606 #endif
607 value = sizeof(v) == 1 ? static_cast<uint8>(v)
608 : sizeof(v) == 2 ? static_cast<uint16>(v)
609 : sizeof(v) == 4 ? static_cast<uint32>(v)
610 : static_cast<uint64>(v);
611 }
612 };
613
614 struct PROTOBUF_EXPORT AlphaNum {
615 const char *piece_data_; // move these to string_ref eventually
616 size_t piece_size_; // move these to string_ref eventually
617
618 char digits[kFastToBufferSize];
619
620 // No bool ctor -- bools convert to an integral type.
621 // A bool ctor would also convert incoming pointers (bletch).
622
AlphaNumAlphaNum623 AlphaNum(int i32)
624 : piece_data_(digits),
625 piece_size_(FastInt32ToBufferLeft(i32, digits) - &digits[0]) {}
AlphaNumAlphaNum626 AlphaNum(unsigned int u32)
627 : piece_data_(digits),
628 piece_size_(FastUInt32ToBufferLeft(u32, digits) - &digits[0]) {}
AlphaNumAlphaNum629 AlphaNum(long long i64)
630 : piece_data_(digits),
631 piece_size_(FastInt64ToBufferLeft(i64, digits) - &digits[0]) {}
AlphaNumAlphaNum632 AlphaNum(unsigned long long u64)
633 : piece_data_(digits),
634 piece_size_(FastUInt64ToBufferLeft(u64, digits) - &digits[0]) {}
635
636 // Note: on some architectures, "long" is only 32 bits, not 64, but the
637 // performance hit of using FastInt64ToBufferLeft to handle 32-bit values
638 // is quite minor.
AlphaNumAlphaNum639 AlphaNum(long i64)
640 : piece_data_(digits),
641 piece_size_(FastInt64ToBufferLeft(i64, digits) - &digits[0]) {}
AlphaNumAlphaNum642 AlphaNum(unsigned long u64)
643 : piece_data_(digits),
644 piece_size_(FastUInt64ToBufferLeft(u64, digits) - &digits[0]) {}
645
AlphaNumAlphaNum646 AlphaNum(float f)
647 : piece_data_(digits), piece_size_(strlen(FloatToBuffer(f, digits))) {}
AlphaNumAlphaNum648 AlphaNum(double f)
649 : piece_data_(digits), piece_size_(strlen(DoubleToBuffer(f, digits))) {}
650
651 AlphaNum(Hex hex);
652
AlphaNumAlphaNum653 AlphaNum(const char* c_str)
654 : piece_data_(c_str), piece_size_(strlen(c_str)) {}
655 // TODO: Add a string_ref constructor, eventually
656 // AlphaNum(const StringPiece &pc) : piece(pc) {}
657
AlphaNumAlphaNum658 AlphaNum(const string& str)
659 : piece_data_(str.data()), piece_size_(str.size()) {}
660
AlphaNumAlphaNum661 AlphaNum(StringPiece str)
662 : piece_data_(str.data()), piece_size_(str.size()) {}
663
AlphaNumAlphaNum664 AlphaNum(internal::StringPiecePod str)
665 : piece_data_(str.data()), piece_size_(str.size()) {}
666
sizeAlphaNum667 size_t size() const { return piece_size_; }
dataAlphaNum668 const char *data() const { return piece_data_; }
669
670 private:
671 // Use ":" not ':'
672 AlphaNum(char c); // NOLINT(runtime/explicit)
673
674 // Disallow copy and assign.
675 AlphaNum(const AlphaNum&);
676 void operator=(const AlphaNum&);
677 };
678
679 } // namespace strings
680
681 using strings::AlphaNum;
682
683 // ----------------------------------------------------------------------
684 // StrCat()
685 // This merges the given strings or numbers, with no delimiter. This
686 // is designed to be the fastest possible way to construct a string out
687 // of a mix of raw C strings, strings, bool values,
688 // and numeric values.
689 //
690 // Don't use this for user-visible strings. The localization process
691 // works poorly on strings built up out of fragments.
692 //
693 // For clarity and performance, don't use StrCat when appending to a
694 // string. In particular, avoid using any of these (anti-)patterns:
695 // str.append(StrCat(...)
696 // str += StrCat(...)
697 // str = StrCat(str, ...)
698 // where the last is the worse, with the potential to change a loop
699 // from a linear time operation with O(1) dynamic allocations into a
700 // quadratic time operation with O(n) dynamic allocations. StrAppend
701 // is a better choice than any of the above, subject to the restriction
702 // of StrAppend(&str, a, b, c, ...) that none of the a, b, c, ... may
703 // be a reference into str.
704 // ----------------------------------------------------------------------
705
706 PROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b);
707 PROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b,
708 const AlphaNum& c);
709 PROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b,
710 const AlphaNum& c, const AlphaNum& d);
711 PROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b,
712 const AlphaNum& c, const AlphaNum& d,
713 const AlphaNum& e);
714 PROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b,
715 const AlphaNum& c, const AlphaNum& d,
716 const AlphaNum& e, const AlphaNum& f);
717 PROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b,
718 const AlphaNum& c, const AlphaNum& d,
719 const AlphaNum& e, const AlphaNum& f,
720 const AlphaNum& g);
721 PROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b,
722 const AlphaNum& c, const AlphaNum& d,
723 const AlphaNum& e, const AlphaNum& f,
724 const AlphaNum& g, const AlphaNum& h);
725 PROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b,
726 const AlphaNum& c, const AlphaNum& d,
727 const AlphaNum& e, const AlphaNum& f,
728 const AlphaNum& g, const AlphaNum& h,
729 const AlphaNum& i);
730
StrCat(const AlphaNum & a)731 inline string StrCat(const AlphaNum& a) { return string(a.data(), a.size()); }
732
733 // ----------------------------------------------------------------------
734 // StrAppend()
735 // Same as above, but adds the output to the given string.
736 // WARNING: For speed, StrAppend does not try to check each of its input
737 // arguments to be sure that they are not a subset of the string being
738 // appended to. That is, while this will work:
739 //
740 // string s = "foo";
741 // s += s;
742 //
743 // This will not (necessarily) work:
744 //
745 // string s = "foo";
746 // StrAppend(&s, s);
747 //
748 // Note: while StrCat supports appending up to 9 arguments, StrAppend
749 // is currently limited to 4. That's rarely an issue except when
750 // automatically transforming StrCat to StrAppend, and can easily be
751 // worked around as consecutive calls to StrAppend are quite efficient.
752 // ----------------------------------------------------------------------
753
754 PROTOBUF_EXPORT void StrAppend(string* dest, const AlphaNum& a);
755 PROTOBUF_EXPORT void StrAppend(string* dest, const AlphaNum& a,
756 const AlphaNum& b);
757 PROTOBUF_EXPORT void StrAppend(string* dest, const AlphaNum& a,
758 const AlphaNum& b, const AlphaNum& c);
759 PROTOBUF_EXPORT void StrAppend(string* dest, const AlphaNum& a,
760 const AlphaNum& b, const AlphaNum& c,
761 const AlphaNum& d);
762
763 // ----------------------------------------------------------------------
764 // Join()
765 // These methods concatenate a range of components into a C++ string, using
766 // the C-string "delim" as a separator between components.
767 // ----------------------------------------------------------------------
768 template <typename Iterator>
Join(Iterator start,Iterator end,const char * delim,string * result)769 void Join(Iterator start, Iterator end,
770 const char* delim, string* result) {
771 for (Iterator it = start; it != end; ++it) {
772 if (it != start) {
773 result->append(delim);
774 }
775 StrAppend(result, *it);
776 }
777 }
778
779 template <typename Range>
Join(const Range & components,const char * delim)780 string Join(const Range& components,
781 const char* delim) {
782 string result;
783 Join(components.begin(), components.end(), delim, &result);
784 return result;
785 }
786
787 // ----------------------------------------------------------------------
788 // ToHex()
789 // Return a lower-case hex string representation of the given integer.
790 // ----------------------------------------------------------------------
791 PROTOBUF_EXPORT string ToHex(uint64 num);
792
793 // ----------------------------------------------------------------------
794 // GlobalReplaceSubstring()
795 // Replaces all instances of a substring in a string. Does nothing
796 // if 'substring' is empty. Returns the number of replacements.
797 //
798 // NOTE: The string pieces must not overlap s.
799 // ----------------------------------------------------------------------
800 PROTOBUF_EXPORT int GlobalReplaceSubstring(const string& substring,
801 const string& replacement,
802 string* s);
803
804 // ----------------------------------------------------------------------
805 // Base64Unescape()
806 // Converts "src" which is encoded in Base64 to its binary equivalent and
807 // writes it to "dest". If src contains invalid characters, dest is cleared
808 // and the function returns false. Returns true on success.
809 // ----------------------------------------------------------------------
810 PROTOBUF_EXPORT bool Base64Unescape(StringPiece src, string* dest);
811
812 // ----------------------------------------------------------------------
813 // WebSafeBase64Unescape()
814 // This is a variation of Base64Unescape which uses '-' instead of '+', and
815 // '_' instead of '/'. src is not null terminated, instead specify len. I
816 // recommend that slen<szdest, but we honor szdest anyway.
817 // RETURNS the length of dest, or -1 if src contains invalid chars.
818
819 // The variation that stores into a string clears the string first, and
820 // returns false (with dest empty) if src contains invalid chars; for
821 // this version src and dest must be different strings.
822 // ----------------------------------------------------------------------
823 PROTOBUF_EXPORT int WebSafeBase64Unescape(const char* src, int slen, char* dest,
824 int szdest);
825 PROTOBUF_EXPORT bool WebSafeBase64Unescape(StringPiece src, string* dest);
826
827 // Return the length to use for the output buffer given to the base64 escape
828 // routines. Make sure to use the same value for do_padding in both.
829 // This function may return incorrect results if given input_len values that
830 // are extremely high, which should happen rarely.
831 PROTOBUF_EXPORT int CalculateBase64EscapedLen(int input_len, bool do_padding);
832 // Use this version when calling Base64Escape without a do_padding arg.
833 PROTOBUF_EXPORT int CalculateBase64EscapedLen(int input_len);
834
835 // ----------------------------------------------------------------------
836 // Base64Escape()
837 // WebSafeBase64Escape()
838 // Encode "src" to "dest" using base64 encoding.
839 // src is not null terminated, instead specify len.
840 // 'dest' should have at least CalculateBase64EscapedLen() length.
841 // RETURNS the length of dest.
842 // The WebSafe variation use '-' instead of '+' and '_' instead of '/'
843 // so that we can place the out in the URL or cookies without having
844 // to escape them. It also has an extra parameter "do_padding",
845 // which when set to false will prevent padding with "=".
846 // ----------------------------------------------------------------------
847 PROTOBUF_EXPORT int Base64Escape(const unsigned char* src, int slen, char* dest,
848 int szdest);
849 PROTOBUF_EXPORT int WebSafeBase64Escape(const unsigned char* src, int slen,
850 char* dest, int szdest,
851 bool do_padding);
852 // Encode src into dest with padding.
853 PROTOBUF_EXPORT void Base64Escape(StringPiece src, string* dest);
854 // Encode src into dest web-safely without padding.
855 PROTOBUF_EXPORT void WebSafeBase64Escape(StringPiece src, string* dest);
856 // Encode src into dest web-safely with padding.
857 PROTOBUF_EXPORT void WebSafeBase64EscapeWithPadding(StringPiece src,
858 string* dest);
859
860 PROTOBUF_EXPORT void Base64Escape(const unsigned char* src, int szsrc,
861 string* dest, bool do_padding);
862 PROTOBUF_EXPORT void WebSafeBase64Escape(const unsigned char* src, int szsrc,
863 string* dest, bool do_padding);
864
IsValidCodePoint(uint32 code_point)865 inline bool IsValidCodePoint(uint32 code_point) {
866 return code_point < 0xD800 ||
867 (code_point >= 0xE000 && code_point <= 0x10FFFF);
868 }
869
870 static const int UTFmax = 4;
871 // ----------------------------------------------------------------------
872 // EncodeAsUTF8Char()
873 // Helper to append a Unicode code point to a string as UTF8, without bringing
874 // in any external dependencies. The output buffer must be as least 4 bytes
875 // large.
876 // ----------------------------------------------------------------------
877 PROTOBUF_EXPORT int EncodeAsUTF8Char(uint32 code_point, char* output);
878
879 // ----------------------------------------------------------------------
880 // UTF8FirstLetterNumBytes()
881 // Length of the first UTF-8 character.
882 // ----------------------------------------------------------------------
883 PROTOBUF_EXPORT int UTF8FirstLetterNumBytes(const char* src, int len);
884
885 // From google3/third_party/absl/strings/escaping.h
886
887 // ----------------------------------------------------------------------
888 // CleanStringLineEndings()
889 // Clean up a multi-line string to conform to Unix line endings.
890 // Reads from src and appends to dst, so usually dst should be empty.
891 //
892 // If there is no line ending at the end of a non-empty string, it can
893 // be added automatically.
894 //
895 // Four different types of input are correctly handled:
896 //
897 // - Unix/Linux files: line ending is LF: pass through unchanged
898 //
899 // - DOS/Windows files: line ending is CRLF: convert to LF
900 //
901 // - Legacy Mac files: line ending is CR: convert to LF
902 //
903 // - Garbled files: random line endings: convert gracefully
904 // lonely CR, lonely LF, CRLF: convert to LF
905 //
906 // @param src The multi-line string to convert
907 // @param dst The converted string is appended to this string
908 // @param auto_end_last_line Automatically terminate the last line
909 //
910 // Limitations:
911 //
912 // This does not do the right thing for CRCRLF files created by
913 // broken programs that do another Unix->DOS conversion on files
914 // that are already in CRLF format. For this, a two-pass approach
915 // brute-force would be needed that
916 //
917 // (1) determines the presence of LF (first one is ok)
918 // (2) if yes, removes any CR, else convert every CR to LF
919 PROTOBUF_EXPORT void CleanStringLineEndings(const string& src, string* dst,
920 bool auto_end_last_line);
921
922 // Same as above, but transforms the argument in place.
923 PROTOBUF_EXPORT void CleanStringLineEndings(string* str,
924 bool auto_end_last_line);
925
926 namespace strings {
EndsWith(StringPiece text,StringPiece suffix)927 inline bool EndsWith(StringPiece text, StringPiece suffix) {
928 return suffix.empty() ||
929 (text.size() >= suffix.size() &&
930 memcmp(text.data() + (text.size() - suffix.size()), suffix.data(),
931 suffix.size()) == 0);
932 }
933 } // namespace strings
934
935 } // namespace protobuf
936 } // namespace google
937
938 #include <google/protobuf/port_undef.inc>
939
940 #endif // GOOGLE_PROTOBUF_STUBS_STRUTIL_H__
941