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