strutil.h 37 KB

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