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_
24 #include <boost/type_traits.hpp>
25 #include <boost/regex/pending/unicode_iterator.hpp>
27 #ifdef FOLLY_HAVE_DEPRECATED_ASSOC
28 #ifdef _GLIBCXX_SYMVER
29 #include <ext/hash_set>
30 #include <ext/hash_map>
34 #include <unordered_set>
35 #include <unordered_map>
37 #include <folly/Conv.h>
38 #include <folly/ExceptionString.h>
39 #include <folly/FBString.h>
40 #include <folly/FBVector.h>
41 #include <folly/Portability.h>
42 #include <folly/Range.h>
43 #include <folly/ScopeGuard.h>
45 // Compatibility function, to make sure toStdString(s) can be called
46 // to convert a std::string or fbstring variable s into type std::string
47 // with very little overhead if s was already std::string
51 std::string toStdString(const folly::fbstring& s) {
52 return std::string(s.data(), s.size());
56 const std::string& toStdString(const std::string& s) {
60 // If called with a temporary, the compiler will select this overload instead
61 // of the above, so we don't return a (lvalue) reference to a temporary.
63 std::string&& toStdString(std::string&& s) {
68 * C-Escape a string, making it suitable for representation as a C string
69 * literal. Appends the result to the output string.
71 * Backslashes all occurrences of backslash and double-quote:
75 * Replaces all non-printable ASCII characters with backslash-octal
79 * Note that we use backslash-octal instead of backslash-hex because the octal
80 * representation is guaranteed to consume no more than 3 characters; "\3760"
81 * represents two characters, one with value 254, and one with value 48 ('0'),
82 * whereas "\xfe0" represents only one character (with value 4064, which leads
83 * to implementation-defined behavior).
85 template <class String>
86 void cEscape(StringPiece str, String& out);
89 * Similar to cEscape above, but returns the escaped string.
91 template <class String>
92 String cEscape(StringPiece str) {
99 * C-Unescape a string; the opposite of cEscape above. Appends the result
100 * to the output string.
102 * Recognizes the standard C escape sequences:
104 * \' \" \? \\ \a \b \f \n \r \t \v
108 * In strict mode (default), throws std::invalid_argument if it encounters
109 * an unrecognized escape sequence. In non-strict mode, it leaves
110 * the escape sequence unchanged.
112 template <class String>
113 void cUnescape(StringPiece str, String& out, bool strict = true);
116 * Similar to cUnescape above, but returns the escaped string.
118 template <class String>
119 String cUnescape(StringPiece str, bool strict = true) {
121 cUnescape(str, out, strict);
126 * URI-escape a string. Appends the result to the output string.
128 * Alphanumeric characters and other characters marked as "unreserved" in RFC
129 * 3986 ( -_.~ ) are left unchanged. In PATH mode, the forward slash (/) is
130 * also left unchanged. In QUERY mode, spaces are replaced by '+'. All other
131 * characters are percent-encoded.
133 enum class UriEscapeMode : unsigned char {
134 // The values are meaningful, see generate_escape_tables.py
139 template <class String>
140 void uriEscape(StringPiece str,
142 UriEscapeMode mode = UriEscapeMode::ALL);
145 * Similar to uriEscape above, but returns the escaped string.
147 template <class String>
148 String uriEscape(StringPiece str, UriEscapeMode mode = UriEscapeMode::ALL) {
150 uriEscape(str, out, mode);
155 * URI-unescape a string. Appends the result to the output string.
157 * In QUERY mode, '+' are replaced by space. %XX sequences are decoded if
158 * XX is a valid hex sequence, otherwise we throw invalid_argument.
160 template <class String>
161 void uriUnescape(StringPiece str,
163 UriEscapeMode mode = UriEscapeMode::ALL);
166 * Similar to uriUnescape above, but returns the unescaped string.
168 template <class String>
169 String uriUnescape(StringPiece str, UriEscapeMode mode = UriEscapeMode::ALL) {
171 uriUnescape(str, out, mode);
176 * stringPrintf is much like printf but deposits its result into a
177 * string. Two signatures are supported: the first simply returns the
178 * resulting string, and the second appends the produced characters to
179 * the specified string and returns a reference to it.
181 std::string stringPrintf(FOLLY_PRINTF_FORMAT const char* format, ...)
182 FOLLY_PRINTF_FORMAT_ATTR(1, 2);
184 /* Similar to stringPrintf, with different signature. */
185 void stringPrintf(std::string* out, FOLLY_PRINTF_FORMAT const char* fmt, ...)
186 FOLLY_PRINTF_FORMAT_ATTR(2, 3);
188 std::string& stringAppendf(std::string* output,
189 FOLLY_PRINTF_FORMAT const char* format, ...)
190 FOLLY_PRINTF_FORMAT_ATTR(2, 3);
193 * Similar to stringPrintf, but accepts a va_list argument.
195 * As with vsnprintf() itself, the value of ap is undefined after the call.
196 * These functions do not call va_end() on ap.
198 std::string stringVPrintf(const char* format, va_list ap);
199 void stringVPrintf(std::string* out, const char* format, va_list ap);
200 std::string& stringVAppendf(std::string* out, const char* format, va_list ap);
203 * Backslashify a string, that is, replace non-printable characters
204 * with C-style (but NOT C compliant) "\xHH" encoding. If hex_style
205 * is false, then shorthand notations like "\0" will be used instead
206 * of "\x00" for the most common backslash cases.
208 * There are two forms, one returning the input string, and one
209 * creating output in the specified output string.
211 * This is mainly intended for printing to a terminal, so it is not
212 * particularly optimized.
214 * Do *not* use this in situations where you expect to be able to feed
215 * the string to a C or C++ compiler, as there are nuances with how C
216 * parses such strings that lead to failures. This is for display
217 * purposed only. If you want a string you can embed for use in C or
218 * C++, use cEscape instead. This function is for display purposes
221 template <class String1, class String2>
222 void backslashify(const String1& input, String2& output, bool hex_style=false);
224 template <class String>
225 String backslashify(const String& input, bool hex_style=false) {
227 backslashify(input, output, hex_style);
232 * Take a string and "humanify" it -- that is, make it look better.
233 * Since "better" is subjective, caveat emptor. The basic approach is
234 * to count the number of unprintable characters. If there are none,
235 * then the output is the input. If there are relatively few, or if
236 * there is a long "enough" prefix of printable characters, use
237 * backslashify. If it is mostly binary, then simply hex encode.
239 * This is an attempt to make a computer smart, and so likely is wrong
242 template <class String1, class String2>
243 void humanify(const String1& input, String2& output);
245 template <class String>
246 String humanify(const String& input) {
248 humanify(input, output);
253 * Same functionality as Python's binascii.hexlify. Returns true
254 * on successful conversion.
256 * If append_output is true, append data to the output rather than
259 template<class InputString, class OutputString>
260 bool hexlify(const InputString& input, OutputString& output,
263 template <class OutputString = std::string>
264 OutputString hexlify(ByteRange input) {
266 if (!hexlify(input, output)) {
267 // hexlify() currently always returns true, so this can't really happen
268 throw std::runtime_error("hexlify failed");
273 template <class OutputString = std::string>
274 OutputString hexlify(StringPiece input) {
275 return hexlify<OutputString>(ByteRange{input});
279 * Same functionality as Python's binascii.unhexlify. Returns true
280 * on successful conversion.
282 template<class InputString, class OutputString>
283 bool unhexlify(const InputString& input, OutputString& output);
285 template <class OutputString = std::string>
286 OutputString unhexlify(StringPiece input) {
288 if (!unhexlify(input, output)) {
289 // unhexlify() fails if the input has non-hexidecimal characters,
290 // or if it doesn't consist of a whole number of bytes
291 throw std::domain_error("unhexlify() called with non-hex input");
297 * A pretty-printer for numbers that appends suffixes of units of the
298 * given type. It prints 4 sig-figs of value with the most
301 * If `addSpace' is true, we put a space between the units suffix and
305 * PRETTY_TIME - s, ms, us, ns, etc.
306 * PRETTY_BYTES_METRIC - kB, MB, GB, etc (goes up by 10^3 = 1000 each time)
307 * PRETTY_BYTES - kB, MB, GB, etc (goes up by 2^10 = 1024 each time)
308 * PRETTY_BYTES_IEC - KiB, MiB, GiB, etc
309 * PRETTY_UNITS_METRIC - k, M, G, etc (goes up by 10^3 = 1000 each time)
310 * PRETTY_UNITS_BINARY - k, M, G, etc (goes up by 2^10 = 1024 each time)
311 * PRETTY_UNITS_BINARY_IEC - Ki, Mi, Gi, etc
312 * PRETTY_SI - full SI metric prefixes from yocto to Yotta
313 * http://en.wikipedia.org/wiki/Metric_prefix
314 * @author Mark Rabkin <mrabkin@fb.com>
321 PRETTY_BYTES = PRETTY_BYTES_BINARY,
322 PRETTY_BYTES_BINARY_IEC,
323 PRETTY_BYTES_IEC = PRETTY_BYTES_BINARY_IEC,
327 PRETTY_UNITS_BINARY_IEC,
333 std::string prettyPrint(double val, PrettyType, bool addSpace = true);
336 * This utility converts StringPiece in pretty format (look above) to double,
337 * with progress information. Alters the StringPiece parameter
338 * to get rid of the already-parsed characters.
339 * Expects string in form <floating point number> {space}* [<suffix>]
340 * If string is not in correct format, utility finds longest valid prefix and
341 * if there at least one, returns double value based on that prefix and
342 * modifies string to what is left after parsing. Throws and std::range_error
343 * exception if there is no correct parse.
344 * Examples(for PRETTY_UNITS_METRIC):
345 * '10M' => 10 000 000
346 * '10 M' => 10 000 000
348 * '10 Mx' => 10 000 000, prettyString == "x"
349 * 'abc' => throws std::range_error
351 double prettyToDouble(folly::StringPiece *const prettyString,
352 const PrettyType type);
355 * Same as prettyToDouble(folly::StringPiece*, PrettyType), but
356 * expects whole string to be correctly parseable. Throws std::range_error
359 double prettyToDouble(folly::StringPiece prettyString, const PrettyType type);
362 * Write a hex dump of size bytes starting at ptr to out.
364 * The hex dump is formatted as follows:
366 * for the string "abcdefghijklmnopqrstuvwxyz\x02"
367 00000000 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f 70 |abcdefghijklmnop|
368 00000010 71 72 73 74 75 76 77 78 79 7a 02 |qrstuvwxyz. |
370 * that is, we write 16 bytes per line, both as hex bytes and as printable
371 * characters. Non-printable characters are replaced with '.'
372 * Lines are written to out one by one (one StringPiece at a time) without
375 template <class OutIt>
376 void hexDump(const void* ptr, size_t size, OutIt out);
379 * Return the hex dump of size bytes starting at ptr as a string.
381 std::string hexDump(const void* ptr, size_t size);
384 * Return a fbstring containing the description of the given errno value.
385 * Takes care not to overwrite the actual system errno, so calling
386 * errnoStr(errno) is valid.
388 fbstring errnoStr(int err);
391 * Split a string into a list of tokens by delimiter.
393 * The split interface here supports different output types, selected
394 * at compile time: StringPiece, fbstring, or std::string. If you are
395 * using a vector to hold the output, it detects the type based on
396 * what your vector contains. If the output vector is not empty, split
397 * will append to the end of the vector.
399 * You can also use splitTo() to write the output to an arbitrary
400 * OutputIterator (e.g. std::inserter() on a std::set<>), in which
401 * case you have to tell the function the type. (Rationale:
402 * OutputIterators don't have a value_type, so we can't detect the
403 * type in splitTo without being told.)
407 * std::vector<folly::StringPiece> v;
408 * folly::split(":", "asd:bsd", v);
410 * std::set<StringPiece> s;
411 * folly::splitTo<StringPiece>(":", "asd:bsd:asd:csd",
412 * std::inserter(s, s.begin()));
414 * Split also takes a flag (ignoreEmpty) that indicates whether adjacent
415 * delimiters should be treated as one single separator (ignoring empty tokens)
416 * or not (generating empty tokens).
419 template<class Delim, class String, class OutputType>
420 void split(const Delim& delimiter,
422 std::vector<OutputType>& out,
423 const bool ignoreEmpty = false);
425 template<class Delim, class String, class OutputType>
426 void split(const Delim& delimiter,
428 folly::fbvector<OutputType>& out,
429 const bool ignoreEmpty = false);
431 template<class OutputValueType, class Delim, class String,
432 class OutputIterator>
433 void splitTo(const Delim& delimiter,
436 const bool ignoreEmpty = false);
439 * Split a string into a fixed number of string pieces and/or numeric types
440 * by delimiter. Conversions are supported for any type which folly:to<> can
441 * target, including all overloads of parseTo(). Returns 'true' if the fields
442 * were all successfully populated. Returns 'false' if there were too few
443 * fields in the input, or too many fields if exact=true. Casting exceptions
444 * will not be caught.
448 * folly::StringPiece name, key, value;
449 * if (folly::split('\t', line, name, key, value))
452 * folly::StringPiece name;
455 * if (folly::split('\t', line, name, value, id))
458 * The 'exact' template parameter specifies how the function behaves when too
459 * many fields are present in the input string. When 'exact' is set to its
460 * default value of 'true', a call to split will fail if the number of fields in
461 * the input string does not exactly match the number of output parameters
462 * passed. If 'exact' is overridden to 'false', all remaining fields will be
463 * stored, unsplit, in the last field, as shown below:
465 * folly::StringPiece x, y.
466 * if (folly::split<false>(':', "a:b:c", x, y))
467 * assert(x == "a" && y == "b:c");
469 * Note that this will likely not work if the last field's target is of numeric
470 * type, in which case folly::to<> will throw an exception.
472 template <class T, class Enable = void>
473 struct IsSomeVector {
474 enum { value = false };
478 struct IsSomeVector<std::vector<T>, void> {
479 enum { value = true };
483 struct IsSomeVector<fbvector<T>, void> {
484 enum { value = true };
487 template <class T, class Enable = void>
488 struct IsConvertible {
489 enum { value = false };
493 struct IsConvertible<
495 decltype(static_cast<void>(
496 parseTo(std::declval<folly::StringPiece>(), std::declval<T&>())))> {
497 enum { value = true };
500 template <class... Types>
501 struct AllConvertible;
503 template <class Head, class... Tail>
504 struct AllConvertible<Head, Tail...> {
505 enum { value = IsConvertible<Head>::value && AllConvertible<Tail...>::value };
509 struct AllConvertible<> {
510 enum { value = true };
513 static_assert(AllConvertible<float>::value, "");
514 static_assert(AllConvertible<int>::value, "");
515 static_assert(AllConvertible<bool>::value, "");
516 static_assert(AllConvertible<int>::value, "");
517 static_assert(!AllConvertible<std::vector<int>>::value, "");
519 template <bool exact = true, class Delim, class... OutputTypes>
520 typename std::enable_if<
521 AllConvertible<OutputTypes...>::value && sizeof...(OutputTypes) >= 1,
523 split(const Delim& delimiter, StringPiece input, OutputTypes&... outputs);
526 * Join list of tokens.
528 * Stores a string representation of tokens in the same order with
529 * deliminer between each element.
532 template <class Delim, class Iterator, class String>
533 void join(const Delim& delimiter,
538 template <class Delim, class Container, class String>
539 void join(const Delim& delimiter,
540 const Container& container,
542 join(delimiter, container.begin(), container.end(), output);
545 template <class Delim, class Value, class String>
546 void join(const Delim& delimiter,
547 const std::initializer_list<Value>& values,
549 join(delimiter, values.begin(), values.end(), output);
552 template <class Delim, class Container>
553 std::string join(const Delim& delimiter,
554 const Container& container) {
556 join(delimiter, container.begin(), container.end(), output);
560 template <class Delim, class Value>
561 std::string join(const Delim& delimiter,
562 const std::initializer_list<Value>& values) {
564 join(delimiter, values.begin(), values.end(), output);
568 template <class Delim,
570 typename std::enable_if<std::is_same<
571 typename std::iterator_traits<Iterator>::iterator_category,
572 std::random_access_iterator_tag>::value>::type* = nullptr>
573 std::string join(const Delim& delimiter, Iterator begin, Iterator end) {
575 join(delimiter, begin, end, output);
580 * Returns a subpiece with all whitespace removed from the front of @sp.
581 * Whitespace means any of [' ', '\n', '\r', '\t'].
583 StringPiece ltrimWhitespace(StringPiece sp);
586 * Returns a subpiece with all whitespace removed from the back of @sp.
587 * Whitespace means any of [' ', '\n', '\r', '\t'].
589 StringPiece rtrimWhitespace(StringPiece sp);
592 * Returns a subpiece with all whitespace removed from the back and front of @sp.
593 * Whitespace means any of [' ', '\n', '\r', '\t'].
595 inline StringPiece trimWhitespace(StringPiece sp) {
596 return ltrimWhitespace(rtrimWhitespace(sp));
600 * Returns a subpiece with all whitespace removed from the front of @sp.
601 * Whitespace means any of [' ', '\n', '\r', '\t'].
602 * DEPRECATED: @see ltrimWhitespace @see rtrimWhitespace
604 inline StringPiece skipWhitespace(StringPiece sp) {
605 return ltrimWhitespace(sp);
609 * Strips the leading and the trailing whitespace-only lines. Then looks for
610 * the least indented non-whitespace-only line and removes its amount of
611 * leading whitespace from every line. Assumes leading whitespace is either all
612 * spaces or all tabs.
614 * Purpose: including a multiline string literal in source code, indented to
615 * the level expected from context.
617 std::string stripLeftMargin(std::string s);
620 * Fast, in-place lowercasing of ASCII alphabetic characters in strings.
621 * Leaves all other characters unchanged, including those with the 0x80
623 * @param str String to convert
624 * @param len Length of str, in bytes
626 void toLowerAscii(char* str, size_t length);
628 inline void toLowerAscii(MutableStringPiece str) {
629 toLowerAscii(str.begin(), str.size());
632 template <class Iterator = const char*,
633 class Base = folly::Range<boost::u8_to_u32_iterator<Iterator>>>
634 class UTF8Range : public Base {
636 /* implicit */ UTF8Range(const folly::Range<Iterator> baseRange)
637 : Base(boost::u8_to_u32_iterator<Iterator>(
638 baseRange.begin(), baseRange.begin(), baseRange.end()),
639 boost::u8_to_u32_iterator<Iterator>(
640 baseRange.end(), baseRange.begin(), baseRange.end())) {}
641 /* implicit */ UTF8Range(const std::string& baseString)
642 : Base(folly::Range<Iterator>(baseString)) {}
645 using UTF8StringPiece = UTF8Range<const char*>;
649 // Hook into boost's type traits
652 struct has_nothrow_constructor<folly::basic_fbstring<T> > : true_type {
653 enum { value = true };
657 #include <folly/String-inl.h>