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