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