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