2 * Copyright 2016 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 #define FOLLY_STRING_H_
23 #include <boost/type_traits.hpp>
24 #include <boost/regex/pending/unicode_iterator.hpp>
26 #ifdef FOLLY_HAVE_DEPRECATED_ASSOC
27 #ifdef _GLIBCXX_SYMVER
28 #include <ext/hash_set>
29 #include <ext/hash_map>
33 #include <unordered_set>
34 #include <unordered_map>
36 #include <folly/Conv.h>
37 #include <folly/Demangle.h>
38 #include <folly/FBString.h>
39 #include <folly/FBVector.h>
40 #include <folly/Portability.h>
41 #include <folly/Range.h>
42 #include <folly/ScopeGuard.h>
44 // Compatibility function, to make sure toStdString(s) can be called
45 // to convert a std::string or fbstring variable s into type std::string
46 // with very little overhead if s was already std::string
50 std::string toStdString(const folly::fbstring& s) {
51 return std::string(s.data(), s.size());
55 const std::string& toStdString(const std::string& s) {
59 // If called with a temporary, the compiler will select this overload instead
60 // of the above, so we don't return a (lvalue) reference to a temporary.
62 std::string&& toStdString(std::string&& s) {
67 * C-Escape a string, making it suitable for representation as a C string
68 * literal. Appends the result to the output string.
70 * Backslashes all occurrences of backslash and double-quote:
74 * Replaces all non-printable ASCII characters with backslash-octal
78 * Note that we use backslash-octal instead of backslash-hex because the octal
79 * representation is guaranteed to consume no more than 3 characters; "\3760"
80 * represents two characters, one with value 254, and one with value 48 ('0'),
81 * whereas "\xfe0" represents only one character (with value 4064, which leads
82 * to implementation-defined behavior).
84 template <class String>
85 void cEscape(StringPiece str, String& out);
88 * Similar to cEscape above, but returns the escaped string.
90 template <class String>
91 String cEscape(StringPiece str) {
98 * C-Unescape a string; the opposite of cEscape above. Appends the result
99 * to the output string.
101 * Recognizes the standard C escape sequences:
103 * \' \" \? \\ \a \b \f \n \r \t \v
107 * In strict mode (default), throws std::invalid_argument if it encounters
108 * an unrecognized escape sequence. In non-strict mode, it leaves
109 * the escape sequence unchanged.
111 template <class String>
112 void cUnescape(StringPiece str, String& out, bool strict = true);
115 * Similar to cUnescape above, but returns the escaped string.
117 template <class String>
118 String cUnescape(StringPiece str, bool strict = true) {
120 cUnescape(str, out, strict);
125 * URI-escape a string. Appends the result to the output string.
127 * Alphanumeric characters and other characters marked as "unreserved" in RFC
128 * 3986 ( -_.~ ) are left unchanged. In PATH mode, the forward slash (/) is
129 * also left unchanged. In QUERY mode, spaces are replaced by '+'. All other
130 * characters are percent-encoded.
132 enum class UriEscapeMode : unsigned char {
133 // The values are meaningful, see generate_escape_tables.py
138 template <class String>
139 void uriEscape(StringPiece str,
141 UriEscapeMode mode = UriEscapeMode::ALL);
144 * Similar to uriEscape above, but returns the escaped string.
146 template <class String>
147 String uriEscape(StringPiece str, UriEscapeMode mode = UriEscapeMode::ALL) {
149 uriEscape(str, out, mode);
154 * URI-unescape a string. Appends the result to the output string.
156 * In QUERY mode, '+' are replaced by space. %XX sequences are decoded if
157 * XX is a valid hex sequence, otherwise we throw invalid_argument.
159 template <class String>
160 void uriUnescape(StringPiece str,
162 UriEscapeMode mode = UriEscapeMode::ALL);
165 * Similar to uriUnescape above, but returns the unescaped string.
167 template <class String>
168 String uriUnescape(StringPiece str, UriEscapeMode mode = UriEscapeMode::ALL) {
170 uriUnescape(str, out, mode);
175 * stringPrintf is much like printf but deposits its result into a
176 * string. Two signatures are supported: the first simply returns the
177 * resulting string, and the second appends the produced characters to
178 * the specified string and returns a reference to it.
180 std::string stringPrintf(FOLLY_PRINTF_FORMAT const char* format, ...)
181 FOLLY_PRINTF_FORMAT_ATTR(1, 2);
183 /* Similar to stringPrintf, with different signature. */
184 void stringPrintf(std::string* out, FOLLY_PRINTF_FORMAT const char* fmt, ...)
185 FOLLY_PRINTF_FORMAT_ATTR(2, 3);
187 std::string& stringAppendf(std::string* output,
188 FOLLY_PRINTF_FORMAT const char* format, ...)
189 FOLLY_PRINTF_FORMAT_ATTR(2, 3);
192 * Similar to stringPrintf, but accepts a va_list argument.
194 * As with vsnprintf() itself, the value of ap is undefined after the call.
195 * These functions do not call va_end() on ap.
197 std::string stringVPrintf(const char* format, va_list ap);
198 void stringVPrintf(std::string* out, const char* format, va_list ap);
199 std::string& stringVAppendf(std::string* out, const char* format, va_list ap);
202 * Backslashify a string, that is, replace non-printable characters
203 * with C-style (but NOT C compliant) "\xHH" encoding. If hex_style
204 * is false, then shorthand notations like "\0" will be used instead
205 * of "\x00" for the most common backslash cases.
207 * There are two forms, one returning the input string, and one
208 * creating output in the specified output string.
210 * This is mainly intended for printing to a terminal, so it is not
211 * particularly optimized.
213 * Do *not* use this in situations where you expect to be able to feed
214 * the string to a C or C++ compiler, as there are nuances with how C
215 * parses such strings that lead to failures. This is for display
216 * purposed only. If you want a string you can embed for use in C or
217 * C++, use cEscape instead. This function is for display purposes
220 template <class String1, class String2>
221 void backslashify(const String1& input, String2& output, bool hex_style=false);
223 template <class String>
224 String backslashify(const String& input, bool hex_style=false) {
226 backslashify(input, output, hex_style);
231 * Take a string and "humanify" it -- that is, make it look better.
232 * Since "better" is subjective, caveat emptor. The basic approach is
233 * to count the number of unprintable characters. If there are none,
234 * then the output is the input. If there are relatively few, or if
235 * there is a long "enough" prefix of printable characters, use
236 * backslashify. If it is mostly binary, then simply hex encode.
238 * This is an attempt to make a computer smart, and so likely is wrong
241 template <class String1, class String2>
242 void humanify(const String1& input, String2& output);
244 template <class String>
245 String humanify(const String& input) {
247 humanify(input, output);
252 * Same functionality as Python's binascii.hexlify. Returns true
253 * on successful conversion.
255 * If append_output is true, append data to the output rather than
258 template<class InputString, class OutputString>
259 bool hexlify(const InputString& input, OutputString& output,
262 template <class OutputString = std::string>
263 OutputString hexlify(ByteRange input) {
265 if (!hexlify(input, output)) {
266 // hexlify() currently always returns true, so this can't really happen
267 throw std::runtime_error("hexlify failed");
272 template <class OutputString = std::string>
273 OutputString hexlify(StringPiece input) {
274 return hexlify<OutputString>(ByteRange{input});
278 * Same functionality as Python's binascii.unhexlify. Returns true
279 * on successful conversion.
281 template<class InputString, class OutputString>
282 bool unhexlify(const InputString& input, OutputString& output);
284 template <class OutputString = std::string>
285 OutputString unhexlify(StringPiece input) {
287 if (!unhexlify(input, output)) {
288 // unhexlify() fails if the input has non-hexidecimal characters,
289 // or if it doesn't consist of a whole number of bytes
290 throw std::domain_error("unhexlify() called with non-hex input");
296 * A pretty-printer for numbers that appends suffixes of units of the
297 * given type. It prints 4 sig-figs of value with the most
300 * If `addSpace' is true, we put a space between the units suffix and
304 * PRETTY_TIME - s, ms, us, ns, etc.
305 * PRETTY_BYTES_METRIC - kB, MB, GB, etc (goes up by 10^3 = 1000 each time)
306 * PRETTY_BYTES - kB, MB, GB, etc (goes up by 2^10 = 1024 each time)
307 * PRETTY_BYTES_IEC - KiB, MiB, GiB, etc
308 * PRETTY_UNITS_METRIC - k, M, G, etc (goes up by 10^3 = 1000 each time)
309 * PRETTY_UNITS_BINARY - k, M, G, etc (goes up by 2^10 = 1024 each time)
310 * PRETTY_UNITS_BINARY_IEC - Ki, Mi, Gi, etc
311 * PRETTY_SI - full SI metric prefixes from yocto to Yotta
312 * http://en.wikipedia.org/wiki/Metric_prefix
313 * @author Mark Rabkin <mrabkin@fb.com>
320 PRETTY_BYTES = PRETTY_BYTES_BINARY,
321 PRETTY_BYTES_BINARY_IEC,
322 PRETTY_BYTES_IEC = PRETTY_BYTES_BINARY_IEC,
326 PRETTY_UNITS_BINARY_IEC,
332 std::string prettyPrint(double val, PrettyType, bool addSpace = true);
335 * This utility converts StringPiece in pretty format (look above) to double,
336 * with progress information. Alters the StringPiece parameter
337 * to get rid of the already-parsed characters.
338 * Expects string in form <floating point number> {space}* [<suffix>]
339 * If string is not in correct format, utility finds longest valid prefix and
340 * if there at least one, returns double value based on that prefix and
341 * modifies string to what is left after parsing. Throws and std::range_error
342 * exception if there is no correct parse.
343 * Examples(for PRETTY_UNITS_METRIC):
344 * '10M' => 10 000 000
345 * '10 M' => 10 000 000
347 * '10 Mx' => 10 000 000, prettyString == "x"
348 * 'abc' => throws std::range_error
350 double prettyToDouble(folly::StringPiece *const prettyString,
351 const PrettyType type);
354 * Same as prettyToDouble(folly::StringPiece*, PrettyType), but
355 * expects whole string to be correctly parseable. Throws std::range_error
358 double prettyToDouble(folly::StringPiece prettyString, const PrettyType type);
361 * Write a hex dump of size bytes starting at ptr to out.
363 * The hex dump is formatted as follows:
365 * for the string "abcdefghijklmnopqrstuvwxyz\x02"
366 00000000 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f 70 |abcdefghijklmnop|
367 00000010 71 72 73 74 75 76 77 78 79 7a 02 |qrstuvwxyz. |
369 * that is, we write 16 bytes per line, both as hex bytes and as printable
370 * characters. Non-printable characters are replaced with '.'
371 * Lines are written to out one by one (one StringPiece at a time) without
374 template <class OutIt>
375 void hexDump(const void* ptr, size_t size, OutIt out);
378 * Return the hex dump of size bytes starting at ptr as a string.
380 std::string hexDump(const void* ptr, size_t size);
383 * Return a fbstring containing the description of the given errno value.
384 * Takes care not to overwrite the actual system errno, so calling
385 * errnoStr(errno) is valid.
387 fbstring errnoStr(int err);
390 * Debug string for an exception: include type and what(), if
393 inline fbstring exceptionStr(const std::exception& e) {
394 #ifdef FOLLY_HAS_RTTI
395 return folly::to<fbstring>(demangle(typeid(e)), ": ", e.what());
397 return folly::to<fbstring>("Exception (no RTTI available): ", e.what());
401 // Empirically, this indicates if the runtime supports
402 // std::exception_ptr, as not all (arm, for instance) do.
403 #if defined(__GNUC__) && defined(__GCC_ATOMIC_INT_LOCK_FREE) && \
404 __GCC_ATOMIC_INT_LOCK_FREE > 1
405 inline fbstring exceptionStr(std::exception_ptr ep) {
407 std::rethrow_exception(ep);
408 } catch (const std::exception& e) {
409 return exceptionStr(e);
411 return "<unknown exception>";
417 auto exceptionStr(const E& e)
418 -> typename std::enable_if<!std::is_base_of<std::exception, E>::value,
421 #ifdef FOLLY_HAS_RTTI
422 return folly::to<fbstring>(demangle(typeid(e)));
424 return "Exception (no RTTI available)";
429 * Split a string into a list of tokens by delimiter.
431 * The split interface here supports different output types, selected
432 * at compile time: StringPiece, fbstring, or std::string. If you are
433 * using a vector to hold the output, it detects the type based on
434 * what your vector contains. If the output vector is not empty, split
435 * will append to the end of the vector.
437 * You can also use splitTo() to write the output to an arbitrary
438 * OutputIterator (e.g. std::inserter() on a std::set<>), in which
439 * case you have to tell the function the type. (Rationale:
440 * OutputIterators don't have a value_type, so we can't detect the
441 * type in splitTo without being told.)
445 * std::vector<folly::StringPiece> v;
446 * folly::split(":", "asd:bsd", v);
448 * std::set<StringPiece> s;
449 * folly::splitTo<StringPiece>(":", "asd:bsd:asd:csd",
450 * std::inserter(s, s.begin()));
452 * Split also takes a flag (ignoreEmpty) that indicates whether adjacent
453 * delimiters should be treated as one single separator (ignoring empty tokens)
454 * or not (generating empty tokens).
457 template<class Delim, class String, class OutputType>
458 void split(const Delim& delimiter,
460 std::vector<OutputType>& out,
461 const bool ignoreEmpty = false);
463 template<class Delim, class String, class OutputType>
464 void split(const Delim& delimiter,
466 folly::fbvector<OutputType>& out,
467 const bool ignoreEmpty = false);
469 template<class OutputValueType, class Delim, class String,
470 class OutputIterator>
471 void splitTo(const Delim& delimiter,
474 const bool ignoreEmpty = false);
477 * Split a string into a fixed number of string pieces and/or numeric types
478 * by delimiter. Conversions are supported for any type which folly:to<> can
479 * target, including all overloads of parseTo(). Returns 'true' if the fields
480 * were all successfully populated. Returns 'false' if there were too few
481 * fields in the input, or too many fields if exact=true. Casting exceptions
482 * will not be caught.
486 * folly::StringPiece name, key, value;
487 * if (folly::split('\t', line, name, key, value))
490 * folly::StringPiece name;
493 * if (folly::split('\t', line, name, value, id))
496 * The 'exact' template parameter specifies how the function behaves when too
497 * many fields are present in the input string. When 'exact' is set to its
498 * default value of 'true', a call to split will fail if the number of fields in
499 * the input string does not exactly match the number of output parameters
500 * passed. If 'exact' is overridden to 'false', all remaining fields will be
501 * stored, unsplit, in the last field, as shown below:
503 * folly::StringPiece x, y.
504 * if (folly::split<false>(':', "a:b:c", x, y))
505 * assert(x == "a" && y == "b:c");
507 * Note that this will likely not work if the last field's target is of numeric
508 * type, in which case folly::to<> will throw an exception.
510 template <class T, class Enable = void>
511 struct IsSomeVector {
512 enum { value = false };
516 struct IsSomeVector<std::vector<T>, void> {
517 enum { value = true };
521 struct IsSomeVector<fbvector<T>, void> {
522 enum { value = true };
525 template <class T, class Enable = void>
526 struct IsConvertible {
527 enum { value = false };
531 struct IsConvertible<
533 decltype(parseTo(std::declval<folly::StringPiece>(), std::declval<T&>()))> {
534 enum { value = true };
537 template <class... Types>
538 struct AllConvertible;
540 template <class Head, class... Tail>
541 struct AllConvertible<Head, Tail...> {
542 enum { value = IsConvertible<Head>::value && AllConvertible<Tail...>::value };
546 struct AllConvertible<> {
547 enum { value = true };
550 static_assert(AllConvertible<float>::value, "");
551 static_assert(AllConvertible<int>::value, "");
552 static_assert(AllConvertible<bool>::value, "");
553 static_assert(AllConvertible<int>::value, "");
554 static_assert(!AllConvertible<std::vector<int>>::value, "");
556 template <bool exact = true, class Delim, class... OutputTypes>
557 typename std::enable_if<
558 AllConvertible<OutputTypes...>::value && sizeof...(OutputTypes) >= 1,
560 split(const Delim& delimiter, StringPiece input, OutputTypes&... outputs);
563 * Join list of tokens.
565 * Stores a string representation of tokens in the same order with
566 * deliminer between each element.
569 template <class Delim, class Iterator, class String>
570 void join(const Delim& delimiter,
575 template <class Delim, class Container, class String>
576 void join(const Delim& delimiter,
577 const Container& container,
579 join(delimiter, container.begin(), container.end(), output);
582 template <class Delim, class Value, class String>
583 void join(const Delim& delimiter,
584 const std::initializer_list<Value>& values,
586 join(delimiter, values.begin(), values.end(), output);
589 template <class Delim, class Container>
590 std::string join(const Delim& delimiter,
591 const Container& container) {
593 join(delimiter, container.begin(), container.end(), output);
597 template <class Delim, class Value>
598 std::string join(const Delim& delimiter,
599 const std::initializer_list<Value>& values) {
601 join(delimiter, values.begin(), values.end(), output);
605 template <class Delim,
607 typename std::enable_if<std::is_same<
608 typename std::iterator_traits<Iterator>::iterator_category,
609 std::random_access_iterator_tag>::value>::type* = nullptr>
610 std::string join(const Delim& delimiter, Iterator begin, Iterator end) {
612 join(delimiter, begin, end, output);
617 * Returns a subpiece with all whitespace removed from the front of @sp.
618 * Whitespace means any of [' ', '\n', '\r', '\t'].
620 StringPiece ltrimWhitespace(StringPiece sp);
623 * Returns a subpiece with all whitespace removed from the back of @sp.
624 * Whitespace means any of [' ', '\n', '\r', '\t'].
626 StringPiece rtrimWhitespace(StringPiece sp);
629 * Returns a subpiece with all whitespace removed from the back and front of @sp.
630 * Whitespace means any of [' ', '\n', '\r', '\t'].
632 inline StringPiece trimWhitespace(StringPiece sp) {
633 return ltrimWhitespace(rtrimWhitespace(sp));
637 * Returns a subpiece with all whitespace removed from the front of @sp.
638 * Whitespace means any of [' ', '\n', '\r', '\t'].
639 * DEPRECATED: @see ltrimWhitespace @see rtrimWhitespace
641 inline StringPiece skipWhitespace(StringPiece sp) {
642 return ltrimWhitespace(sp);
646 * Strips the leading and the trailing whitespace-only lines. Then looks for
647 * the least indented non-whitespace-only line and removes its amount of
648 * leading whitespace from every line. Assumes leading whitespace is either all
649 * spaces or all tabs.
651 * Purpose: including a multiline string literal in source code, indented to
652 * the level expected from context.
654 std::string stripLeftMargin(std::string s);
657 * Fast, in-place lowercasing of ASCII alphabetic characters in strings.
658 * Leaves all other characters unchanged, including those with the 0x80
660 * @param str String to convert
661 * @param len Length of str, in bytes
663 void toLowerAscii(char* str, size_t length);
665 inline void toLowerAscii(MutableStringPiece str) {
666 toLowerAscii(str.begin(), str.size());
669 template <class Iterator = const char*,
670 class Base = folly::Range<boost::u8_to_u32_iterator<Iterator>>>
671 class UTF8Range : public Base {
673 /* implicit */ UTF8Range(const folly::Range<Iterator> baseRange)
674 : Base(boost::u8_to_u32_iterator<Iterator>(
675 baseRange.begin(), baseRange.begin(), baseRange.end()),
676 boost::u8_to_u32_iterator<Iterator>(
677 baseRange.end(), baseRange.begin(), baseRange.end())) {}
678 /* implicit */ UTF8Range(const std::string& baseString)
679 : Base(folly::Range<Iterator>(baseString)) {}
682 using UTF8StringPiece = UTF8Range<const char*>;
686 // Hook into boost's type traits
689 struct has_nothrow_constructor<folly::basic_fbstring<T> > : true_type {
690 enum { value = true };
694 #include <folly/String-inl.h>