2 * Copyright 2017 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 <unordered_map>
24 #include <unordered_set>
27 #include <boost/regex/pending/unicode_iterator.hpp>
28 #include <boost/type_traits.hpp>
30 #include <folly/Conv.h>
31 #include <folly/ExceptionString.h>
32 #include <folly/FBString.h>
33 #include <folly/FBVector.h>
34 #include <folly/Portability.h>
35 #include <folly/Range.h>
36 #include <folly/ScopeGuard.h>
38 // Compatibility function, to make sure toStdString(s) can be called
39 // to convert a std::string or fbstring variable s into type std::string
40 // with very little overhead if s was already std::string
44 std::string toStdString(const folly::fbstring& s) {
45 return std::string(s.data(), s.size());
49 const std::string& toStdString(const std::string& s) {
53 // If called with a temporary, the compiler will select this overload instead
54 // of the above, so we don't return a (lvalue) reference to a temporary.
56 std::string&& toStdString(std::string&& s) {
61 * C-Escape a string, making it suitable for representation as a C string
62 * literal. Appends the result to the output string.
64 * Backslashes all occurrences of backslash and double-quote:
68 * Replaces all non-printable ASCII characters with backslash-octal
72 * Note that we use backslash-octal instead of backslash-hex because the octal
73 * representation is guaranteed to consume no more than 3 characters; "\3760"
74 * represents two characters, one with value 254, and one with value 48 ('0'),
75 * whereas "\xfe0" represents only one character (with value 4064, which leads
76 * to implementation-defined behavior).
78 template <class String>
79 void cEscape(StringPiece str, String& out);
82 * Similar to cEscape above, but returns the escaped string.
84 template <class String>
85 String cEscape(StringPiece str) {
92 * C-Unescape a string; the opposite of cEscape above. Appends the result
93 * to the output string.
95 * Recognizes the standard C escape sequences:
97 * \' \" \? \\ \a \b \f \n \r \t \v
101 * In strict mode (default), throws std::invalid_argument if it encounters
102 * an unrecognized escape sequence. In non-strict mode, it leaves
103 * the escape sequence unchanged.
105 template <class String>
106 void cUnescape(StringPiece str, String& out, bool strict = true);
109 * Similar to cUnescape above, but returns the escaped string.
111 template <class String>
112 String cUnescape(StringPiece str, bool strict = true) {
114 cUnescape(str, out, strict);
119 * URI-escape a string. Appends the result to the output string.
121 * Alphanumeric characters and other characters marked as "unreserved" in RFC
122 * 3986 ( -_.~ ) are left unchanged. In PATH mode, the forward slash (/) is
123 * also left unchanged. In QUERY mode, spaces are replaced by '+'. All other
124 * characters are percent-encoded.
126 enum class UriEscapeMode : unsigned char {
127 // The values are meaningful, see generate_escape_tables.py
132 template <class String>
133 void uriEscape(StringPiece str,
135 UriEscapeMode mode = UriEscapeMode::ALL);
138 * Similar to uriEscape above, but returns the escaped string.
140 template <class String>
141 String uriEscape(StringPiece str, UriEscapeMode mode = UriEscapeMode::ALL) {
143 uriEscape(str, out, mode);
148 * URI-unescape a string. Appends the result to the output string.
150 * In QUERY mode, '+' are replaced by space. %XX sequences are decoded if
151 * XX is a valid hex sequence, otherwise we throw invalid_argument.
153 template <class String>
154 void uriUnescape(StringPiece str,
156 UriEscapeMode mode = UriEscapeMode::ALL);
159 * Similar to uriUnescape above, but returns the unescaped string.
161 template <class String>
162 String uriUnescape(StringPiece str, UriEscapeMode mode = UriEscapeMode::ALL) {
164 uriUnescape(str, out, mode);
169 * stringPrintf is much like printf but deposits its result into a
170 * string. Two signatures are supported: the first simply returns the
171 * resulting string, and the second appends the produced characters to
172 * the specified string and returns a reference to it.
174 std::string stringPrintf(FOLLY_PRINTF_FORMAT const char* format, ...)
175 FOLLY_PRINTF_FORMAT_ATTR(1, 2);
177 /* Similar to stringPrintf, with different signature. */
178 void stringPrintf(std::string* out, FOLLY_PRINTF_FORMAT const char* fmt, ...)
179 FOLLY_PRINTF_FORMAT_ATTR(2, 3);
181 std::string& stringAppendf(std::string* output,
182 FOLLY_PRINTF_FORMAT const char* format, ...)
183 FOLLY_PRINTF_FORMAT_ATTR(2, 3);
186 * Similar to stringPrintf, but accepts a va_list argument.
188 * As with vsnprintf() itself, the value of ap is undefined after the call.
189 * These functions do not call va_end() on ap.
191 std::string stringVPrintf(const char* format, va_list ap);
192 void stringVPrintf(std::string* out, const char* format, va_list ap);
193 std::string& stringVAppendf(std::string* out, const char* format, va_list ap);
196 * Backslashify a string, that is, replace non-printable characters
197 * with C-style (but NOT C compliant) "\xHH" encoding. If hex_style
198 * is false, then shorthand notations like "\0" will be used instead
199 * of "\x00" for the most common backslash cases.
201 * There are two forms, one returning the input string, and one
202 * creating output in the specified output string.
204 * This is mainly intended for printing to a terminal, so it is not
205 * particularly optimized.
207 * Do *not* use this in situations where you expect to be able to feed
208 * the string to a C or C++ compiler, as there are nuances with how C
209 * parses such strings that lead to failures. This is for display
210 * purposed only. If you want a string you can embed for use in C or
211 * C++, use cEscape instead. This function is for display purposes
214 template <class OutputString>
216 folly::StringPiece input,
217 OutputString& output,
218 bool hex_style = false);
220 template <class OutputString = std::string>
221 OutputString backslashify(StringPiece input, bool hex_style = false) {
223 backslashify(input, output, hex_style);
228 * Take a string and "humanify" it -- that is, make it look better.
229 * Since "better" is subjective, caveat emptor. The basic approach is
230 * to count the number of unprintable characters. If there are none,
231 * then the output is the input. If there are relatively few, or if
232 * there is a long "enough" prefix of printable characters, use
233 * backslashify. If it is mostly binary, then simply hex encode.
235 * This is an attempt to make a computer smart, and so likely is wrong
238 template <class String1, class String2>
239 void humanify(const String1& input, String2& output);
241 template <class String>
242 String humanify(const String& input) {
244 humanify(input, output);
249 * Same functionality as Python's binascii.hexlify. Returns true
250 * on successful conversion.
252 * If append_output is true, append data to the output rather than
255 template <class InputString, class OutputString>
256 bool hexlify(const InputString& input, OutputString& output,
259 template <class OutputString = std::string>
260 OutputString hexlify(ByteRange input) {
262 if (!hexlify(input, output)) {
263 // hexlify() currently always returns true, so this can't really happen
264 throw std::runtime_error("hexlify failed");
269 template <class OutputString = std::string>
270 OutputString hexlify(StringPiece input) {
271 return hexlify<OutputString>(ByteRange{input});
275 * Same functionality as Python's binascii.unhexlify. Returns true
276 * on successful conversion.
278 template <class InputString, class OutputString>
279 bool unhexlify(const InputString& input, OutputString& output);
281 template <class OutputString = std::string>
282 OutputString unhexlify(StringPiece input) {
284 if (!unhexlify(input, output)) {
285 // unhexlify() fails if the input has non-hexidecimal characters,
286 // or if it doesn't consist of a whole number of bytes
287 throw std::domain_error("unhexlify() called with non-hex input");
293 * A pretty-printer for numbers that appends suffixes of units of the
294 * given type. It prints 4 sig-figs of value with the most
297 * If `addSpace' is true, we put a space between the units suffix and
301 * PRETTY_TIME - s, ms, us, ns, etc.
302 * PRETTY_BYTES_METRIC - kB, MB, GB, etc (goes up by 10^3 = 1000 each time)
303 * PRETTY_BYTES - kB, MB, GB, etc (goes up by 2^10 = 1024 each time)
304 * PRETTY_BYTES_IEC - KiB, MiB, GiB, etc
305 * PRETTY_UNITS_METRIC - k, M, G, etc (goes up by 10^3 = 1000 each time)
306 * PRETTY_UNITS_BINARY - k, M, G, etc (goes up by 2^10 = 1024 each time)
307 * PRETTY_UNITS_BINARY_IEC - Ki, Mi, Gi, etc
308 * PRETTY_SI - full SI metric prefixes from yocto to Yotta
309 * http://en.wikipedia.org/wiki/Metric_prefix
310 * @author Mark Rabkin <mrabkin@fb.com>
317 PRETTY_BYTES = PRETTY_BYTES_BINARY,
318 PRETTY_BYTES_BINARY_IEC,
319 PRETTY_BYTES_IEC = PRETTY_BYTES_BINARY_IEC,
323 PRETTY_UNITS_BINARY_IEC,
329 std::string prettyPrint(double val, PrettyType, bool addSpace = true);
332 * This utility converts StringPiece in pretty format (look above) to double,
333 * with progress information. Alters the StringPiece parameter
334 * to get rid of the already-parsed characters.
335 * Expects string in form <floating point number> {space}* [<suffix>]
336 * If string is not in correct format, utility finds longest valid prefix and
337 * if there at least one, returns double value based on that prefix and
338 * modifies string to what is left after parsing. Throws and std::range_error
339 * exception if there is no correct parse.
340 * Examples(for PRETTY_UNITS_METRIC):
341 * '10M' => 10 000 000
342 * '10 M' => 10 000 000
344 * '10 Mx' => 10 000 000, prettyString == "x"
345 * 'abc' => throws std::range_error
347 double prettyToDouble(folly::StringPiece *const prettyString,
348 const PrettyType type);
351 * Same as prettyToDouble(folly::StringPiece*, PrettyType), but
352 * expects whole string to be correctly parseable. Throws std::range_error
355 double prettyToDouble(folly::StringPiece prettyString, const PrettyType type);
358 * Write a hex dump of size bytes starting at ptr to out.
360 * The hex dump is formatted as follows:
362 * for the string "abcdefghijklmnopqrstuvwxyz\x02"
363 00000000 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f 70 |abcdefghijklmnop|
364 00000010 71 72 73 74 75 76 77 78 79 7a 02 |qrstuvwxyz. |
366 * that is, we write 16 bytes per line, both as hex bytes and as printable
367 * characters. Non-printable characters are replaced with '.'
368 * Lines are written to out one by one (one StringPiece at a time) without
371 template <class OutIt>
372 void hexDump(const void* ptr, size_t size, OutIt out);
375 * Return the hex dump of size bytes starting at ptr as a string.
377 std::string hexDump(const void* ptr, size_t size);
380 * Return a fbstring containing the description of the given errno value.
381 * Takes care not to overwrite the actual system errno, so calling
382 * errnoStr(errno) is valid.
384 fbstring errnoStr(int err);
387 * Split a string into a list of tokens by delimiter.
389 * The split interface here supports different output types, selected
390 * at compile time: StringPiece, fbstring, or std::string. If you are
391 * using a vector to hold the output, it detects the type based on
392 * what your vector contains. If the output vector is not empty, split
393 * will append to the end of the vector.
395 * You can also use splitTo() to write the output to an arbitrary
396 * OutputIterator (e.g. std::inserter() on a std::set<>), in which
397 * case you have to tell the function the type. (Rationale:
398 * OutputIterators don't have a value_type, so we can't detect the
399 * type in splitTo without being told.)
403 * std::vector<folly::StringPiece> v;
404 * folly::split(":", "asd:bsd", v);
406 * std::set<StringPiece> s;
407 * folly::splitTo<StringPiece>(":", "asd:bsd:asd:csd",
408 * std::inserter(s, s.begin()));
410 * Split also takes a flag (ignoreEmpty) that indicates whether adjacent
411 * delimiters should be treated as one single separator (ignoring empty tokens)
412 * or not (generating empty tokens).
415 template <class Delim, class String, class OutputType>
416 void split(const Delim& delimiter,
418 std::vector<OutputType>& out,
419 const bool ignoreEmpty = false);
421 template <class Delim, class String, class OutputType>
422 void split(const Delim& delimiter,
424 folly::fbvector<OutputType>& out,
425 const bool ignoreEmpty = false);
428 class OutputValueType,
431 class OutputIterator>
432 void splitTo(const Delim& delimiter,
435 const bool ignoreEmpty = false);
438 * Split a string into a fixed number of string pieces and/or numeric types
439 * by delimiter. Conversions are supported for any type which folly:to<> can
440 * target, including all overloads of parseTo(). Returns 'true' if the fields
441 * were all successfully populated. Returns 'false' if there were too few
442 * fields in the input, or too many fields if exact=true. Casting exceptions
443 * will not be caught.
447 * folly::StringPiece name, key, value;
448 * if (folly::split('\t', line, name, key, value))
451 * folly::StringPiece name;
454 * if (folly::split('\t', line, name, value, id))
457 * The 'exact' template parameter specifies how the function behaves when too
458 * many fields are present in the input string. When 'exact' is set to its
459 * default value of 'true', a call to split will fail if the number of fields in
460 * the input string does not exactly match the number of output parameters
461 * passed. If 'exact' is overridden to 'false', all remaining fields will be
462 * stored, unsplit, in the last field, as shown below:
464 * folly::StringPiece x, y.
465 * if (folly::split<false>(':', "a:b:c", x, y))
466 * assert(x == "a" && y == "b:c");
468 * Note that this will likely not work if the last field's target is of numeric
469 * type, in which case folly::to<> will throw an exception.
471 template <class T, class Enable = void>
472 struct IsSomeVector {
473 enum { value = false };
477 struct IsSomeVector<std::vector<T>, void> {
478 enum { value = true };
482 struct IsSomeVector<fbvector<T>, void> {
483 enum { value = true };
486 template <class T, class Enable = void>
487 struct IsConvertible {
488 enum { value = false };
492 struct IsConvertible<
494 decltype(static_cast<void>(
495 parseTo(std::declval<folly::StringPiece>(), std::declval<T&>())))> {
496 enum { value = true };
499 template <class... Types>
500 struct AllConvertible;
502 template <class Head, class... Tail>
503 struct AllConvertible<Head, Tail...> {
504 enum { value = IsConvertible<Head>::value && AllConvertible<Tail...>::value };
508 struct AllConvertible<> {
509 enum { value = true };
512 static_assert(AllConvertible<float>::value, "");
513 static_assert(AllConvertible<int>::value, "");
514 static_assert(AllConvertible<bool>::value, "");
515 static_assert(AllConvertible<int>::value, "");
516 static_assert(!AllConvertible<std::vector<int>>::value, "");
518 template <bool exact = true, class Delim, class... OutputTypes>
519 typename std::enable_if<
520 AllConvertible<OutputTypes...>::value && sizeof...(OutputTypes) >= 1,
522 split(const Delim& delimiter, StringPiece input, OutputTypes&... outputs);
525 * Join list of tokens.
527 * Stores a string representation of tokens in the same order with
528 * deliminer between each element.
531 template <class Delim, class Iterator, class String>
532 void join(const Delim& delimiter,
537 template <class Delim, class Container, class String>
538 void join(const Delim& delimiter,
539 const Container& container,
541 join(delimiter, container.begin(), container.end(), output);
544 template <class Delim, class Value, class String>
545 void join(const Delim& delimiter,
546 const std::initializer_list<Value>& values,
548 join(delimiter, values.begin(), values.end(), output);
551 template <class Delim, class Container>
552 std::string join(const Delim& delimiter,
553 const Container& container) {
555 join(delimiter, container.begin(), container.end(), output);
559 template <class Delim, class Value>
560 std::string join(const Delim& delimiter,
561 const std::initializer_list<Value>& values) {
563 join(delimiter, values.begin(), values.end(), output);
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 length 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 inline void toLowerAscii(std::string& str) {
633 // str[0] is legal also if the string is empty.
634 toLowerAscii(&str[0], str.size());
638 class Iterator = const char*,
639 class Base = folly::Range<boost::u8_to_u32_iterator<Iterator>>>
640 class UTF8Range : public Base {
642 /* implicit */ UTF8Range(const folly::Range<Iterator> baseRange)
643 : Base(boost::u8_to_u32_iterator<Iterator>(
644 baseRange.begin(), baseRange.begin(), baseRange.end()),
645 boost::u8_to_u32_iterator<Iterator>(
646 baseRange.end(), baseRange.begin(), baseRange.end())) {}
647 /* implicit */ UTF8Range(const std::string& baseString)
648 : Base(folly::Range<Iterator>(baseString)) {}
651 using UTF8StringPiece = UTF8Range<const char*>;
655 #include <folly/String-inl.h>