blob: 920701ebfc9bf5f6e89534c4bb6e747970869a38 [file] [log] [blame]
temporal40ee5512008-07-10 02:12:20 +00001// Protocol Buffers - Google's data interchange format
kenton@google.com24bf56f2008-09-24 20:31:01 +00002// Copyright 2008 Google Inc. All rights reserved.
Feng Xiaoe4288622014-10-01 16:26:23 -07003// https://developers.google.com/protocol-buffers/
temporal40ee5512008-07-10 02:12:20 +00004//
kenton@google.com24bf56f2008-09-24 20:31:01 +00005// Redistribution and use in source and binary forms, with or without
6// modification, are permitted provided that the following conditions are
7// met:
temporal40ee5512008-07-10 02:12:20 +00008//
kenton@google.com24bf56f2008-09-24 20:31:01 +00009// * 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.
temporal40ee5512008-07-10 02:12:20 +000018//
kenton@google.com24bf56f2008-09-24 20:31:01 +000019// 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.
temporal40ee5512008-07-10 02:12:20 +000030
31// from google3/strings/strutil.h
32
33#ifndef GOOGLE_PROTOBUF_STUBS_STRUTIL_H__
34#define GOOGLE_PROTOBUF_STUBS_STRUTIL_H__
35
kenton@google.com3aa7a0d2009-08-17 20:34:29 +000036#include <stdlib.h>
temporal40ee5512008-07-10 02:12:20 +000037#include <vector>
38#include <google/protobuf/stubs/common.h>
39
40namespace google {
41namespace protobuf {
42
43#ifdef _MSC_VER
44#define strtoll _strtoi64
45#define strtoull _strtoui64
kenton@google.coma2a32c22008-11-14 17:29:32 +000046#elif defined(__DECCXX) && defined(__osf__)
47// HP C++ on Tru64 does not have strtoll, but strtol is already 64-bit.
48#define strtoll strtol
49#define strtoull strtoul
temporal40ee5512008-07-10 02:12:20 +000050#endif
51
52// ----------------------------------------------------------------------
53// ascii_isalnum()
54// Check if an ASCII character is alphanumeric. We can't use ctype's
55// isalnum() because it is affected by locale. This function is applied
56// to identifiers in the protocol buffer language, not to natural-language
57// strings, so locale should not be taken into account.
58// ascii_isdigit()
59// Like above, but only accepts digits.
Feng Xiao6ef984a2014-11-10 17:34:54 -080060// ascii_isspace()
61// Check if the character is a space character.
temporal40ee5512008-07-10 02:12:20 +000062// ----------------------------------------------------------------------
63
64inline bool ascii_isalnum(char c) {
65 return ('a' <= c && c <= 'z') ||
66 ('A' <= c && c <= 'Z') ||
67 ('0' <= c && c <= '9');
68}
69
70inline bool ascii_isdigit(char c) {
71 return ('0' <= c && c <= '9');
72}
73
Feng Xiao6ef984a2014-11-10 17:34:54 -080074inline bool ascii_isspace(char c) {
75 return c == ' ';
76}
77
temporal40ee5512008-07-10 02:12:20 +000078// ----------------------------------------------------------------------
79// HasPrefixString()
80// Check if a string begins with a given prefix.
81// StripPrefixString()
82// Given a string and a putative prefix, returns the string minus the
83// prefix string if the prefix matches, otherwise the original
84// string.
85// ----------------------------------------------------------------------
86inline bool HasPrefixString(const string& str,
87 const string& prefix) {
88 return str.size() >= prefix.size() &&
89 str.compare(0, prefix.size(), prefix) == 0;
90}
91
92inline string StripPrefixString(const string& str, const string& prefix) {
93 if (HasPrefixString(str, prefix)) {
94 return str.substr(prefix.size());
95 } else {
96 return str;
97 }
98}
99
100// ----------------------------------------------------------------------
101// HasSuffixString()
102// Return true if str ends in suffix.
103// StripSuffixString()
104// Given a string and a putative suffix, returns the string minus the
105// suffix string if the suffix matches, otherwise the original
106// string.
107// ----------------------------------------------------------------------
108inline bool HasSuffixString(const string& str,
109 const string& suffix) {
110 return str.size() >= suffix.size() &&
111 str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
112}
113
114inline string StripSuffixString(const string& str, const string& suffix) {
115 if (HasSuffixString(str, suffix)) {
116 return str.substr(0, str.size() - suffix.size());
117 } else {
118 return str;
119 }
120}
121
122// ----------------------------------------------------------------------
123// StripString
124// Replaces any occurrence of the character 'remove' (or the characters
125// in 'remove') with the character 'replacewith'.
126// Good for keeping html characters or protocol characters (\t) out
127// of places where they might cause a problem.
Feng Xiao6ef984a2014-11-10 17:34:54 -0800128// StripWhitespace
129// Removes whitespaces from both ends of the given string.
temporal40ee5512008-07-10 02:12:20 +0000130// ----------------------------------------------------------------------
131LIBPROTOBUF_EXPORT void StripString(string* s, const char* remove,
132 char replacewith);
133
Feng Xiao6ef984a2014-11-10 17:34:54 -0800134LIBPROTOBUF_EXPORT void StripWhitespace(string* s);
135
136
temporal40ee5512008-07-10 02:12:20 +0000137// ----------------------------------------------------------------------
138// LowerString()
139// UpperString()
jieluo@google.com4de8f552014-07-18 00:47:59 +0000140// ToUpper()
temporal40ee5512008-07-10 02:12:20 +0000141// Convert the characters in "s" to lowercase or uppercase. ASCII-only:
142// these functions intentionally ignore locale because they are applied to
143// identifiers used in the Protocol Buffer language, not to natural-language
144// strings.
145// ----------------------------------------------------------------------
146
147inline void LowerString(string * s) {
148 string::iterator end = s->end();
149 for (string::iterator i = s->begin(); i != end; ++i) {
150 // tolower() changes based on locale. We don't want this!
151 if ('A' <= *i && *i <= 'Z') *i += 'a' - 'A';
152 }
153}
154
155inline void UpperString(string * s) {
156 string::iterator end = s->end();
157 for (string::iterator i = s->begin(); i != end; ++i) {
158 // toupper() changes based on locale. We don't want this!
159 if ('a' <= *i && *i <= 'z') *i += 'A' - 'a';
160 }
161}
162
jieluo@google.com4de8f552014-07-18 00:47:59 +0000163inline string ToUpper(const string& s) {
164 string out = s;
165 UpperString(&out);
166 return out;
167}
168
temporal40ee5512008-07-10 02:12:20 +0000169// ----------------------------------------------------------------------
170// StringReplace()
171// Give me a string and two patterns "old" and "new", and I replace
172// the first instance of "old" in the string with "new", if it
173// exists. RETURN a new string, regardless of whether the replacement
174// happened or not.
175// ----------------------------------------------------------------------
176
177LIBPROTOBUF_EXPORT string StringReplace(const string& s, const string& oldsub,
178 const string& newsub, bool replace_all);
179
180// ----------------------------------------------------------------------
181// SplitStringUsing()
182// Split a string using a character delimiter. Append the components
183// to 'result'. If there are consecutive delimiters, this function skips
184// over all of them.
185// ----------------------------------------------------------------------
186LIBPROTOBUF_EXPORT void SplitStringUsing(const string& full, const char* delim,
187 vector<string>* res);
188
xiaofeng@google.comb55a20f2012-09-22 02:40:50 +0000189// Split a string using one or more byte delimiters, presented
190// as a nul-terminated c string. Append the components to 'result'.
191// If there are consecutive delimiters, this function will return
192// corresponding empty strings. If you want to drop the empty
193// strings, try SplitStringUsing().
194//
195// If "full" is the empty string, yields an empty string as the only value.
196// ----------------------------------------------------------------------
197LIBPROTOBUF_EXPORT void SplitStringAllowEmpty(const string& full,
198 const char* delim,
199 vector<string>* result);
200
temporal40ee5512008-07-10 02:12:20 +0000201// ----------------------------------------------------------------------
jieluo@google.com4de8f552014-07-18 00:47:59 +0000202// Split()
203// Split a string using a character delimiter.
204// ----------------------------------------------------------------------
205inline vector<string> Split(
206 const string& full, const char* delim, bool skip_empty = true) {
207 vector<string> result;
208 if (skip_empty) {
209 SplitStringUsing(full, delim, &result);
210 } else {
211 SplitStringAllowEmpty(full, delim, &result);
212 }
213 return result;
214}
215
216// ----------------------------------------------------------------------
temporal40ee5512008-07-10 02:12:20 +0000217// JoinStrings()
218// These methods concatenate a vector of strings into a C++ string, using
219// the C-string "delim" as a separator between components. There are two
220// flavors of the function, one flavor returns the concatenated string,
221// another takes a pointer to the target string. In the latter case the
222// target string is cleared and overwritten.
223// ----------------------------------------------------------------------
224LIBPROTOBUF_EXPORT void JoinStrings(const vector<string>& components,
225 const char* delim, string* result);
226
227inline string JoinStrings(const vector<string>& components,
228 const char* delim) {
229 string result;
230 JoinStrings(components, delim, &result);
231 return result;
232}
233
234// ----------------------------------------------------------------------
235// UnescapeCEscapeSequences()
236// Copies "source" to "dest", rewriting C-style escape sequences
237// -- '\n', '\r', '\\', '\ooo', etc -- to their ASCII
238// equivalents. "dest" must be sufficiently large to hold all
239// the characters in the rewritten string (i.e. at least as large
240// as strlen(source) + 1 should be safe, since the replacements
241// are always shorter than the original escaped sequences). It's
242// safe for source and dest to be the same. RETURNS the length
243// of dest.
244//
245// It allows hex sequences \xhh, or generally \xhhhhh with an
246// arbitrary number of hex digits, but all of them together must
247// specify a value of a single byte (e.g. \x0045 is equivalent
248// to \x45, and \x1234 is erroneous).
249//
250// It also allows escape sequences of the form \uhhhh (exactly four
251// hex digits, upper or lower case) or \Uhhhhhhhh (exactly eight
252// hex digits, upper or lower case) to specify a Unicode code
253// point. The dest array will contain the UTF8-encoded version of
254// that code-point (e.g., if source contains \u2019, then dest will
kenton@google.com20363742010-02-10 00:13:33 +0000255// contain the three bytes 0xE2, 0x80, and 0x99).
temporal40ee5512008-07-10 02:12:20 +0000256//
257// Errors: In the first form of the call, errors are reported with
258// LOG(ERROR). The same is true for the second form of the call if
259// the pointer to the string vector is NULL; otherwise, error
260// messages are stored in the vector. In either case, the effect on
261// the dest array is not defined, but rest of the source will be
262// processed.
263// ----------------------------------------------------------------------
264
265LIBPROTOBUF_EXPORT int UnescapeCEscapeSequences(const char* source, char* dest);
266LIBPROTOBUF_EXPORT int UnescapeCEscapeSequences(const char* source, char* dest,
267 vector<string> *errors);
268
269// ----------------------------------------------------------------------
270// UnescapeCEscapeString()
271// This does the same thing as UnescapeCEscapeSequences, but creates
272// a new string. The caller does not need to worry about allocating
273// a dest buffer. This should be used for non performance critical
274// tasks such as printing debug messages. It is safe for src and dest
275// to be the same.
276//
277// The second call stores its errors in a supplied string vector.
278// If the string vector pointer is NULL, it reports the errors with LOG().
279//
280// In the first and second calls, the length of dest is returned. In the
281// the third call, the new string is returned.
282// ----------------------------------------------------------------------
283
284LIBPROTOBUF_EXPORT int UnescapeCEscapeString(const string& src, string* dest);
285LIBPROTOBUF_EXPORT int UnescapeCEscapeString(const string& src, string* dest,
286 vector<string> *errors);
287LIBPROTOBUF_EXPORT string UnescapeCEscapeString(const string& src);
288
289// ----------------------------------------------------------------------
290// CEscapeString()
291// Copies 'src' to 'dest', escaping dangerous characters using
292// C-style escape sequences. This is very useful for preparing query
293// flags. 'src' and 'dest' should not overlap.
294// Returns the number of bytes written to 'dest' (not including the \0)
295// or -1 if there was insufficient space.
296//
297// Currently only \n, \r, \t, ", ', \ and !isprint() chars are escaped.
298// ----------------------------------------------------------------------
299LIBPROTOBUF_EXPORT int CEscapeString(const char* src, int src_len,
300 char* dest, int dest_len);
301
302// ----------------------------------------------------------------------
303// CEscape()
304// More convenient form of CEscapeString: returns result as a "string".
305// This version is slower than CEscapeString() because it does more
306// allocation. However, it is much more convenient to use in
307// non-speed-critical code like logging messages etc.
308// ----------------------------------------------------------------------
309LIBPROTOBUF_EXPORT string CEscape(const string& src);
310
kenton@google.comfccb1462009-12-18 02:11:36 +0000311namespace strings {
312// Like CEscape() but does not escape bytes with the upper bit set.
313LIBPROTOBUF_EXPORT string Utf8SafeCEscape(const string& src);
314
315// Like CEscape() but uses hex (\x) escapes instead of octals.
316LIBPROTOBUF_EXPORT string CHexEscape(const string& src);
317} // namespace strings
318
temporal40ee5512008-07-10 02:12:20 +0000319// ----------------------------------------------------------------------
320// strto32()
321// strtou32()
322// strto64()
323// strtou64()
324// Architecture-neutral plug compatible replacements for strtol() and
325// strtoul(). Long's have different lengths on ILP-32 and LP-64
326// platforms, so using these is safer, from the point of view of
327// overflow behavior, than using the standard libc functions.
328// ----------------------------------------------------------------------
329LIBPROTOBUF_EXPORT int32 strto32_adaptor(const char *nptr, char **endptr,
330 int base);
331LIBPROTOBUF_EXPORT uint32 strtou32_adaptor(const char *nptr, char **endptr,
332 int base);
333
334inline int32 strto32(const char *nptr, char **endptr, int base) {
335 if (sizeof(int32) == sizeof(long))
336 return strtol(nptr, endptr, base);
337 else
338 return strto32_adaptor(nptr, endptr, base);
339}
340
341inline uint32 strtou32(const char *nptr, char **endptr, int base) {
342 if (sizeof(uint32) == sizeof(unsigned long))
343 return strtoul(nptr, endptr, base);
344 else
345 return strtou32_adaptor(nptr, endptr, base);
346}
347
348// For now, long long is 64-bit on all the platforms we care about, so these
349// functions can simply pass the call to strto[u]ll.
350inline int64 strto64(const char *nptr, char **endptr, int base) {
351 GOOGLE_COMPILE_ASSERT(sizeof(int64) == sizeof(long long),
352 sizeof_int64_is_not_sizeof_long_long);
353 return strtoll(nptr, endptr, base);
354}
355
356inline uint64 strtou64(const char *nptr, char **endptr, int base) {
357 GOOGLE_COMPILE_ASSERT(sizeof(uint64) == sizeof(unsigned long long),
358 sizeof_uint64_is_not_sizeof_long_long);
359 return strtoull(nptr, endptr, base);
360}
361
362// ----------------------------------------------------------------------
jieluo@google.com4de8f552014-07-18 00:47:59 +0000363// safe_strto32()
364// ----------------------------------------------------------------------
365LIBPROTOBUF_EXPORT bool safe_int(string text, int32* value_p);
366
367inline bool safe_strto32(string text, int32* value) {
368 return safe_int(text, value);
369}
370
371// ----------------------------------------------------------------------
temporal40ee5512008-07-10 02:12:20 +0000372// FastIntToBuffer()
373// FastHexToBuffer()
374// FastHex64ToBuffer()
375// FastHex32ToBuffer()
376// FastTimeToBuffer()
377// These are intended for speed. FastIntToBuffer() assumes the
378// integer is non-negative. FastHexToBuffer() puts output in
379// hex rather than decimal. FastTimeToBuffer() puts the output
380// into RFC822 format.
381//
382// FastHex64ToBuffer() puts a 64-bit unsigned value in hex-format,
383// padded to exactly 16 bytes (plus one byte for '\0')
384//
385// FastHex32ToBuffer() puts a 32-bit unsigned value in hex-format,
386// padded to exactly 8 bytes (plus one byte for '\0')
387//
388// All functions take the output buffer as an arg.
389// They all return a pointer to the beginning of the output,
390// which may not be the beginning of the input buffer.
391// ----------------------------------------------------------------------
392
393// Suggested buffer size for FastToBuffer functions. Also works with
394// DoubleToBuffer() and FloatToBuffer().
395static const int kFastToBufferSize = 32;
396
397LIBPROTOBUF_EXPORT char* FastInt32ToBuffer(int32 i, char* buffer);
398LIBPROTOBUF_EXPORT char* FastInt64ToBuffer(int64 i, char* buffer);
399char* FastUInt32ToBuffer(uint32 i, char* buffer); // inline below
400char* FastUInt64ToBuffer(uint64 i, char* buffer); // inline below
401LIBPROTOBUF_EXPORT char* FastHexToBuffer(int i, char* buffer);
402LIBPROTOBUF_EXPORT char* FastHex64ToBuffer(uint64 i, char* buffer);
403LIBPROTOBUF_EXPORT char* FastHex32ToBuffer(uint32 i, char* buffer);
404
405// at least 22 bytes long
406inline char* FastIntToBuffer(int i, char* buffer) {
407 return (sizeof(i) == 4 ?
408 FastInt32ToBuffer(i, buffer) : FastInt64ToBuffer(i, buffer));
409}
410inline char* FastUIntToBuffer(unsigned int i, char* buffer) {
411 return (sizeof(i) == 4 ?
412 FastUInt32ToBuffer(i, buffer) : FastUInt64ToBuffer(i, buffer));
413}
414inline char* FastLongToBuffer(long i, char* buffer) {
415 return (sizeof(i) == 4 ?
416 FastInt32ToBuffer(i, buffer) : FastInt64ToBuffer(i, buffer));
417}
418inline char* FastULongToBuffer(unsigned long i, char* buffer) {
419 return (sizeof(i) == 4 ?
420 FastUInt32ToBuffer(i, buffer) : FastUInt64ToBuffer(i, buffer));
421}
422
423// ----------------------------------------------------------------------
424// FastInt32ToBufferLeft()
425// FastUInt32ToBufferLeft()
426// FastInt64ToBufferLeft()
427// FastUInt64ToBufferLeft()
428//
429// Like the Fast*ToBuffer() functions above, these are intended for speed.
430// Unlike the Fast*ToBuffer() functions, however, these functions write
431// their output to the beginning of the buffer (hence the name, as the
432// output is left-aligned). The caller is responsible for ensuring that
433// the buffer has enough space to hold the output.
434//
435// Returns a pointer to the end of the string (i.e. the null character
436// terminating the string).
437// ----------------------------------------------------------------------
438
439LIBPROTOBUF_EXPORT char* FastInt32ToBufferLeft(int32 i, char* buffer);
440LIBPROTOBUF_EXPORT char* FastUInt32ToBufferLeft(uint32 i, char* buffer);
441LIBPROTOBUF_EXPORT char* FastInt64ToBufferLeft(int64 i, char* buffer);
442LIBPROTOBUF_EXPORT char* FastUInt64ToBufferLeft(uint64 i, char* buffer);
443
444// Just define these in terms of the above.
445inline char* FastUInt32ToBuffer(uint32 i, char* buffer) {
446 FastUInt32ToBufferLeft(i, buffer);
447 return buffer;
448}
449inline char* FastUInt64ToBuffer(uint64 i, char* buffer) {
450 FastUInt64ToBufferLeft(i, buffer);
451 return buffer;
452}
453
454// ----------------------------------------------------------------------
455// SimpleItoa()
456// Description: converts an integer to a string.
457//
458// Return value: string
459// ----------------------------------------------------------------------
460LIBPROTOBUF_EXPORT string SimpleItoa(int i);
461LIBPROTOBUF_EXPORT string SimpleItoa(unsigned int i);
462LIBPROTOBUF_EXPORT string SimpleItoa(long i);
463LIBPROTOBUF_EXPORT string SimpleItoa(unsigned long i);
464LIBPROTOBUF_EXPORT string SimpleItoa(long long i);
465LIBPROTOBUF_EXPORT string SimpleItoa(unsigned long long i);
466
467// ----------------------------------------------------------------------
468// SimpleDtoa()
469// SimpleFtoa()
470// DoubleToBuffer()
471// FloatToBuffer()
472// Description: converts a double or float to a string which, if
473// passed to NoLocaleStrtod(), will produce the exact same original double
474// (except in case of NaN; all NaNs are considered the same value).
475// We try to keep the string short but it's not guaranteed to be as
476// short as possible.
477//
478// DoubleToBuffer() and FloatToBuffer() write the text to the given
479// buffer and return it. The buffer must be at least
480// kDoubleToBufferSize bytes for doubles and kFloatToBufferSize
481// bytes for floats. kFastToBufferSize is also guaranteed to be large
482// enough to hold either.
483//
484// Return value: string
485// ----------------------------------------------------------------------
486LIBPROTOBUF_EXPORT string SimpleDtoa(double value);
487LIBPROTOBUF_EXPORT string SimpleFtoa(float value);
488
489LIBPROTOBUF_EXPORT char* DoubleToBuffer(double i, char* buffer);
490LIBPROTOBUF_EXPORT char* FloatToBuffer(float i, char* buffer);
491
492// In practice, doubles should never need more than 24 bytes and floats
493// should never need more than 14 (including null terminators), but we
494// overestimate to be safe.
495static const int kDoubleToBufferSize = 32;
496static const int kFloatToBufferSize = 24;
497
Jisi Liu885b6122015-02-28 14:51:22 -0800498namespace strings {
temporal40ee5512008-07-10 02:12:20 +0000499
Jisi Liu885b6122015-02-28 14:51:22 -0800500struct Hex {
501 uint64 value;
502 enum PadSpec {
503 NONE = 1,
504 ZERO_PAD_2,
505 ZERO_PAD_3,
506 ZERO_PAD_4,
507 ZERO_PAD_5,
508 ZERO_PAD_6,
509 ZERO_PAD_7,
510 ZERO_PAD_8,
511 ZERO_PAD_9,
512 ZERO_PAD_10,
513 ZERO_PAD_11,
514 ZERO_PAD_12,
515 ZERO_PAD_13,
516 ZERO_PAD_14,
517 ZERO_PAD_15,
518 ZERO_PAD_16,
519 } spec;
520 template <class Int>
521 explicit Hex(Int v, PadSpec s = NONE)
522 : spec(s) {
523 // Prevent sign-extension by casting integers to
524 // their unsigned counterparts.
525#ifdef LANG_CXX11
526 static_assert(
527 sizeof(v) == 1 || sizeof(v) == 2 || sizeof(v) == 4 || sizeof(v) == 8,
528 "Unknown integer type");
529#endif
530 value = sizeof(v) == 1 ? static_cast<uint8>(v)
531 : sizeof(v) == 2 ? static_cast<uint16>(v)
532 : sizeof(v) == 4 ? static_cast<uint32>(v)
533 : static_cast<uint64>(v);
534 }
535};
536
537struct AlphaNum {
538 const char *piece_data_; // move these to string_ref eventually
539 size_t piece_size_; // move these to string_ref eventually
540
541 char digits[kFastToBufferSize];
542
543 // No bool ctor -- bools convert to an integral type.
544 // A bool ctor would also convert incoming pointers (bletch).
545
546 AlphaNum(int32 i32)
547 : piece_data_(digits),
548 piece_size_(FastInt32ToBufferLeft(i32, digits) - &digits[0]) {}
549 AlphaNum(uint32 u32)
550 : piece_data_(digits),
551 piece_size_(FastUInt32ToBufferLeft(u32, digits) - &digits[0]) {}
552 AlphaNum(int64 i64)
553 : piece_data_(digits),
554 piece_size_(FastInt64ToBufferLeft(i64, digits) - &digits[0]) {}
555 AlphaNum(uint64 u64)
556 : piece_data_(digits),
557 piece_size_(FastUInt64ToBufferLeft(u64, digits) - &digits[0]) {}
558
559 AlphaNum(float f)
560 : piece_data_(digits), piece_size_(strlen(FloatToBuffer(f, digits))) {}
561 AlphaNum(double f)
562 : piece_data_(digits), piece_size_(strlen(DoubleToBuffer(f, digits))) {}
563
564 AlphaNum(Hex hex);
565
566 AlphaNum(const char* c_str)
567 : piece_data_(c_str), piece_size_(strlen(c_str)) {}
568 // TODO: Add a string_ref constructor, eventually
569 // AlphaNum(const StringPiece &pc) : piece(pc) {}
570
571 AlphaNum(const string& str)
572 : piece_data_(str.data()), piece_size_(str.size()) {}
573
574 size_t size() const { return piece_size_; }
575 const char *data() const { return piece_data_; }
576
577 private:
578 // Use ":" not ':'
579 AlphaNum(char c); // NOLINT(runtime/explicit)
580
581 // Disallow copy and assign.
582 AlphaNum(const AlphaNum&);
583 void operator=(const AlphaNum&);
584};
585
586} // namespace strings
587
588using strings::AlphaNum;
jieluo@google.com4de8f552014-07-18 00:47:59 +0000589
590// ----------------------------------------------------------------------
591// StrCat()
Jisi Liu885b6122015-02-28 14:51:22 -0800592// This merges the given strings or numbers, with no delimiter. This
593// is designed to be the fastest possible way to construct a string out
594// of a mix of raw C strings, strings, bool values,
595// and numeric values.
596//
597// Don't use this for user-visible strings. The localization process
598// works poorly on strings built up out of fragments.
599//
600// For clarity and performance, don't use StrCat when appending to a
601// string. In particular, avoid using any of these (anti-)patterns:
602// str.append(StrCat(...)
603// str += StrCat(...)
604// str = StrCat(str, ...)
605// where the last is the worse, with the potential to change a loop
606// from a linear time operation with O(1) dynamic allocations into a
607// quadratic time operation with O(n) dynamic allocations. StrAppend
608// is a better choice than any of the above, subject to the restriction
609// of StrAppend(&str, a, b, c, ...) that none of the a, b, c, ... may
610// be a reference into str.
jieluo@google.com4de8f552014-07-18 00:47:59 +0000611// ----------------------------------------------------------------------
Feng Xiao6ef984a2014-11-10 17:34:54 -0800612
Jisi Liu885b6122015-02-28 14:51:22 -0800613string StrCat(const AlphaNum &a, const AlphaNum &b);
614string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c);
615string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c,
616 const AlphaNum &d);
617string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c,
618 const AlphaNum &d, const AlphaNum &e);
619string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c,
620 const AlphaNum &d, const AlphaNum &e, const AlphaNum &f);
621string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c,
622 const AlphaNum &d, const AlphaNum &e, const AlphaNum &f,
623 const AlphaNum &g);
624string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c,
625 const AlphaNum &d, const AlphaNum &e, const AlphaNum &f,
626 const AlphaNum &g, const AlphaNum &h);
627string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c,
628 const AlphaNum &d, const AlphaNum &e, const AlphaNum &f,
629 const AlphaNum &g, const AlphaNum &h, const AlphaNum &i);
jieluo@google.com4de8f552014-07-18 00:47:59 +0000630
Jisi Liu885b6122015-02-28 14:51:22 -0800631inline string StrCat(const AlphaNum& a) { return string(a.data(), a.size()); }
jieluo@google.com4de8f552014-07-18 00:47:59 +0000632
Jisi Liu885b6122015-02-28 14:51:22 -0800633// ----------------------------------------------------------------------
634// StrAppend()
635// Same as above, but adds the output to the given string.
636// WARNING: For speed, StrAppend does not try to check each of its input
637// arguments to be sure that they are not a subset of the string being
638// appended to. That is, while this will work:
639//
640// string s = "foo";
641// s += s;
642//
643// This will not (necessarily) work:
644//
645// string s = "foo";
646// StrAppend(&s, s);
647//
648// Note: while StrCat supports appending up to 9 arguments, StrAppend
649// is currently limited to 4. That's rarely an issue except when
650// automatically transforming StrCat to StrAppend, and can easily be
651// worked around as consecutive calls to StrAppend are quite efficient.
652// ----------------------------------------------------------------------
jieluo@google.com4de8f552014-07-18 00:47:59 +0000653
Jisi Liu885b6122015-02-28 14:51:22 -0800654void StrAppend(string* dest, const AlphaNum& a);
655void StrAppend(string* dest, const AlphaNum& a, const AlphaNum& b);
656void StrAppend(string* dest, const AlphaNum& a, const AlphaNum& b,
657 const AlphaNum& c);
658void StrAppend(string* dest, const AlphaNum& a, const AlphaNum& b,
659 const AlphaNum& c, const AlphaNum& d);
jieluo@google.com4de8f552014-07-18 00:47:59 +0000660
661// ----------------------------------------------------------------------
662// Join()
663// These methods concatenate a range of components into a C++ string, using
664// the C-string "delim" as a separator between components.
665// ----------------------------------------------------------------------
666template <typename Iterator>
667void Join(Iterator start, Iterator end,
668 const char* delim, string* result) {
669 for (Iterator it = start; it != end; ++it) {
670 if (it != start) {
671 result->append(delim);
672 }
Jisi Liu885b6122015-02-28 14:51:22 -0800673 StrAppend(result, *it);
jieluo@google.com4de8f552014-07-18 00:47:59 +0000674 }
675}
676
677template <typename Range>
678string Join(const Range& components,
679 const char* delim) {
680 string result;
681 Join(components.begin(), components.end(), delim, &result);
682 return result;
683}
684
685// ----------------------------------------------------------------------
686// ToHex()
687// Return a lower-case hex string representation of the given integer.
688// ----------------------------------------------------------------------
689LIBPROTOBUF_EXPORT string ToHex(uint64 num);
temporal40ee5512008-07-10 02:12:20 +0000690
Feng Xiao6ef984a2014-11-10 17:34:54 -0800691// ----------------------------------------------------------------------
692// GlobalReplaceSubstring()
693// Replaces all instances of a substring in a string. Does nothing
694// if 'substring' is empty. Returns the number of replacements.
695//
696// NOTE: The string pieces must not overlap s.
697// ----------------------------------------------------------------------
698LIBPROTOBUF_EXPORT int GlobalReplaceSubstring(const string& substring,
699 const string& replacement,
700 string* s);
701
temporal40ee5512008-07-10 02:12:20 +0000702} // namespace protobuf
703} // namespace google
704
705#endif // GOOGLE_PROTOBUF_STUBS_STRUTIL_H__