Revert "[Folly] Helper method to get exception type"
[folly.git] / folly / String.h
1 /*
2  * Copyright 2013 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 <string>
22 #include <boost/type_traits.hpp>
23
24 #ifdef __GNUC__
25 # include <ext/hash_set>
26 # include <ext/hash_map>
27 #endif
28
29 #include "folly/Conv.h"
30 #include "folly/FBString.h"
31 #include "folly/FBVector.h"
32 #include "folly/Range.h"
33 #include "folly/ScopeGuard.h"
34
35 // Compatibility function, to make sure toStdString(s) can be called
36 // to convert a std::string or fbstring variable s into type std::string
37 // with very little overhead if s was already std::string
38 namespace folly {
39
40 inline
41 std::string toStdString(const folly::fbstring& s) {
42   return std::string(s.data(), s.size());
43 }
44
45 inline
46 const std::string& toStdString(const std::string& s) {
47   return s;
48 }
49
50 // If called with a temporary, the compiler will select this overload instead
51 // of the above, so we don't return a (lvalue) reference to a temporary.
52 inline
53 std::string&& toStdString(std::string&& s) {
54   return std::move(s);
55 }
56
57 /**
58  * C-Escape a string, making it suitable for representation as a C string
59  * literal.  Appends the result to the output string.
60  *
61  * Backslashes all occurrences of backslash and double-quote:
62  *   "  ->  \"
63  *   \  ->  \\
64  *
65  * Replaces all non-printable ASCII characters with backslash-octal
66  * representation:
67  *   <ASCII 254> -> \376
68  *
69  * Note that we use backslash-octal instead of backslash-hex because the octal
70  * representation is guaranteed to consume no more than 3 characters; "\3760"
71  * represents two characters, one with value 254, and one with value 48 ('0'),
72  * whereas "\xfe0" represents only one character (with value 4064, which leads
73  * to implementation-defined behavior).
74  */
75 template <class String>
76 void cEscape(StringPiece str, String& out);
77
78 /**
79  * Similar to cEscape above, but returns the escaped string.
80  */
81 template <class String>
82 String cEscape(StringPiece str) {
83   String out;
84   cEscape(str, out);
85   return out;
86 }
87
88 /**
89  * C-Unescape a string; the opposite of cEscape above.  Appends the result
90  * to the output string.
91  *
92  * Recognizes the standard C escape sequences:
93  *
94  * \' \" \? \\ \a \b \f \n \r \t \v
95  * \[0-7]+
96  * \x[0-9a-fA-F]+
97  *
98  * In strict mode (default), throws std::invalid_argument if it encounters
99  * an unrecognized escape sequence.  In non-strict mode, it leaves
100  * the escape sequence unchanged.
101  */
102 template <class String>
103 void cUnescape(StringPiece str, String& out, bool strict = true);
104
105 /**
106  * Similar to cUnescape above, but returns the escaped string.
107  */
108 template <class String>
109 String cUnescape(StringPiece str, bool strict = true) {
110   String out;
111   cUnescape(str, out, strict);
112   return out;
113 }
114
115 /**
116  * URI-escape a string.  Appends the result to the output string.
117  *
118  * Alphanumeric characters and other characters marked as "unreserved" in RFC
119  * 3986 ( -_.~ ) are left unchanged.  In PATH mode, the forward slash (/) is
120  * also left unchanged.  In QUERY mode, spaces are replaced by '+'.  All other
121  * characters are percent-encoded.
122  */
123 enum class UriEscapeMode : unsigned char {
124   // The values are meaningful, see generate_escape_tables.py
125   ALL = 0,
126   QUERY = 1,
127   PATH = 2
128 };
129 template <class String>
130 void uriEscape(StringPiece str,
131                String& out,
132                UriEscapeMode mode = UriEscapeMode::ALL);
133
134 /**
135  * Similar to uriEscape above, but returns the escaped string.
136  */
137 template <class String>
138 String uriEscape(StringPiece str, UriEscapeMode mode = UriEscapeMode::ALL) {
139   String out;
140   uriEscape(str, out, mode);
141   return out;
142 }
143
144 /**
145  * URI-unescape a string.  Appends the result to the output string.
146  *
147  * In QUERY mode, '+' are replaced by space.  %XX sequences are decoded if
148  * XX is a valid hex sequence, otherwise we throw invalid_argument.
149  */
150 template <class String>
151 void uriUnescape(StringPiece str,
152                  String& out,
153                  UriEscapeMode mode = UriEscapeMode::ALL);
154
155 /**
156  * Similar to uriUnescape above, but returns the unescaped string.
157  */
158 template <class String>
159 String uriUnescape(StringPiece str, UriEscapeMode mode = UriEscapeMode::ALL) {
160   String out;
161   uriUnescape(str, out, mode);
162   return out;
163 }
164
165 /**
166  * stringPrintf is much like printf but deposits its result into a
167  * string. Two signatures are supported: the first simply returns the
168  * resulting string, and the second appends the produced characters to
169  * the specified string and returns a reference to it.
170  */
171 std::string stringPrintf(const char* format, ...)
172   __attribute__ ((format (printf, 1, 2)));
173
174 /** Similar to stringPrintf, with different signiture.
175   */
176 void stringPrintf(std::string* out, const char* fmt, ...)
177   __attribute__ ((format (printf, 2, 3)));
178
179 std::string& stringAppendf(std::string* output, const char* format, ...)
180   __attribute__ ((format (printf, 2, 3)));
181
182 /**
183  * Backslashify a string, that is, replace non-printable characters
184  * with C-style (but NOT C compliant) "\xHH" encoding.  If hex_style
185  * is false, then shorthand notations like "\0" will be used instead
186  * of "\x00" for the most common backslash cases.
187  *
188  * There are two forms, one returning the input string, and one
189  * creating output in the specified output string.
190  *
191  * This is mainly intended for printing to a terminal, so it is not
192  * particularly optimized.
193  *
194  * Do *not* use this in situations where you expect to be able to feed
195  * the string to a C or C++ compiler, as there are nuances with how C
196  * parses such strings that lead to failures.  This is for display
197  * purposed only.  If you want a string you can embed for use in C or
198  * C++, use cEscape instead.  This function is for display purposes
199  * only.
200  */
201 template <class String1, class String2>
202 void backslashify(const String1& input, String2& output, bool hex_style=false);
203
204 template <class String>
205 String backslashify(const String& input, bool hex_style=false) {
206   String output;
207   backslashify(input, output, hex_style);
208   return output;
209 }
210
211 /**
212  * Take a string and "humanify" it -- that is, make it look better.
213  * Since "better" is subjective, caveat emptor.  The basic approach is
214  * to count the number of unprintable characters.  If there are none,
215  * then the output is the input.  If there are relatively few, or if
216  * there is a long "enough" prefix of printable characters, use
217  * backslashify.  If it is mostly binary, then simply hex encode.
218  *
219  * This is an attempt to make a computer smart, and so likely is wrong
220  * most of the time.
221  */
222 template <class String1, class String2>
223 void humanify(const String1& input, String2& output);
224
225 template <class String>
226 String humanify(const String& input) {
227   String output;
228   humanify(input, output);
229   return output;
230 }
231
232 /**
233  * Same functionality as Python's binascii.hexlify.  Returns true
234  * on successful conversion.
235  *
236  * If append_output is true, append data to the output rather than
237  * replace it.
238  */
239 template<class InputString, class OutputString>
240 bool hexlify(const InputString& input, OutputString& output,
241              bool append=false);
242
243 /**
244  * Same functionality as Python's binascii.unhexlify.  Returns true
245  * on successful conversion.
246  */
247 template<class InputString, class OutputString>
248 bool unhexlify(const InputString& input, OutputString& output);
249
250 /*
251  * A pretty-printer for numbers that appends suffixes of units of the
252  * given type.  It prints 4 sig-figs of value with the most
253  * appropriate unit.
254  *
255  * If `addSpace' is true, we put a space between the units suffix and
256  * the value.
257  *
258  * Current types are:
259  *   PRETTY_TIME         - s, ms, us, ns, etc.
260  *   PRETTY_BYTES_METRIC - kB, MB, GB, etc (goes up by 10^3 = 1000 each time)
261  *   PRETTY_BYTES        - kB, MB, GB, etc (goes up by 2^10 = 1024 each time)
262  *   PRETTY_BYTES_IEC    - KiB, MiB, GiB, etc
263  *   PRETTY_UNITS_METRIC - k, M, G, etc (goes up by 10^3 = 1000 each time)
264  *   PRETTY_UNITS_BINARY - k, M, G, etc (goes up by 2^10 = 1024 each time)
265  *   PRETTY_UNITS_BINARY_IEC - Ki, Mi, Gi, etc
266  *
267  * @author Mark Rabkin <mrabkin@fb.com>
268  */
269 enum PrettyType {
270   PRETTY_TIME,
271
272   PRETTY_BYTES_METRIC,
273   PRETTY_BYTES_BINARY,
274   PRETTY_BYTES = PRETTY_BYTES_BINARY,
275   PRETTY_BYTES_BINARY_IEC,
276   PRETTY_BYTES_IEC = PRETTY_BYTES_BINARY_IEC,
277
278   PRETTY_UNITS_METRIC,
279   PRETTY_UNITS_BINARY,
280   PRETTY_UNITS_BINARY_IEC,
281
282   PRETTY_NUM_TYPES
283 };
284
285 std::string prettyPrint(double val, PrettyType, bool addSpace = true);
286
287 /**
288  * Write a hex dump of size bytes starting at ptr to out.
289  *
290  * The hex dump is formatted as follows:
291  *
292  * for the string "abcdefghijklmnopqrstuvwxyz\x02"
293 00000000  61 62 63 64 65 66 67 68  69 6a 6b 6c 6d 6e 6f 70  |abcdefghijklmnop|
294 00000010  71 72 73 74 75 76 77 78  79 7a 02                 |qrstuvwxyz.     |
295  *
296  * that is, we write 16 bytes per line, both as hex bytes and as printable
297  * characters.  Non-printable characters are replaced with '.'
298  * Lines are written to out one by one (one StringPiece at a time) without
299  * delimiters.
300  */
301 template <class OutIt>
302 void hexDump(const void* ptr, size_t size, OutIt out);
303
304 /**
305  * Return the hex dump of size bytes starting at ptr as a string.
306  */
307 std::string hexDump(const void* ptr, size_t size);
308
309 /**
310  * Return a fbstring containing the description of the given errno value.
311  * Takes care not to overwrite the actual system errno, so calling
312  * errnoStr(errno) is valid.
313  */
314 fbstring errnoStr(int err);
315
316 /**
317  * Return the demangled (prettyfied) version of a C++ type.
318  *
319  * This function tries to produce a human-readable type, but the type name will
320  * be returned unchanged in case of error or if demangling isn't supported on
321  * your system.
322  *
323  * Use for debugging -- do not rely on demangle() returning anything useful.
324  *
325  * This function may allocate memory (and therefore throw std::bad_alloc).
326  */
327 fbstring demangle(const char* name);
328 inline fbstring demangle(const std::type_info& type) {
329   return demangle(type.name());
330 }
331
332 /**
333  * Return the demangled (prettyfied) version of a C++ type in a user-provided
334  * buffer.
335  *
336  * The semantics are the same as for snprintf or strlcpy: bufSize is the size
337  * of the buffer, the string is always null-terminated, and the return value is
338  * the number of characters (not including the null terminator) that would have
339  * been written if the buffer was big enough. (So a return value >= bufSize
340  * indicates that the output was truncated)
341  *
342  * This function does not allocate memory and is async-signal-safe.
343  *
344  * Note that the underlying function for the fbstring-returning demangle is
345  * somewhat standard (abi::__cxa_demangle, which uses malloc), the underlying
346  * function for this version is less so (cplus_demangle_v3_callback from
347  * libiberty), so it is possible for the fbstring version to work, while this
348  * version returns the original, mangled name.
349  */
350 size_t demangle(const char* name, char* buf, size_t bufSize);
351 inline size_t demangle(const std::type_info& type, char* buf, size_t bufSize) {
352   return demangle(type.name(), buf, bufSize);
353 }
354
355 /**
356  * Debug string for an exception: include type and what().
357  */
358 inline fbstring exceptionStr(const std::exception& e) {
359   return folly::to<fbstring>(demangle(typeid(e)), ": ", e.what());
360 }
361
362 inline fbstring exceptionStr(std::exception_ptr ep) {
363   try {
364     std::rethrow_exception(ep);
365   } catch (const std::exception& e) {
366     return exceptionStr(e);
367   } catch (...) {
368     return "<unknown exception>";
369   }
370 }
371
372 /*
373  * Split a string into a list of tokens by delimiter.
374  *
375  * The split interface here supports different output types, selected
376  * at compile time: StringPiece, fbstring, or std::string.  If you are
377  * using a vector to hold the output, it detects the type based on
378  * what your vector contains.  If the output vector is not empty, split
379  * will append to the end of the vector.
380  *
381  * You can also use splitTo() to write the output to an arbitrary
382  * OutputIterator (e.g. std::inserter() on a std::set<>), in which
383  * case you have to tell the function the type.  (Rationale:
384  * OutputIterators don't have a value_type, so we can't detect the
385  * type in splitTo without being told.)
386  *
387  * Examples:
388  *
389  *   std::vector<folly::StringPiece> v;
390  *   folly::split(":", "asd:bsd", v);
391  *
392  *   std::set<StringPiece> s;
393  *   folly::splitTo<StringPiece>(":", "asd:bsd:asd:csd",
394  *    std::inserter(s, s.begin()));
395  *
396  * Split also takes a flag (ignoreEmpty) that indicates whether adjacent
397  * delimiters should be treated as one single separator (ignoring empty tokens)
398  * or not (generating empty tokens).
399  */
400
401 template<class Delim, class String, class OutputType>
402 void split(const Delim& delimiter,
403            const String& input,
404            std::vector<OutputType>& out,
405            bool ignoreEmpty = false);
406
407 template<class Delim, class String, class OutputType>
408 void split(const Delim& delimiter,
409            const String& input,
410            folly::fbvector<OutputType>& out,
411            bool ignoreEmpty = false);
412
413 template<class OutputValueType, class Delim, class String,
414          class OutputIterator>
415 void splitTo(const Delim& delimiter,
416              const String& input,
417              OutputIterator out,
418              bool ignoreEmpty = false);
419
420 /*
421  * Split a string into a fixed number of pieces by delimiter. Returns 'true' if
422  * the fields were all successfully populated.
423  *
424  * Example:
425  *
426  *  folly::StringPiece name, key, value;
427  *  if (folly::split('\t', line, name, key, value))
428  *    ...
429  *
430  * The 'exact' template paremeter specifies how the function behaves when too
431  * many fields are present in the input string. When 'exact' is set to its
432  * default value of 'true', a call to split will fail if the number of fields in
433  * the input string does not exactly match the number of output parameters
434  * passed. If 'exact' is overridden to 'false', all remaining fields will be
435  * stored, unsplit, in the last field, as shown below:
436  *
437  *  folly::StringPiece x, y.
438  *  if (folly::split<false>(':', "a:b:c", x, y))
439  *    assert(x == "a" && y == "b:c");
440  */
441 template<bool exact = true,
442          class Delim,
443          class... StringPieces>
444 bool split(const Delim& delimiter,
445            StringPiece input,
446            StringPiece& outHead,
447            StringPieces&... outTail);
448
449 /*
450  * Join list of tokens.
451  *
452  * Stores a string representation of tokens in the same order with
453  * deliminer between each element.
454  */
455
456 template <class Delim, class Iterator, class String>
457 void join(const Delim& delimiter,
458           Iterator begin,
459           Iterator end,
460           String& output);
461
462 template <class Delim, class Container, class String>
463 void join(const Delim& delimiter,
464           const Container& container,
465           String& output) {
466   join(delimiter, container.begin(), container.end(), output);
467 }
468
469 template <class Delim, class Value, class String>
470 void join(const Delim& delimiter,
471           const std::initializer_list<Value>& values,
472           String& output) {
473   join(delimiter, values.begin(), values.end(), output);
474 }
475
476 template <class Delim, class Container>
477 std::string join(const Delim& delimiter,
478                  const Container& container) {
479   std::string output;
480   join(delimiter, container.begin(), container.end(), output);
481   return output;
482 }
483
484 template <class Delim, class Value>
485 std::string join(const Delim& delimiter,
486                  const std::initializer_list<Value>& values) {
487   std::string output;
488   join(delimiter, values.begin(), values.end(), output);
489   return output;
490 }
491
492 } // namespace folly
493
494 // Hash functions for string and fbstring usable with e.g. hash_map
495 #ifdef __GNUC__
496 namespace __gnu_cxx {
497
498 template <class C>
499 struct hash<folly::basic_fbstring<C> > : private hash<const C*> {
500   size_t operator()(const folly::basic_fbstring<C> & s) const {
501     return hash<const C*>::operator()(s.c_str());
502   }
503 };
504
505 template <class C>
506 struct hash<std::basic_string<C> > : private hash<const C*> {
507   size_t operator()(const std::basic_string<C> & s) const {
508     return hash<const C*>::operator()(s.c_str());
509   }
510 };
511
512 } // namespace __gnu_cxx
513 #endif
514
515 // Hook into boost's type traits
516 namespace boost {
517 template <class T>
518 struct has_nothrow_constructor<folly::basic_fbstring<T> > : true_type {
519   enum { value = true };
520 };
521 } // namespace boost
522
523 #include "folly/String-inl.h"
524
525 #endif