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