String.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. /*
  2. * Copyright 2011-present Facebook, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #pragma once
  17. #define FOLLY_STRING_H_
  18. #include <cstdarg>
  19. #include <exception>
  20. #include <string>
  21. #include <unordered_map>
  22. #include <unordered_set>
  23. #include <vector>
  24. #include <folly/Conv.h>
  25. #include <folly/ExceptionString.h>
  26. #include <folly/FBString.h>
  27. #include <folly/FBVector.h>
  28. #include <folly/Portability.h>
  29. #include <folly/Range.h>
  30. #include <folly/ScopeGuard.h>
  31. #include <folly/Traits.h>
  32. // Compatibility function, to make sure toStdString(s) can be called
  33. // to convert a std::string or fbstring variable s into type std::string
  34. // with very little overhead if s was already std::string
  35. namespace folly {
  36. inline std::string toStdString(const folly::fbstring& s) {
  37. return std::string(s.data(), s.size());
  38. }
  39. inline const std::string& toStdString(const std::string& s) {
  40. return s;
  41. }
  42. // If called with a temporary, the compiler will select this overload instead
  43. // of the above, so we don't return a (lvalue) reference to a temporary.
  44. inline std::string&& toStdString(std::string&& s) {
  45. return std::move(s);
  46. }
  47. /**
  48. * C-Escape a string, making it suitable for representation as a C string
  49. * literal. Appends the result to the output string.
  50. *
  51. * Backslashes all occurrences of backslash and double-quote:
  52. * " -> \"
  53. * \ -> \\
  54. *
  55. * Replaces all non-printable ASCII characters with backslash-octal
  56. * representation:
  57. * <ASCII 254> -> \376
  58. *
  59. * Note that we use backslash-octal instead of backslash-hex because the octal
  60. * representation is guaranteed to consume no more than 3 characters; "\3760"
  61. * represents two characters, one with value 254, and one with value 48 ('0'),
  62. * whereas "\xfe0" represents only one character (with value 4064, which leads
  63. * to implementation-defined behavior).
  64. */
  65. template <class String>
  66. void cEscape(StringPiece str, String& out);
  67. /**
  68. * Similar to cEscape above, but returns the escaped string.
  69. */
  70. template <class String>
  71. String cEscape(StringPiece str) {
  72. String out;
  73. cEscape(str, out);
  74. return out;
  75. }
  76. /**
  77. * C-Unescape a string; the opposite of cEscape above. Appends the result
  78. * to the output string.
  79. *
  80. * Recognizes the standard C escape sequences:
  81. *
  82. * \' \" \? \\ \a \b \f \n \r \t \v
  83. * \[0-7]+
  84. * \x[0-9a-fA-F]+
  85. *
  86. * In strict mode (default), throws std::invalid_argument if it encounters
  87. * an unrecognized escape sequence. In non-strict mode, it leaves
  88. * the escape sequence unchanged.
  89. */
  90. template <class String>
  91. void cUnescape(StringPiece str, String& out, bool strict = true);
  92. /**
  93. * Similar to cUnescape above, but returns the escaped string.
  94. */
  95. template <class String>
  96. String cUnescape(StringPiece str, bool strict = true) {
  97. String out;
  98. cUnescape(str, out, strict);
  99. return out;
  100. }
  101. /**
  102. * URI-escape a string. Appends the result to the output string.
  103. *
  104. * Alphanumeric characters and other characters marked as "unreserved" in RFC
  105. * 3986 ( -_.~ ) are left unchanged. In PATH mode, the forward slash (/) is
  106. * also left unchanged. In QUERY mode, spaces are replaced by '+'. All other
  107. * characters are percent-encoded.
  108. */
  109. enum class UriEscapeMode : unsigned char {
  110. // The values are meaningful, see generate_escape_tables.py
  111. ALL = 0,
  112. QUERY = 1,
  113. PATH = 2
  114. };
  115. template <class String>
  116. void uriEscape(
  117. StringPiece str,
  118. String& out,
  119. UriEscapeMode mode = UriEscapeMode::ALL);
  120. /**
  121. * Similar to uriEscape above, but returns the escaped string.
  122. */
  123. template <class String>
  124. String uriEscape(StringPiece str, UriEscapeMode mode = UriEscapeMode::ALL) {
  125. String out;
  126. uriEscape(str, out, mode);
  127. return out;
  128. }
  129. /**
  130. * URI-unescape a string. Appends the result to the output string.
  131. *
  132. * In QUERY mode, '+' are replaced by space. %XX sequences are decoded if
  133. * XX is a valid hex sequence, otherwise we throw invalid_argument.
  134. */
  135. template <class String>
  136. void uriUnescape(
  137. StringPiece str,
  138. String& out,
  139. UriEscapeMode mode = UriEscapeMode::ALL);
  140. /**
  141. * Similar to uriUnescape above, but returns the unescaped string.
  142. */
  143. template <class String>
  144. String uriUnescape(StringPiece str, UriEscapeMode mode = UriEscapeMode::ALL) {
  145. String out;
  146. uriUnescape(str, out, mode);
  147. return out;
  148. }
  149. /**
  150. * stringPrintf is much like printf but deposits its result into a
  151. * string. Two signatures are supported: the first simply returns the
  152. * resulting string, and the second appends the produced characters to
  153. * the specified string and returns a reference to it.
  154. */
  155. std::string stringPrintf(FOLLY_PRINTF_FORMAT const char* format, ...)
  156. FOLLY_PRINTF_FORMAT_ATTR(1, 2);
  157. /* Similar to stringPrintf, with different signature. */
  158. void stringPrintf(std::string* out, FOLLY_PRINTF_FORMAT const char* fmt, ...)
  159. FOLLY_PRINTF_FORMAT_ATTR(2, 3);
  160. std::string& stringAppendf(
  161. std::string* output,
  162. FOLLY_PRINTF_FORMAT const char* format,
  163. ...) FOLLY_PRINTF_FORMAT_ATTR(2, 3);
  164. /**
  165. * Similar to stringPrintf, but accepts a va_list argument.
  166. *
  167. * As with vsnprintf() itself, the value of ap is undefined after the call.
  168. * These functions do not call va_end() on ap.
  169. */
  170. std::string stringVPrintf(const char* format, va_list ap);
  171. void stringVPrintf(std::string* out, const char* format, va_list ap);
  172. std::string& stringVAppendf(std::string* out, const char* format, va_list ap);
  173. /**
  174. * Backslashify a string, that is, replace non-printable characters
  175. * with C-style (but NOT C compliant) "\xHH" encoding. If hex_style
  176. * is false, then shorthand notations like "\0" will be used instead
  177. * of "\x00" for the most common backslash cases.
  178. *
  179. * There are two forms, one returning the input string, and one
  180. * creating output in the specified output string.
  181. *
  182. * This is mainly intended for printing to a terminal, so it is not
  183. * particularly optimized.
  184. *
  185. * Do *not* use this in situations where you expect to be able to feed
  186. * the string to a C or C++ compiler, as there are nuances with how C
  187. * parses such strings that lead to failures. This is for display
  188. * purposed only. If you want a string you can embed for use in C or
  189. * C++, use cEscape instead. This function is for display purposes
  190. * only.
  191. */
  192. template <class OutputString>
  193. void backslashify(
  194. folly::StringPiece input,
  195. OutputString& output,
  196. bool hex_style = false);
  197. template <class OutputString = std::string>
  198. OutputString backslashify(StringPiece input, bool hex_style = false) {
  199. OutputString output;
  200. backslashify(input, output, hex_style);
  201. return output;
  202. }
  203. /**
  204. * Take a string and "humanify" it -- that is, make it look better.
  205. * Since "better" is subjective, caveat emptor. The basic approach is
  206. * to count the number of unprintable characters. If there are none,
  207. * then the output is the input. If there are relatively few, or if
  208. * there is a long "enough" prefix of printable characters, use
  209. * backslashify. If it is mostly binary, then simply hex encode.
  210. *
  211. * This is an attempt to make a computer smart, and so likely is wrong
  212. * most of the time.
  213. */
  214. template <class String1, class String2>
  215. void humanify(const String1& input, String2& output);
  216. template <class String>
  217. String humanify(const String& input) {
  218. String output;
  219. humanify(input, output);
  220. return output;
  221. }
  222. /**
  223. * Same functionality as Python's binascii.hexlify. Returns true
  224. * on successful conversion.
  225. *
  226. * If append_output is true, append data to the output rather than
  227. * replace it.
  228. */
  229. template <class InputString, class OutputString>
  230. bool hexlify(
  231. const InputString& input,
  232. OutputString& output,
  233. bool append = false);
  234. template <class OutputString = std::string>
  235. OutputString hexlify(ByteRange input) {
  236. OutputString output;
  237. if (!hexlify(input, output)) {
  238. // hexlify() currently always returns true, so this can't really happen
  239. throw std::runtime_error("hexlify failed");
  240. }
  241. return output;
  242. }
  243. template <class OutputString = std::string>
  244. OutputString hexlify(StringPiece input) {
  245. return hexlify<OutputString>(ByteRange{input});
  246. }
  247. /**
  248. * Same functionality as Python's binascii.unhexlify. Returns true
  249. * on successful conversion.
  250. */
  251. template <class InputString, class OutputString>
  252. bool unhexlify(const InputString& input, OutputString& output);
  253. template <class OutputString = std::string>
  254. OutputString unhexlify(StringPiece input) {
  255. OutputString output;
  256. if (!unhexlify(input, output)) {
  257. // unhexlify() fails if the input has non-hexidecimal characters,
  258. // or if it doesn't consist of a whole number of bytes
  259. throw std::domain_error("unhexlify() called with non-hex input");
  260. }
  261. return output;
  262. }
  263. /**
  264. * A pretty-printer for numbers that appends suffixes of units of the
  265. * given type. It prints 4 sig-figs of value with the most
  266. * appropriate unit.
  267. *
  268. * If `addSpace' is true, we put a space between the units suffix and
  269. * the value.
  270. *
  271. * Current types are:
  272. * PRETTY_TIME - s, ms, us, ns, etc.
  273. * PRETTY_TIME_HMS - h, m, s, ms, us, ns, etc.
  274. * PRETTY_BYTES_METRIC - kB, MB, GB, etc (goes up by 10^3 = 1000 each time)
  275. * PRETTY_BYTES - kB, MB, GB, etc (goes up by 2^10 = 1024 each time)
  276. * PRETTY_BYTES_IEC - KiB, MiB, GiB, etc
  277. * PRETTY_UNITS_METRIC - k, M, G, etc (goes up by 10^3 = 1000 each time)
  278. * PRETTY_UNITS_BINARY - k, M, G, etc (goes up by 2^10 = 1024 each time)
  279. * PRETTY_UNITS_BINARY_IEC - Ki, Mi, Gi, etc
  280. * PRETTY_SI - full SI metric prefixes from yocto to Yotta
  281. * http://en.wikipedia.org/wiki/Metric_prefix
  282. *
  283. * @author Mark Rabkin <mrabkin@fb.com>
  284. */
  285. enum PrettyType {
  286. PRETTY_TIME,
  287. PRETTY_TIME_HMS,
  288. PRETTY_BYTES_METRIC,
  289. PRETTY_BYTES_BINARY,
  290. PRETTY_BYTES = PRETTY_BYTES_BINARY,
  291. PRETTY_BYTES_BINARY_IEC,
  292. PRETTY_BYTES_IEC = PRETTY_BYTES_BINARY_IEC,
  293. PRETTY_UNITS_METRIC,
  294. PRETTY_UNITS_BINARY,
  295. PRETTY_UNITS_BINARY_IEC,
  296. PRETTY_SI,
  297. PRETTY_NUM_TYPES,
  298. };
  299. std::string prettyPrint(double val, PrettyType, bool addSpace = true);
  300. /**
  301. * This utility converts StringPiece in pretty format (look above) to double,
  302. * with progress information. Alters the StringPiece parameter
  303. * to get rid of the already-parsed characters.
  304. * Expects string in form <floating point number> {space}* [<suffix>]
  305. * If string is not in correct format, utility finds longest valid prefix and
  306. * if there at least one, returns double value based on that prefix and
  307. * modifies string to what is left after parsing. Throws and std::range_error
  308. * exception if there is no correct parse.
  309. * Examples(for PRETTY_UNITS_METRIC):
  310. * '10M' => 10 000 000
  311. * '10 M' => 10 000 000
  312. * '10' => 10
  313. * '10 Mx' => 10 000 000, prettyString == "x"
  314. * 'abc' => throws std::range_error
  315. */
  316. double prettyToDouble(
  317. folly::StringPiece* const prettyString,
  318. const PrettyType type);
  319. /**
  320. * Same as prettyToDouble(folly::StringPiece*, PrettyType), but
  321. * expects whole string to be correctly parseable. Throws std::range_error
  322. * otherwise
  323. */
  324. double prettyToDouble(folly::StringPiece prettyString, const PrettyType type);
  325. /**
  326. * Write a hex dump of size bytes starting at ptr to out.
  327. *
  328. * The hex dump is formatted as follows:
  329. *
  330. * for the string "abcdefghijklmnopqrstuvwxyz\x02"
  331. 00000000 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f 70 |abcdefghijklmnop|
  332. 00000010 71 72 73 74 75 76 77 78 79 7a 02 |qrstuvwxyz. |
  333. *
  334. * that is, we write 16 bytes per line, both as hex bytes and as printable
  335. * characters. Non-printable characters are replaced with '.'
  336. * Lines are written to out one by one (one StringPiece at a time) without
  337. * delimiters.
  338. */
  339. template <class OutIt>
  340. void hexDump(const void* ptr, size_t size, OutIt out);
  341. /**
  342. * Return the hex dump of size bytes starting at ptr as a string.
  343. */
  344. std::string hexDump(const void* ptr, size_t size);
  345. /**
  346. * Return a fbstring containing the description of the given errno value.
  347. * Takes care not to overwrite the actual system errno, so calling
  348. * errnoStr(errno) is valid.
  349. */
  350. fbstring errnoStr(int err);
  351. /*
  352. * Split a string into a list of tokens by delimiter.
  353. *
  354. * The split interface here supports different output types, selected
  355. * at compile time: StringPiece, fbstring, or std::string. If you are
  356. * using a vector to hold the output, it detects the type based on
  357. * what your vector contains. If the output vector is not empty, split
  358. * will append to the end of the vector.
  359. *
  360. * You can also use splitTo() to write the output to an arbitrary
  361. * OutputIterator (e.g. std::inserter() on a std::set<>), in which
  362. * case you have to tell the function the type. (Rationale:
  363. * OutputIterators don't have a value_type, so we can't detect the
  364. * type in splitTo without being told.)
  365. *
  366. * Examples:
  367. *
  368. * std::vector<folly::StringPiece> v;
  369. * folly::split(":", "asd:bsd", v);
  370. *
  371. * std::set<StringPiece> s;
  372. * folly::splitTo<StringPiece>(":", "asd:bsd:asd:csd",
  373. * std::inserter(s, s.begin()));
  374. *
  375. * Split also takes a flag (ignoreEmpty) that indicates whether adjacent
  376. * delimiters should be treated as one single separator (ignoring empty tokens)
  377. * or not (generating empty tokens).
  378. */
  379. template <class Delim, class String, class OutputType>
  380. void split(
  381. const Delim& delimiter,
  382. const String& input,
  383. std::vector<OutputType>& out,
  384. const bool ignoreEmpty = false);
  385. template <class Delim, class String, class OutputType>
  386. void split(
  387. const Delim& delimiter,
  388. const String& input,
  389. folly::fbvector<OutputType>& out,
  390. const bool ignoreEmpty = false);
  391. template <
  392. class OutputValueType,
  393. class Delim,
  394. class String,
  395. class OutputIterator>
  396. void splitTo(
  397. const Delim& delimiter,
  398. const String& input,
  399. OutputIterator out,
  400. const bool ignoreEmpty = false);
  401. /*
  402. * Split a string into a fixed number of string pieces and/or numeric types
  403. * by delimiter. Conversions are supported for any type which folly:to<> can
  404. * target, including all overloads of parseTo(). Returns 'true' if the fields
  405. * were all successfully populated. Returns 'false' if there were too few
  406. * fields in the input, or too many fields if exact=true. Casting exceptions
  407. * will not be caught.
  408. *
  409. * Examples:
  410. *
  411. * folly::StringPiece name, key, value;
  412. * if (folly::split('\t', line, name, key, value))
  413. * ...
  414. *
  415. * folly::StringPiece name;
  416. * double value;
  417. * int id;
  418. * if (folly::split('\t', line, name, value, id))
  419. * ...
  420. *
  421. * The 'exact' template parameter specifies how the function behaves when too
  422. * many fields are present in the input string. When 'exact' is set to its
  423. * default value of 'true', a call to split will fail if the number of fields in
  424. * the input string does not exactly match the number of output parameters
  425. * passed. If 'exact' is overridden to 'false', all remaining fields will be
  426. * stored, unsplit, in the last field, as shown below:
  427. *
  428. * folly::StringPiece x, y.
  429. * if (folly::split<false>(':', "a:b:c", x, y))
  430. * assert(x == "a" && y == "b:c");
  431. *
  432. * Note that this will likely not work if the last field's target is of numeric
  433. * type, in which case folly::to<> will throw an exception.
  434. */
  435. namespace detail {
  436. template <typename Void, typename OutputType>
  437. struct IsConvertible : std::false_type {};
  438. template <>
  439. struct IsConvertible<void, decltype(std::ignore)> : std::true_type {};
  440. template <typename OutputType>
  441. struct IsConvertible<
  442. void_t<decltype(parseTo(StringPiece{}, std::declval<OutputType&>()))>,
  443. OutputType> : std::true_type {};
  444. } // namespace detail
  445. template <typename OutputType>
  446. struct IsConvertible : detail::IsConvertible<void, OutputType> {};
  447. template <bool exact = true, class Delim, class... OutputTypes>
  448. typename std::enable_if<
  449. StrictConjunction<IsConvertible<OutputTypes>...>::value &&
  450. sizeof...(OutputTypes) >= 1,
  451. bool>::type
  452. split(const Delim& delimiter, StringPiece input, OutputTypes&... outputs);
  453. /*
  454. * Join list of tokens.
  455. *
  456. * Stores a string representation of tokens in the same order with
  457. * deliminer between each element.
  458. */
  459. template <class Delim, class Iterator, class String>
  460. void join(const Delim& delimiter, Iterator begin, Iterator end, String& output);
  461. template <class Delim, class Container, class String>
  462. void join(const Delim& delimiter, const Container& container, String& output) {
  463. join(delimiter, container.begin(), container.end(), output);
  464. }
  465. template <class Delim, class Value, class String>
  466. void join(
  467. const Delim& delimiter,
  468. const std::initializer_list<Value>& values,
  469. String& output) {
  470. join(delimiter, values.begin(), values.end(), output);
  471. }
  472. template <class Delim, class Container>
  473. std::string join(const Delim& delimiter, const Container& container) {
  474. std::string output;
  475. join(delimiter, container.begin(), container.end(), output);
  476. return output;
  477. }
  478. template <class Delim, class Value>
  479. std::string join(
  480. const Delim& delimiter,
  481. const std::initializer_list<Value>& values) {
  482. std::string output;
  483. join(delimiter, values.begin(), values.end(), output);
  484. return output;
  485. }
  486. template <
  487. class Delim,
  488. class Iterator,
  489. typename std::enable_if<std::is_base_of<
  490. std::forward_iterator_tag,
  491. typename std::iterator_traits<Iterator>::iterator_category>::value>::
  492. type* = nullptr>
  493. std::string join(const Delim& delimiter, Iterator begin, Iterator end) {
  494. std::string output;
  495. join(delimiter, begin, end, output);
  496. return output;
  497. }
  498. /**
  499. * Returns a subpiece with all whitespace removed from the front of @sp.
  500. * Whitespace means any of [' ', '\n', '\r', '\t'].
  501. */
  502. StringPiece ltrimWhitespace(StringPiece sp);
  503. /**
  504. * Returns a subpiece with all whitespace removed from the back of @sp.
  505. * Whitespace means any of [' ', '\n', '\r', '\t'].
  506. */
  507. StringPiece rtrimWhitespace(StringPiece sp);
  508. /**
  509. * Returns a subpiece with all whitespace removed from the back and front of
  510. * @sp. Whitespace means any of [' ', '\n', '\r', '\t'].
  511. */
  512. inline StringPiece trimWhitespace(StringPiece sp) {
  513. return ltrimWhitespace(rtrimWhitespace(sp));
  514. }
  515. /**
  516. * Returns a subpiece with all whitespace removed from the front of @sp.
  517. * Whitespace means any of [' ', '\n', '\r', '\t'].
  518. * DEPRECATED: @see ltrimWhitespace @see rtrimWhitespace
  519. */
  520. inline StringPiece skipWhitespace(StringPiece sp) {
  521. return ltrimWhitespace(sp);
  522. }
  523. /**
  524. * Strips the leading and the trailing whitespace-only lines. Then looks for
  525. * the least indented non-whitespace-only line and removes its amount of
  526. * leading whitespace from every line. Assumes leading whitespace is either all
  527. * spaces or all tabs.
  528. *
  529. * Purpose: including a multiline string literal in source code, indented to
  530. * the level expected from context.
  531. */
  532. std::string stripLeftMargin(std::string s);
  533. /**
  534. * Fast, in-place lowercasing of ASCII alphabetic characters in strings.
  535. * Leaves all other characters unchanged, including those with the 0x80
  536. * bit set.
  537. * @param str String to convert
  538. * @param length Length of str, in bytes
  539. */
  540. void toLowerAscii(char* str, size_t length);
  541. inline void toLowerAscii(MutableStringPiece str) {
  542. toLowerAscii(str.begin(), str.size());
  543. }
  544. inline void toLowerAscii(std::string& str) {
  545. // str[0] is legal also if the string is empty.
  546. toLowerAscii(&str[0], str.size());
  547. }
  548. } // namespace folly
  549. #include <folly/String-inl.h>