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