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 String1, class String2>
215 void backslashify(const String1& input, String2& output, bool hex_style=false);
217 template <class String>
218 String backslashify(const String& input, bool hex_style=false) {
220 backslashify(input, output, hex_style);
225 * Take a string and "humanify" it -- that is, make it look better.
226 * Since "better" is subjective, caveat emptor. The basic approach is
227 * to count the number of unprintable characters. If there are none,
228 * then the output is the input. If there are relatively few, or if
229 * there is a long "enough" prefix of printable characters, use
230 * backslashify. If it is mostly binary, then simply hex encode.
232 * This is an attempt to make a computer smart, and so likely is wrong
235 template <class String1, class String2>
236 void humanify(const String1& input, String2& output);
238 template <class String>
239 String humanify(const String& input) {
241 humanify(input, output);
246 * Same functionality as Python's binascii.hexlify. Returns true
247 * on successful conversion.
249 * If append_output is true, append data to the output rather than
252 template <class InputString, class OutputString>
253 bool hexlify(const InputString& input, OutputString& output,
256 template <class OutputString = std::string>
257 OutputString hexlify(ByteRange input) {
259 if (!hexlify(input, output)) {
260 // hexlify() currently always returns true, so this can't really happen
261 throw std::runtime_error("hexlify failed");
266 template <class OutputString = std::string>
267 OutputString hexlify(StringPiece input) {
268 return hexlify<OutputString>(ByteRange{input});
272 * Same functionality as Python's binascii.unhexlify. Returns true
273 * on successful conversion.
275 template <class InputString, class OutputString>
276 bool unhexlify(const InputString& input, OutputString& output);
278 template <class OutputString = std::string>
279 OutputString unhexlify(StringPiece input) {
281 if (!unhexlify(input, output)) {
282 // unhexlify() fails if the input has non-hexidecimal characters,
283 // or if it doesn't consist of a whole number of bytes
284 throw std::domain_error("unhexlify() called with non-hex input");
290 * A pretty-printer for numbers that appends suffixes of units of the
291 * given type. It prints 4 sig-figs of value with the most
294 * If `addSpace' is true, we put a space between the units suffix and
298 * PRETTY_TIME - s, ms, us, ns, etc.
299 * PRETTY_BYTES_METRIC - kB, MB, GB, etc (goes up by 10^3 = 1000 each time)
300 * PRETTY_BYTES - kB, MB, GB, etc (goes up by 2^10 = 1024 each time)
301 * PRETTY_BYTES_IEC - KiB, MiB, GiB, etc
302 * PRETTY_UNITS_METRIC - k, M, G, etc (goes up by 10^3 = 1000 each time)
303 * PRETTY_UNITS_BINARY - k, M, G, etc (goes up by 2^10 = 1024 each time)
304 * PRETTY_UNITS_BINARY_IEC - Ki, Mi, Gi, etc
305 * PRETTY_SI - full SI metric prefixes from yocto to Yotta
306 * http://en.wikipedia.org/wiki/Metric_prefix
307 * @author Mark Rabkin <mrabkin@fb.com>
314 PRETTY_BYTES = PRETTY_BYTES_BINARY,
315 PRETTY_BYTES_BINARY_IEC,
316 PRETTY_BYTES_IEC = PRETTY_BYTES_BINARY_IEC,
320 PRETTY_UNITS_BINARY_IEC,
326 std::string prettyPrint(double val, PrettyType, bool addSpace = true);
329 * This utility converts StringPiece in pretty format (look above) to double,
330 * with progress information. Alters the StringPiece parameter
331 * to get rid of the already-parsed characters.
332 * Expects string in form <floating point number> {space}* [<suffix>]
333 * If string is not in correct format, utility finds longest valid prefix and
334 * if there at least one, returns double value based on that prefix and
335 * modifies string to what is left after parsing. Throws and std::range_error
336 * exception if there is no correct parse.
337 * Examples(for PRETTY_UNITS_METRIC):
338 * '10M' => 10 000 000
339 * '10 M' => 10 000 000
341 * '10 Mx' => 10 000 000, prettyString == "x"
342 * 'abc' => throws std::range_error
344 double prettyToDouble(folly::StringPiece *const prettyString,
345 const PrettyType type);
348 * Same as prettyToDouble(folly::StringPiece*, PrettyType), but
349 * expects whole string to be correctly parseable. Throws std::range_error
352 double prettyToDouble(folly::StringPiece prettyString, const PrettyType type);
355 * Write a hex dump of size bytes starting at ptr to out.
357 * The hex dump is formatted as follows:
359 * for the string "abcdefghijklmnopqrstuvwxyz\x02"
360 00000000 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f 70 |abcdefghijklmnop|
361 00000010 71 72 73 74 75 76 77 78 79 7a 02 |qrstuvwxyz. |
363 * that is, we write 16 bytes per line, both as hex bytes and as printable
364 * characters. Non-printable characters are replaced with '.'
365 * Lines are written to out one by one (one StringPiece at a time) without
368 template <class OutIt>
369 void hexDump(const void* ptr, size_t size, OutIt out);
372 * Return the hex dump of size bytes starting at ptr as a string.
374 std::string hexDump(const void* ptr, size_t size);
377 * Return a fbstring containing the description of the given errno value.
378 * Takes care not to overwrite the actual system errno, so calling
379 * errnoStr(errno) is valid.
381 fbstring errnoStr(int err);
384 * Split a string into a list of tokens by delimiter.
386 * The split interface here supports different output types, selected
387 * at compile time: StringPiece, fbstring, or std::string. If you are
388 * using a vector to hold the output, it detects the type based on
389 * what your vector contains. If the output vector is not empty, split
390 * will append to the end of the vector.
392 * You can also use splitTo() to write the output to an arbitrary
393 * OutputIterator (e.g. std::inserter() on a std::set<>), in which
394 * case you have to tell the function the type. (Rationale:
395 * OutputIterators don't have a value_type, so we can't detect the
396 * type in splitTo without being told.)
400 * std::vector<folly::StringPiece> v;
401 * folly::split(":", "asd:bsd", v);
403 * std::set<StringPiece> s;
404 * folly::splitTo<StringPiece>(":", "asd:bsd:asd:csd",
405 * std::inserter(s, s.begin()));
407 * Split also takes a flag (ignoreEmpty) that indicates whether adjacent
408 * delimiters should be treated as one single separator (ignoring empty tokens)
409 * or not (generating empty tokens).
412 template <class Delim, class String, class OutputType>
413 void split(const Delim& delimiter,
415 std::vector<OutputType>& out,
416 const bool ignoreEmpty = false);
418 template <class Delim, class String, class OutputType>
419 void split(const Delim& delimiter,
421 folly::fbvector<OutputType>& out,
422 const bool ignoreEmpty = false);
425 class OutputValueType,
428 class OutputIterator>
429 void splitTo(const Delim& delimiter,
432 const bool ignoreEmpty = false);
435 * Split a string into a fixed number of string pieces and/or numeric types
436 * by delimiter. Conversions are supported for any type which folly:to<> can
437 * target, including all overloads of parseTo(). Returns 'true' if the fields
438 * were all successfully populated. Returns 'false' if there were too few
439 * fields in the input, or too many fields if exact=true. Casting exceptions
440 * will not be caught.
444 * folly::StringPiece name, key, value;
445 * if (folly::split('\t', line, name, key, value))
448 * folly::StringPiece name;
451 * if (folly::split('\t', line, name, value, id))
454 * The 'exact' template parameter specifies how the function behaves when too
455 * many fields are present in the input string. When 'exact' is set to its
456 * default value of 'true', a call to split will fail if the number of fields in
457 * the input string does not exactly match the number of output parameters
458 * passed. If 'exact' is overridden to 'false', all remaining fields will be
459 * stored, unsplit, in the last field, as shown below:
461 * folly::StringPiece x, y.
462 * if (folly::split<false>(':', "a:b:c", x, y))
463 * assert(x == "a" && y == "b:c");
465 * Note that this will likely not work if the last field's target is of numeric
466 * type, in which case folly::to<> will throw an exception.
468 template <class T, class Enable = void>
469 struct IsSomeVector {
470 enum { value = false };
474 struct IsSomeVector<std::vector<T>, void> {
475 enum { value = true };
479 struct IsSomeVector<fbvector<T>, void> {
480 enum { value = true };
483 template <class T, class Enable = void>
484 struct IsConvertible {
485 enum { value = false };
489 struct IsConvertible<
491 decltype(static_cast<void>(
492 parseTo(std::declval<folly::StringPiece>(), std::declval<T&>())))> {
493 enum { value = true };
496 template <class... Types>
497 struct AllConvertible;
499 template <class Head, class... Tail>
500 struct AllConvertible<Head, Tail...> {
501 enum { value = IsConvertible<Head>::value && AllConvertible<Tail...>::value };
505 struct AllConvertible<> {
506 enum { value = true };
509 static_assert(AllConvertible<float>::value, "");
510 static_assert(AllConvertible<int>::value, "");
511 static_assert(AllConvertible<bool>::value, "");
512 static_assert(AllConvertible<int>::value, "");
513 static_assert(!AllConvertible<std::vector<int>>::value, "");
515 template <bool exact = true, class Delim, class... OutputTypes>
516 typename std::enable_if<
517 AllConvertible<OutputTypes...>::value && sizeof...(OutputTypes) >= 1,
519 split(const Delim& delimiter, StringPiece input, OutputTypes&... outputs);
522 * Join list of tokens.
524 * Stores a string representation of tokens in the same order with
525 * deliminer between each element.
528 template <class Delim, class Iterator, class String>
529 void join(const Delim& delimiter,
534 template <class Delim, class Container, class String>
535 void join(const Delim& delimiter,
536 const Container& container,
538 join(delimiter, container.begin(), container.end(), output);
541 template <class Delim, class Value, class String>
542 void join(const Delim& delimiter,
543 const std::initializer_list<Value>& values,
545 join(delimiter, values.begin(), values.end(), output);
548 template <class Delim, class Container>
549 std::string join(const Delim& delimiter,
550 const Container& container) {
552 join(delimiter, container.begin(), container.end(), output);
556 template <class Delim, class Value>
557 std::string join(const Delim& delimiter,
558 const std::initializer_list<Value>& values) {
560 join(delimiter, values.begin(), values.end(), output);
567 typename std::enable_if<std::is_same<
568 typename std::iterator_traits<Iterator>::iterator_category,
569 std::random_access_iterator_tag>::value>::type* = nullptr>
570 std::string join(const Delim& delimiter, Iterator begin, Iterator end) {
572 join(delimiter, begin, end, output);
577 * Returns a subpiece with all whitespace removed from the front of @sp.
578 * Whitespace means any of [' ', '\n', '\r', '\t'].
580 StringPiece ltrimWhitespace(StringPiece sp);
583 * Returns a subpiece with all whitespace removed from the back of @sp.
584 * Whitespace means any of [' ', '\n', '\r', '\t'].
586 StringPiece rtrimWhitespace(StringPiece sp);
589 * Returns a subpiece with all whitespace removed from the back and front of @sp.
590 * Whitespace means any of [' ', '\n', '\r', '\t'].
592 inline StringPiece trimWhitespace(StringPiece sp) {
593 return ltrimWhitespace(rtrimWhitespace(sp));
597 * Returns a subpiece with all whitespace removed from the front of @sp.
598 * Whitespace means any of [' ', '\n', '\r', '\t'].
599 * DEPRECATED: @see ltrimWhitespace @see rtrimWhitespace
601 inline StringPiece skipWhitespace(StringPiece sp) {
602 return ltrimWhitespace(sp);
606 * Strips the leading and the trailing whitespace-only lines. Then looks for
607 * the least indented non-whitespace-only line and removes its amount of
608 * leading whitespace from every line. Assumes leading whitespace is either all
609 * spaces or all tabs.
611 * Purpose: including a multiline string literal in source code, indented to
612 * the level expected from context.
614 std::string stripLeftMargin(std::string s);
617 * Fast, in-place lowercasing of ASCII alphabetic characters in strings.
618 * Leaves all other characters unchanged, including those with the 0x80
620 * @param str String to convert
621 * @param len Length of str, in bytes
623 void toLowerAscii(char* str, size_t length);
625 inline void toLowerAscii(MutableStringPiece str) {
626 toLowerAscii(str.begin(), str.size());
630 class Iterator = const char*,
631 class Base = folly::Range<boost::u8_to_u32_iterator<Iterator>>>
632 class UTF8Range : public Base {
634 /* implicit */ UTF8Range(const folly::Range<Iterator> baseRange)
635 : Base(boost::u8_to_u32_iterator<Iterator>(
636 baseRange.begin(), baseRange.begin(), baseRange.end()),
637 boost::u8_to_u32_iterator<Iterator>(
638 baseRange.end(), baseRange.begin(), baseRange.end())) {}
639 /* implicit */ UTF8Range(const std::string& baseString)
640 : Base(folly::Range<Iterator>(baseString)) {}
643 using UTF8StringPiece = UTF8Range<const char*>;
647 #include <folly/String-inl.h>