folly/wangle -> wangle cutover
[folly.git] / folly / String.h
1 /*
2  * Copyright 2015 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #ifndef FOLLY_BASE_STRING_H_
18 #define FOLLY_BASE_STRING_H_
19
20 #include <exception>
21 #include <stdarg.h>
22 #include <string>
23 #include <boost/type_traits.hpp>
24
25 #ifdef FOLLY_HAVE_DEPRECATED_ASSOC
26 #ifdef _GLIBCXX_SYMVER
27 #include <ext/hash_set>
28 #include <ext/hash_map>
29 #endif
30 #endif
31
32 #include <unordered_set>
33 #include <unordered_map>
34
35 #include <folly/Conv.h>
36 #include <folly/Demangle.h>
37 #include <folly/FBString.h>
38 #include <folly/FBVector.h>
39 #include <folly/Portability.h>
40 #include <folly/Range.h>
41 #include <folly/ScopeGuard.h>
42
43 // Compatibility function, to make sure toStdString(s) can be called
44 // to convert a std::string or fbstring variable s into type std::string
45 // with very little overhead if s was already std::string
46 namespace folly {
47
48 inline
49 std::string toStdString(const folly::fbstring& s) {
50   return std::string(s.data(), s.size());
51 }
52
53 inline
54 const std::string& toStdString(const std::string& s) {
55   return s;
56 }
57
58 // If called with a temporary, the compiler will select this overload instead
59 // of the above, so we don't return a (lvalue) reference to a temporary.
60 inline
61 std::string&& toStdString(std::string&& s) {
62   return std::move(s);
63 }
64
65 /**
66  * C-Escape a string, making it suitable for representation as a C string
67  * literal.  Appends the result to the output string.
68  *
69  * Backslashes all occurrences of backslash and double-quote:
70  *   "  ->  \"
71  *   \  ->  \\
72  *
73  * Replaces all non-printable ASCII characters with backslash-octal
74  * representation:
75  *   <ASCII 254> -> \376
76  *
77  * Note that we use backslash-octal instead of backslash-hex because the octal
78  * representation is guaranteed to consume no more than 3 characters; "\3760"
79  * represents two characters, one with value 254, and one with value 48 ('0'),
80  * whereas "\xfe0" represents only one character (with value 4064, which leads
81  * to implementation-defined behavior).
82  */
83 template <class String>
84 void cEscape(StringPiece str, String& out);
85
86 /**
87  * Similar to cEscape above, but returns the escaped string.
88  */
89 template <class String>
90 String cEscape(StringPiece str) {
91   String out;
92   cEscape(str, out);
93   return out;
94 }
95
96 /**
97  * C-Unescape a string; the opposite of cEscape above.  Appends the result
98  * to the output string.
99  *
100  * Recognizes the standard C escape sequences:
101  *
102  * \' \" \? \\ \a \b \f \n \r \t \v
103  * \[0-7]+
104  * \x[0-9a-fA-F]+
105  *
106  * In strict mode (default), throws std::invalid_argument if it encounters
107  * an unrecognized escape sequence.  In non-strict mode, it leaves
108  * the escape sequence unchanged.
109  */
110 template <class String>
111 void cUnescape(StringPiece str, String& out, bool strict = true);
112
113 /**
114  * Similar to cUnescape above, but returns the escaped string.
115  */
116 template <class String>
117 String cUnescape(StringPiece str, bool strict = true) {
118   String out;
119   cUnescape(str, out, strict);
120   return out;
121 }
122
123 /**
124  * URI-escape a string.  Appends the result to the output string.
125  *
126  * Alphanumeric characters and other characters marked as "unreserved" in RFC
127  * 3986 ( -_.~ ) are left unchanged.  In PATH mode, the forward slash (/) is
128  * also left unchanged.  In QUERY mode, spaces are replaced by '+'.  All other
129  * characters are percent-encoded.
130  */
131 enum class UriEscapeMode : unsigned char {
132   // The values are meaningful, see generate_escape_tables.py
133   ALL = 0,
134   QUERY = 1,
135   PATH = 2
136 };
137 template <class String>
138 void uriEscape(StringPiece str,
139                String& out,
140                UriEscapeMode mode = UriEscapeMode::ALL);
141
142 /**
143  * Similar to uriEscape above, but returns the escaped string.
144  */
145 template <class String>
146 String uriEscape(StringPiece str, UriEscapeMode mode = UriEscapeMode::ALL) {
147   String out;
148   uriEscape(str, out, mode);
149   return out;
150 }
151
152 /**
153  * URI-unescape a string.  Appends the result to the output string.
154  *
155  * In QUERY mode, '+' are replaced by space.  %XX sequences are decoded if
156  * XX is a valid hex sequence, otherwise we throw invalid_argument.
157  */
158 template <class String>
159 void uriUnescape(StringPiece str,
160                  String& out,
161                  UriEscapeMode mode = UriEscapeMode::ALL);
162
163 /**
164  * Similar to uriUnescape above, but returns the unescaped string.
165  */
166 template <class String>
167 String uriUnescape(StringPiece str, UriEscapeMode mode = UriEscapeMode::ALL) {
168   String out;
169   uriUnescape(str, out, mode);
170   return out;
171 }
172
173 /**
174  * stringPrintf is much like printf but deposits its result into a
175  * string. Two signatures are supported: the first simply returns the
176  * resulting string, and the second appends the produced characters to
177  * the specified string and returns a reference to it.
178  */
179 std::string stringPrintf(FOLLY_PRINTF_FORMAT const char* format, ...)
180   FOLLY_PRINTF_FORMAT_ATTR(1, 2);
181
182 /* Similar to stringPrintf, with different signature. */
183 void stringPrintf(std::string* out, FOLLY_PRINTF_FORMAT const char* fmt, ...)
184   FOLLY_PRINTF_FORMAT_ATTR(2, 3);
185
186 std::string& stringAppendf(std::string* output,
187                           FOLLY_PRINTF_FORMAT const char* format, ...)
188   FOLLY_PRINTF_FORMAT_ATTR(2, 3);
189
190 /**
191  * Similar to stringPrintf, but accepts a va_list argument.
192  *
193  * As with vsnprintf() itself, the value of ap is undefined after the call.
194  * These functions do not call va_end() on ap.
195  */
196 std::string stringVPrintf(const char* format, va_list ap);
197 void stringVPrintf(std::string* out, const char* format, va_list ap);
198 std::string& stringVAppendf(std::string* out, const char* format, va_list ap);
199
200 /**
201  * Backslashify a string, that is, replace non-printable characters
202  * with C-style (but NOT C compliant) "\xHH" encoding.  If hex_style
203  * is false, then shorthand notations like "\0" will be used instead
204  * of "\x00" for the most common backslash cases.
205  *
206  * There are two forms, one returning the input string, and one
207  * creating output in the specified output string.
208  *
209  * This is mainly intended for printing to a terminal, so it is not
210  * particularly optimized.
211  *
212  * Do *not* use this in situations where you expect to be able to feed
213  * the string to a C or C++ compiler, as there are nuances with how C
214  * parses such strings that lead to failures.  This is for display
215  * purposed only.  If you want a string you can embed for use in C or
216  * C++, use cEscape instead.  This function is for display purposes
217  * only.
218  */
219 template <class String1, class String2>
220 void backslashify(const String1& input, String2& output, bool hex_style=false);
221
222 template <class String>
223 String backslashify(const String& input, bool hex_style=false) {
224   String output;
225   backslashify(input, output, hex_style);
226   return output;
227 }
228
229 /**
230  * Take a string and "humanify" it -- that is, make it look better.
231  * Since "better" is subjective, caveat emptor.  The basic approach is
232  * to count the number of unprintable characters.  If there are none,
233  * then the output is the input.  If there are relatively few, or if
234  * there is a long "enough" prefix of printable characters, use
235  * backslashify.  If it is mostly binary, then simply hex encode.
236  *
237  * This is an attempt to make a computer smart, and so likely is wrong
238  * most of the time.
239  */
240 template <class String1, class String2>
241 void humanify(const String1& input, String2& output);
242
243 template <class String>
244 String humanify(const String& input) {
245   String output;
246   humanify(input, output);
247   return output;
248 }
249
250 /**
251  * Same functionality as Python's binascii.hexlify.  Returns true
252  * on successful conversion.
253  *
254  * If append_output is true, append data to the output rather than
255  * replace it.
256  */
257 template<class InputString, class OutputString>
258 bool hexlify(const InputString& input, OutputString& output,
259              bool append=false);
260
261 /**
262  * Same functionality as Python's binascii.unhexlify.  Returns true
263  * on successful conversion.
264  */
265 template<class InputString, class OutputString>
266 bool unhexlify(const InputString& input, OutputString& output);
267
268 /*
269  * A pretty-printer for numbers that appends suffixes of units of the
270  * given type.  It prints 4 sig-figs of value with the most
271  * appropriate unit.
272  *
273  * If `addSpace' is true, we put a space between the units suffix and
274  * the value.
275  *
276  * Current types are:
277  *   PRETTY_TIME         - s, ms, us, ns, etc.
278  *   PRETTY_BYTES_METRIC - kB, MB, GB, etc (goes up by 10^3 = 1000 each time)
279  *   PRETTY_BYTES        - kB, MB, GB, etc (goes up by 2^10 = 1024 each time)
280  *   PRETTY_BYTES_IEC    - KiB, MiB, GiB, etc
281  *   PRETTY_UNITS_METRIC - k, M, G, etc (goes up by 10^3 = 1000 each time)
282  *   PRETTY_UNITS_BINARY - k, M, G, etc (goes up by 2^10 = 1024 each time)
283  *   PRETTY_UNITS_BINARY_IEC - Ki, Mi, Gi, etc
284  *   PRETTY_SI           - full SI metric prefixes from yocto to Yotta
285  *                         http://en.wikipedia.org/wiki/Metric_prefix
286  * @author Mark Rabkin <mrabkin@fb.com>
287  */
288 enum PrettyType {
289   PRETTY_TIME,
290
291   PRETTY_BYTES_METRIC,
292   PRETTY_BYTES_BINARY,
293   PRETTY_BYTES = PRETTY_BYTES_BINARY,
294   PRETTY_BYTES_BINARY_IEC,
295   PRETTY_BYTES_IEC = PRETTY_BYTES_BINARY_IEC,
296
297   PRETTY_UNITS_METRIC,
298   PRETTY_UNITS_BINARY,
299   PRETTY_UNITS_BINARY_IEC,
300
301   PRETTY_SI,
302   PRETTY_NUM_TYPES,
303 };
304
305 std::string prettyPrint(double val, PrettyType, bool addSpace = true);
306
307 /**
308  * This utility converts StringPiece in pretty format (look above) to double,
309  * with progress information. Alters the  StringPiece parameter
310  * to get rid of the already-parsed characters.
311  * Expects string in form <floating point number> {space}* [<suffix>]
312  * If string is not in correct format, utility finds longest valid prefix and
313  * if there at least one, returns double value based on that prefix and
314  * modifies string to what is left after parsing. Throws and std::range_error
315  * exception if there is no correct parse.
316  * Examples(for PRETTY_UNITS_METRIC):
317  * '10M' => 10 000 000
318  * '10 M' => 10 000 000
319  * '10' => 10
320  * '10 Mx' => 10 000 000, prettyString == "x"
321  * 'abc' => throws std::range_error
322  */
323 double prettyToDouble(folly::StringPiece *const prettyString,
324                       const PrettyType type);
325
326 /*
327  * Same as prettyToDouble(folly::StringPiece*, PrettyType), but
328  * expects whole string to be correctly parseable. Throws std::range_error
329  * otherwise
330  */
331 double prettyToDouble(folly::StringPiece prettyString, const PrettyType type);
332
333 /**
334  * Write a hex dump of size bytes starting at ptr to out.
335  *
336  * The hex dump is formatted as follows:
337  *
338  * for the string "abcdefghijklmnopqrstuvwxyz\x02"
339 00000000  61 62 63 64 65 66 67 68  69 6a 6b 6c 6d 6e 6f 70  |abcdefghijklmnop|
340 00000010  71 72 73 74 75 76 77 78  79 7a 02                 |qrstuvwxyz.     |
341  *
342  * that is, we write 16 bytes per line, both as hex bytes and as printable
343  * characters.  Non-printable characters are replaced with '.'
344  * Lines are written to out one by one (one StringPiece at a time) without
345  * delimiters.
346  */
347 template <class OutIt>
348 void hexDump(const void* ptr, size_t size, OutIt out);
349
350 /**
351  * Return the hex dump of size bytes starting at ptr as a string.
352  */
353 std::string hexDump(const void* ptr, size_t size);
354
355 /**
356  * Return a fbstring containing the description of the given errno value.
357  * Takes care not to overwrite the actual system errno, so calling
358  * errnoStr(errno) is valid.
359  */
360 fbstring errnoStr(int err);
361
362 /**
363  * Debug string for an exception: include type and what(), if
364  * defined.
365  */
366 inline fbstring exceptionStr(const std::exception& e) {
367 #ifdef FOLLY_HAS_RTTI
368   return folly::to<fbstring>(demangle(typeid(e)), ": ", e.what());
369 #else
370   return folly::to<fbstring>("Exception (no RTTI available): ", e.what());
371 #endif
372 }
373
374 // Empirically, this indicates if the runtime supports
375 // std::exception_ptr, as not all (arm, for instance) do.
376 #if defined(__GNUC__) && defined(__GCC_ATOMIC_INT_LOCK_FREE) && \
377   __GCC_ATOMIC_INT_LOCK_FREE > 1
378 inline fbstring exceptionStr(std::exception_ptr ep) {
379   try {
380     std::rethrow_exception(ep);
381   } catch (const std::exception& e) {
382     return exceptionStr(e);
383   } catch (...) {
384     return "<unknown exception>";
385   }
386 }
387 #endif
388
389 template<typename E>
390 auto exceptionStr(const E& e)
391   -> typename std::enable_if<!std::is_base_of<std::exception, E>::value,
392                              fbstring>::type
393 {
394 #ifdef FOLLY_HAS_RTTI
395   return folly::to<fbstring>(demangle(typeid(e)));
396 #else
397   return "Exception (no RTTI available)";
398 #endif
399 }
400
401 /*
402  * Split a string into a list of tokens by delimiter.
403  *
404  * The split interface here supports different output types, selected
405  * at compile time: StringPiece, fbstring, or std::string.  If you are
406  * using a vector to hold the output, it detects the type based on
407  * what your vector contains.  If the output vector is not empty, split
408  * will append to the end of the vector.
409  *
410  * You can also use splitTo() to write the output to an arbitrary
411  * OutputIterator (e.g. std::inserter() on a std::set<>), in which
412  * case you have to tell the function the type.  (Rationale:
413  * OutputIterators don't have a value_type, so we can't detect the
414  * type in splitTo without being told.)
415  *
416  * Examples:
417  *
418  *   std::vector<folly::StringPiece> v;
419  *   folly::split(":", "asd:bsd", v);
420  *
421  *   std::set<StringPiece> s;
422  *   folly::splitTo<StringPiece>(":", "asd:bsd:asd:csd",
423  *    std::inserter(s, s.begin()));
424  *
425  * Split also takes a flag (ignoreEmpty) that indicates whether adjacent
426  * delimiters should be treated as one single separator (ignoring empty tokens)
427  * or not (generating empty tokens).
428  */
429
430 template<class Delim, class String, class OutputType>
431 void split(const Delim& delimiter,
432            const String& input,
433            std::vector<OutputType>& out,
434            bool ignoreEmpty = false);
435
436 template<class Delim, class String, class OutputType>
437 void split(const Delim& delimiter,
438            const String& input,
439            folly::fbvector<OutputType>& out,
440            bool ignoreEmpty = false);
441
442 template<class OutputValueType, class Delim, class String,
443          class OutputIterator>
444 void splitTo(const Delim& delimiter,
445              const String& input,
446              OutputIterator out,
447              bool ignoreEmpty = false);
448
449 /*
450  * Split a string into a fixed number of string pieces and/or numeric types
451  * by delimiter. Any numeric type that folly::to<> can convert to from a
452  * string piece is supported as a target. Returns 'true' if the fields were
453  * all successfully populated.  Returns 'false' if there were too few fields
454  * in the input, or too many fields if exact=true.  Casting exceptions will
455  * not be caught.
456  *
457  * Examples:
458  *
459  *  folly::StringPiece name, key, value;
460  *  if (folly::split('\t', line, name, key, value))
461  *    ...
462  *
463  *  folly::StringPiece name;
464  *  double value;
465  *  int id;
466  *  if (folly::split('\t', line, name, value, id))
467  *    ...
468  *
469  * The 'exact' template parameter specifies how the function behaves when too
470  * many fields are present in the input string. When 'exact' is set to its
471  * default value of 'true', a call to split will fail if the number of fields in
472  * the input string does not exactly match the number of output parameters
473  * passed. If 'exact' is overridden to 'false', all remaining fields will be
474  * stored, unsplit, in the last field, as shown below:
475  *
476  *  folly::StringPiece x, y.
477  *  if (folly::split<false>(':', "a:b:c", x, y))
478  *    assert(x == "a" && y == "b:c");
479  *
480  * Note that this will likely not work if the last field's target is of numeric
481  * type, in which case folly::to<> will throw an exception.
482  */
483 template <class T>
484 using IsSplitTargetType = std::integral_constant<bool,
485   std::is_arithmetic<T>::value ||
486   std::is_same<T, StringPiece>::value ||
487   IsSomeString<T>::value>;
488
489 template<bool exact = true,
490          class Delim,
491          class OutputType,
492          class... OutputTypes>
493 typename std::enable_if<IsSplitTargetType<OutputType>::value, bool>::type
494 split(const Delim& delimiter,
495       StringPiece input,
496       OutputType& outHead,
497       OutputTypes&... outTail);
498
499 /*
500  * Join list of tokens.
501  *
502  * Stores a string representation of tokens in the same order with
503  * deliminer between each element.
504  */
505
506 template <class Delim, class Iterator, class String>
507 void join(const Delim& delimiter,
508           Iterator begin,
509           Iterator end,
510           String& output);
511
512 template <class Delim, class Container, class String>
513 void join(const Delim& delimiter,
514           const Container& container,
515           String& output) {
516   join(delimiter, container.begin(), container.end(), output);
517 }
518
519 template <class Delim, class Value, class String>
520 void join(const Delim& delimiter,
521           const std::initializer_list<Value>& values,
522           String& output) {
523   join(delimiter, values.begin(), values.end(), output);
524 }
525
526 template <class Delim, class Container>
527 std::string join(const Delim& delimiter,
528                  const Container& container) {
529   std::string output;
530   join(delimiter, container.begin(), container.end(), output);
531   return output;
532 }
533
534 template <class Delim, class Value>
535 std::string join(const Delim& delimiter,
536                  const std::initializer_list<Value>& values) {
537   std::string output;
538   join(delimiter, values.begin(), values.end(), output);
539   return output;
540 }
541
542 template <class Delim,
543           class Iterator,
544           typename std::enable_if<std::is_same<
545               typename std::iterator_traits<Iterator>::iterator_category,
546               std::random_access_iterator_tag>::value>::type* = nullptr>
547 std::string join(const Delim& delimiter, Iterator begin, Iterator end) {
548   std::string output;
549   join(delimiter, begin, end, output);
550   return output;
551 }
552
553 /**
554  * Returns a subpiece with all whitespace removed from the front of @sp.
555  * Whitespace means any of [' ', '\n', '\r', '\t'].
556  */
557 StringPiece ltrimWhitespace(StringPiece sp);
558
559 /**
560  * Returns a subpiece with all whitespace removed from the back of @sp.
561  * Whitespace means any of [' ', '\n', '\r', '\t'].
562  */
563 StringPiece rtrimWhitespace(StringPiece sp);
564
565 /**
566  * Returns a subpiece with all whitespace removed from the back and front of @sp.
567  * Whitespace means any of [' ', '\n', '\r', '\t'].
568  */
569 inline StringPiece trimWhitespace(StringPiece sp) {
570   return ltrimWhitespace(rtrimWhitespace(sp));
571 }
572
573 /**
574  * Returns a subpiece with all whitespace removed from the front of @sp.
575  * Whitespace means any of [' ', '\n', '\r', '\t'].
576  * DEPRECATED: @see ltrimWhitespace @see rtrimWhitespace
577  */
578 inline StringPiece skipWhitespace(StringPiece sp) {
579   return ltrimWhitespace(sp);
580 }
581
582 /**
583  * Fast, in-place lowercasing of ASCII alphabetic characters in strings.
584  * Leaves all other characters unchanged, including those with the 0x80
585  * bit set.
586  * @param str String to convert
587  * @param len Length of str, in bytes
588  */
589 void toLowerAscii(char* str, size_t length);
590
591 inline void toLowerAscii(MutableStringPiece str) {
592   toLowerAscii(str.begin(), str.size());
593 }
594
595 } // namespace folly
596
597 // Hook into boost's type traits
598 namespace boost {
599 template <class T>
600 struct has_nothrow_constructor<folly::basic_fbstring<T> > : true_type {
601   enum { value = true };
602 };
603 } // namespace boost
604
605 #include <folly/String-inl.h>
606
607 #endif