2 * Copyright 2014 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.
17 #ifndef FOLLY_BASE_STRING_H_
18 #define FOLLY_BASE_STRING_H_
22 #include <boost/type_traits.hpp>
24 #ifdef FOLLY_HAVE_DEPRECATED_ASSOC
25 #ifdef _GLIBCXX_SYMVER
26 #include <ext/hash_set>
27 #include <ext/hash_map>
31 #include <unordered_set>
32 #include <unordered_map>
34 #include <folly/Conv.h>
35 #include <folly/Demangle.h>
36 #include <folly/FBString.h>
37 #include <folly/FBVector.h>
38 #include <folly/Portability.h>
39 #include <folly/Range.h>
40 #include <folly/ScopeGuard.h>
42 // Compatibility function, to make sure toStdString(s) can be called
43 // to convert a std::string or fbstring variable s into type std::string
44 // with very little overhead if s was already std::string
48 std::string toStdString(const folly::fbstring& s) {
49 return std::string(s.data(), s.size());
53 const std::string& toStdString(const std::string& s) {
57 // If called with a temporary, the compiler will select this overload instead
58 // of the above, so we don't return a (lvalue) reference to a temporary.
60 std::string&& toStdString(std::string&& s) {
65 * C-Escape a string, making it suitable for representation as a C string
66 * literal. Appends the result to the output string.
68 * Backslashes all occurrences of backslash and double-quote:
72 * Replaces all non-printable ASCII characters with backslash-octal
76 * Note that we use backslash-octal instead of backslash-hex because the octal
77 * representation is guaranteed to consume no more than 3 characters; "\3760"
78 * represents two characters, one with value 254, and one with value 48 ('0'),
79 * whereas "\xfe0" represents only one character (with value 4064, which leads
80 * to implementation-defined behavior).
82 template <class String>
83 void cEscape(StringPiece str, String& out);
86 * Similar to cEscape above, but returns the escaped string.
88 template <class String>
89 String cEscape(StringPiece str) {
96 * C-Unescape a string; the opposite of cEscape above. Appends the result
97 * to the output string.
99 * Recognizes the standard C escape sequences:
101 * \' \" \? \\ \a \b \f \n \r \t \v
105 * In strict mode (default), throws std::invalid_argument if it encounters
106 * an unrecognized escape sequence. In non-strict mode, it leaves
107 * the escape sequence unchanged.
109 template <class String>
110 void cUnescape(StringPiece str, String& out, bool strict = true);
113 * Similar to cUnescape above, but returns the escaped string.
115 template <class String>
116 String cUnescape(StringPiece str, bool strict = true) {
118 cUnescape(str, out, strict);
123 * URI-escape a string. Appends the result to the output string.
125 * Alphanumeric characters and other characters marked as "unreserved" in RFC
126 * 3986 ( -_.~ ) are left unchanged. In PATH mode, the forward slash (/) is
127 * also left unchanged. In QUERY mode, spaces are replaced by '+'. All other
128 * characters are percent-encoded.
130 enum class UriEscapeMode : unsigned char {
131 // The values are meaningful, see generate_escape_tables.py
136 template <class String>
137 void uriEscape(StringPiece str,
139 UriEscapeMode mode = UriEscapeMode::ALL);
142 * Similar to uriEscape above, but returns the escaped string.
144 template <class String>
145 String uriEscape(StringPiece str, UriEscapeMode mode = UriEscapeMode::ALL) {
147 uriEscape(str, out, mode);
152 * URI-unescape a string. Appends the result to the output string.
154 * In QUERY mode, '+' are replaced by space. %XX sequences are decoded if
155 * XX is a valid hex sequence, otherwise we throw invalid_argument.
157 template <class String>
158 void uriUnescape(StringPiece str,
160 UriEscapeMode mode = UriEscapeMode::ALL);
163 * Similar to uriUnescape above, but returns the unescaped string.
165 template <class String>
166 String uriUnescape(StringPiece str, UriEscapeMode mode = UriEscapeMode::ALL) {
168 uriUnescape(str, out, mode);
173 * stringPrintf is much like printf but deposits its result into a
174 * string. Two signatures are supported: the first simply returns the
175 * resulting string, and the second appends the produced characters to
176 * the specified string and returns a reference to it.
178 std::string stringPrintf(FOLLY_PRINTF_FORMAT const char* format, ...)
179 FOLLY_PRINTF_FORMAT_ATTR(1, 2);
181 /* Similar to stringPrintf, with different signature. */
182 void stringPrintf(std::string* out, FOLLY_PRINTF_FORMAT const char* fmt, ...)
183 FOLLY_PRINTF_FORMAT_ATTR(2, 3);
185 std::string& stringAppendf(std::string* output,
186 FOLLY_PRINTF_FORMAT const char* format, ...)
187 FOLLY_PRINTF_FORMAT_ATTR(2, 3);
190 * Similar to stringPrintf, but accepts a va_list argument.
192 * As with vsnprintf() itself, the value of ap is undefined after the call.
193 * These functions do not call va_end() on ap.
195 std::string stringVPrintf(const char* format, va_list ap);
196 void stringVPrintf(std::string* out, const char* format, va_list ap);
197 std::string& stringVAppendf(std::string* out, const char* format, va_list ap);
200 * Backslashify a string, that is, replace non-printable characters
201 * with C-style (but NOT C compliant) "\xHH" encoding. If hex_style
202 * is false, then shorthand notations like "\0" will be used instead
203 * of "\x00" for the most common backslash cases.
205 * There are two forms, one returning the input string, and one
206 * creating output in the specified output string.
208 * This is mainly intended for printing to a terminal, so it is not
209 * particularly optimized.
211 * Do *not* use this in situations where you expect to be able to feed
212 * the string to a C or C++ compiler, as there are nuances with how C
213 * parses such strings that lead to failures. This is for display
214 * purposed only. If you want a string you can embed for use in C or
215 * C++, use cEscape instead. This function is for display purposes
218 template <class String1, class String2>
219 void backslashify(const String1& input, String2& output, bool hex_style=false);
221 template <class String>
222 String backslashify(const String& input, bool hex_style=false) {
224 backslashify(input, output, hex_style);
229 * Take a string and "humanify" it -- that is, make it look better.
230 * Since "better" is subjective, caveat emptor. The basic approach is
231 * to count the number of unprintable characters. If there are none,
232 * then the output is the input. If there are relatively few, or if
233 * there is a long "enough" prefix of printable characters, use
234 * backslashify. If it is mostly binary, then simply hex encode.
236 * This is an attempt to make a computer smart, and so likely is wrong
239 template <class String1, class String2>
240 void humanify(const String1& input, String2& output);
242 template <class String>
243 String humanify(const String& input) {
245 humanify(input, output);
250 * Same functionality as Python's binascii.hexlify. Returns true
251 * on successful conversion.
253 * If append_output is true, append data to the output rather than
256 template<class InputString, class OutputString>
257 bool hexlify(const InputString& input, OutputString& output,
261 * Same functionality as Python's binascii.unhexlify. Returns true
262 * on successful conversion.
264 template<class InputString, class OutputString>
265 bool unhexlify(const InputString& input, OutputString& output);
268 * A pretty-printer for numbers that appends suffixes of units of the
269 * given type. It prints 4 sig-figs of value with the most
272 * If `addSpace' is true, we put a space between the units suffix and
276 * PRETTY_TIME - s, ms, us, ns, etc.
277 * PRETTY_BYTES_METRIC - kB, MB, GB, etc (goes up by 10^3 = 1000 each time)
278 * PRETTY_BYTES - kB, MB, GB, etc (goes up by 2^10 = 1024 each time)
279 * PRETTY_BYTES_IEC - KiB, MiB, GiB, etc
280 * PRETTY_UNITS_METRIC - k, M, G, etc (goes up by 10^3 = 1000 each time)
281 * PRETTY_UNITS_BINARY - k, M, G, etc (goes up by 2^10 = 1024 each time)
282 * PRETTY_UNITS_BINARY_IEC - Ki, Mi, Gi, etc
283 * PRETTY_SI - full SI metric prefixes from yocto to Yotta
284 * http://en.wikipedia.org/wiki/Metric_prefix
285 * @author Mark Rabkin <mrabkin@fb.com>
292 PRETTY_BYTES = PRETTY_BYTES_BINARY,
293 PRETTY_BYTES_BINARY_IEC,
294 PRETTY_BYTES_IEC = PRETTY_BYTES_BINARY_IEC,
298 PRETTY_UNITS_BINARY_IEC,
304 std::string prettyPrint(double val, PrettyType, bool addSpace = true);
307 * This utility converts StringPiece in pretty format (look above) to double,
308 * with progress information. Alters the StringPiece parameter
309 * to get rid of the already-parsed characters.
310 * Expects string in form <floating point number> {space}* [<suffix>]
311 * If string is not in correct format, utility finds longest valid prefix and
312 * if there at least one, returns double value based on that prefix and
313 * modifies string to what is left after parsing. Throws and std::range_error
314 * exception if there is no correct parse.
315 * Examples(for PRETTY_UNITS_METRIC):
316 * '10M' => 10 000 000
317 * '10 M' => 10 000 000
319 * '10 Mx' => 10 000 000, prettyString == "x"
320 * 'abc' => throws std::range_error
322 double prettyToDouble(folly::StringPiece *const prettyString,
323 const PrettyType type);
326 * Same as prettyToDouble(folly::StringPiece*, PrettyType), but
327 * expects whole string to be correctly parseable. Throws std::range_error
330 double prettyToDouble(folly::StringPiece prettyString, const PrettyType type);
333 * Write a hex dump of size bytes starting at ptr to out.
335 * The hex dump is formatted as follows:
337 * for the string "abcdefghijklmnopqrstuvwxyz\x02"
338 00000000 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f 70 |abcdefghijklmnop|
339 00000010 71 72 73 74 75 76 77 78 79 7a 02 |qrstuvwxyz. |
341 * that is, we write 16 bytes per line, both as hex bytes and as printable
342 * characters. Non-printable characters are replaced with '.'
343 * Lines are written to out one by one (one StringPiece at a time) without
346 template <class OutIt>
347 void hexDump(const void* ptr, size_t size, OutIt out);
350 * Return the hex dump of size bytes starting at ptr as a string.
352 std::string hexDump(const void* ptr, size_t size);
355 * Return a fbstring containing the description of the given errno value.
356 * Takes care not to overwrite the actual system errno, so calling
357 * errnoStr(errno) is valid.
359 fbstring errnoStr(int err);
362 * Debug string for an exception: include type and what(), if
365 inline fbstring exceptionStr(const std::exception& e) {
366 return folly::to<fbstring>(demangle(typeid(e)), ": ", e.what());
369 inline fbstring exceptionStr(std::exception_ptr ep) {
371 std::rethrow_exception(ep);
372 } catch (const std::exception& e) {
373 return exceptionStr(e);
375 return "<unknown exception>";
380 auto exceptionStr(const E& e)
381 -> typename std::enable_if<!std::is_base_of<std::exception, E>::value,
384 return folly::to<fbstring>(demangle(typeid(e)));
388 * Split a string into a list of tokens by delimiter.
390 * The split interface here supports different output types, selected
391 * at compile time: StringPiece, fbstring, or std::string. If you are
392 * using a vector to hold the output, it detects the type based on
393 * what your vector contains. If the output vector is not empty, split
394 * will append to the end of the vector.
396 * You can also use splitTo() to write the output to an arbitrary
397 * OutputIterator (e.g. std::inserter() on a std::set<>), in which
398 * case you have to tell the function the type. (Rationale:
399 * OutputIterators don't have a value_type, so we can't detect the
400 * type in splitTo without being told.)
404 * std::vector<folly::StringPiece> v;
405 * folly::split(":", "asd:bsd", v);
407 * std::set<StringPiece> s;
408 * folly::splitTo<StringPiece>(":", "asd:bsd:asd:csd",
409 * std::inserter(s, s.begin()));
411 * Split also takes a flag (ignoreEmpty) that indicates whether adjacent
412 * delimiters should be treated as one single separator (ignoring empty tokens)
413 * or not (generating empty tokens).
416 template<class Delim, class String, class OutputType>
417 void split(const Delim& delimiter,
419 std::vector<OutputType>& out,
420 bool ignoreEmpty = false);
422 template<class Delim, class String, class OutputType>
423 void split(const Delim& delimiter,
425 folly::fbvector<OutputType>& out,
426 bool ignoreEmpty = false);
428 template<class OutputValueType, class Delim, class String,
429 class OutputIterator>
430 void splitTo(const Delim& delimiter,
433 bool ignoreEmpty = false);
436 * Split a string into a fixed number of string pieces and/or numeric types
437 * by delimiter. Any numeric type that folly::to<> can convert to from a
438 * string piece is supported as a target. Returns 'true' if the fields were
439 * all successfully populated.
443 * folly::StringPiece name, key, value;
444 * if (folly::split('\t', line, name, key, value))
447 * folly::StringPiece name;
450 * if (folly::split('\t', line, name, value, id))
453 * The 'exact' template parameter specifies how the function behaves when too
454 * many fields are present in the input string. When 'exact' is set to its
455 * default value of 'true', a call to split will fail if the number of fields in
456 * the input string does not exactly match the number of output parameters
457 * passed. If 'exact' is overridden to 'false', all remaining fields will be
458 * stored, unsplit, in the last field, as shown below:
460 * folly::StringPiece x, y.
461 * if (folly::split<false>(':', "a:b:c", x, y))
462 * assert(x == "a" && y == "b:c");
464 * Note that this will likely not work if the last field's target is of numeric
465 * type, in which case folly::to<> will throw an exception.
468 using IsSplitTargetType = std::integral_constant<bool,
469 std::is_arithmetic<T>::value ||
470 std::is_same<T, StringPiece>::value ||
471 IsSomeString<T>::value>;
473 template<bool exact = true,
476 class... OutputTypes>
477 typename std::enable_if<IsSplitTargetType<OutputType>::value, bool>::type
478 split(const Delim& delimiter,
481 OutputTypes&... outTail);
484 * Join list of tokens.
486 * Stores a string representation of tokens in the same order with
487 * deliminer between each element.
490 template <class Delim, class Iterator, class String>
491 void join(const Delim& delimiter,
496 template <class Delim, class Container, class String>
497 void join(const Delim& delimiter,
498 const Container& container,
500 join(delimiter, container.begin(), container.end(), output);
503 template <class Delim, class Value, class String>
504 void join(const Delim& delimiter,
505 const std::initializer_list<Value>& values,
507 join(delimiter, values.begin(), values.end(), output);
510 template <class Delim, class Container>
511 std::string join(const Delim& delimiter,
512 const Container& container) {
514 join(delimiter, container.begin(), container.end(), output);
518 template <class Delim, class Value>
519 std::string join(const Delim& delimiter,
520 const std::initializer_list<Value>& values) {
522 join(delimiter, values.begin(), values.end(), output);
527 * Returns a subpiece with all whitespace removed from the front of @sp.
528 * Whitespace means any of [' ', '\n', '\r', '\t'].
530 StringPiece skipWhitespace(StringPiece sp);
533 * Fast, in-place lowercasing of ASCII alphabetic characters in strings.
534 * Leaves all other characters unchanged, including those with the 0x80
536 * @param str String to convert
537 * @param len Length of str, in bytes
539 void toLowerAscii(char* str, size_t length);
541 inline void toLowerAscii(MutableStringPiece str) {
542 toLowerAscii(str.begin(), str.size());
547 // Hook into boost's type traits
550 struct has_nothrow_constructor<folly::basic_fbstring<T> > : true_type {
551 enum { value = true };
555 #include <folly/String-inl.h>