strutil.h 39 KB

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