Fix some old license headers
[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 #include <unordered_set>
28 #include <unordered_map>
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 String1, class String2>
215 void backslashify(const String1& input, String2& output, bool hex_style=false);
216
217 template <class String>
218 String backslashify(const String& input, bool hex_style=false) {
219   String output;
220   backslashify(input, output, hex_style);
221   return output;
222 }
223
224 /**
225  * Take a string and "humanify" it -- that is, make it look better.
226  * Since "better" is subjective, caveat emptor.  The basic approach is
227  * to count the number of unprintable characters.  If there are none,
228  * then the output is the input.  If there are relatively few, or if
229  * there is a long "enough" prefix of printable characters, use
230  * backslashify.  If it is mostly binary, then simply hex encode.
231  *
232  * This is an attempt to make a computer smart, and so likely is wrong
233  * most of the time.
234  */
235 template <class String1, class String2>
236 void humanify(const String1& input, String2& output);
237
238 template <class String>
239 String humanify(const String& input) {
240   String output;
241   humanify(input, output);
242   return output;
243 }
244
245 /**
246  * Same functionality as Python's binascii.hexlify.  Returns true
247  * on successful conversion.
248  *
249  * If append_output is true, append data to the output rather than
250  * replace it.
251  */
252 template<class InputString, class OutputString>
253 bool hexlify(const InputString& input, OutputString& output,
254              bool append=false);
255
256 template <class OutputString = std::string>
257 OutputString hexlify(ByteRange input) {
258   OutputString output;
259   if (!hexlify(input, output)) {
260     // hexlify() currently always returns true, so this can't really happen
261     throw std::runtime_error("hexlify failed");
262   }
263   return output;
264 }
265
266 template <class OutputString = std::string>
267 OutputString hexlify(StringPiece input) {
268   return hexlify<OutputString>(ByteRange{input});
269 }
270
271 /**
272  * Same functionality as Python's binascii.unhexlify.  Returns true
273  * on successful conversion.
274  */
275 template<class InputString, class OutputString>
276 bool unhexlify(const InputString& input, OutputString& output);
277
278 template <class OutputString = std::string>
279 OutputString unhexlify(StringPiece input) {
280   OutputString output;
281   if (!unhexlify(input, output)) {
282     // unhexlify() fails if the input has non-hexidecimal characters,
283     // or if it doesn't consist of a whole number of bytes
284     throw std::domain_error("unhexlify() called with non-hex input");
285   }
286   return output;
287 }
288
289 /*
290  * A pretty-printer for numbers that appends suffixes of units of the
291  * given type.  It prints 4 sig-figs of value with the most
292  * appropriate unit.
293  *
294  * If `addSpace' is true, we put a space between the units suffix and
295  * the value.
296  *
297  * Current types are:
298  *   PRETTY_TIME         - s, ms, us, ns, etc.
299  *   PRETTY_BYTES_METRIC - kB, MB, GB, etc (goes up by 10^3 = 1000 each time)
300  *   PRETTY_BYTES        - kB, MB, GB, etc (goes up by 2^10 = 1024 each time)
301  *   PRETTY_BYTES_IEC    - KiB, MiB, GiB, etc
302  *   PRETTY_UNITS_METRIC - k, M, G, etc (goes up by 10^3 = 1000 each time)
303  *   PRETTY_UNITS_BINARY - k, M, G, etc (goes up by 2^10 = 1024 each time)
304  *   PRETTY_UNITS_BINARY_IEC - Ki, Mi, Gi, etc
305  *   PRETTY_SI           - full SI metric prefixes from yocto to Yotta
306  *                         http://en.wikipedia.org/wiki/Metric_prefix
307  * @author Mark Rabkin <mrabkin@fb.com>
308  */
309 enum PrettyType {
310   PRETTY_TIME,
311
312   PRETTY_BYTES_METRIC,
313   PRETTY_BYTES_BINARY,
314   PRETTY_BYTES = PRETTY_BYTES_BINARY,
315   PRETTY_BYTES_BINARY_IEC,
316   PRETTY_BYTES_IEC = PRETTY_BYTES_BINARY_IEC,
317
318   PRETTY_UNITS_METRIC,
319   PRETTY_UNITS_BINARY,
320   PRETTY_UNITS_BINARY_IEC,
321
322   PRETTY_SI,
323   PRETTY_NUM_TYPES,
324 };
325
326 std::string prettyPrint(double val, PrettyType, bool addSpace = true);
327
328 /**
329  * This utility converts StringPiece in pretty format (look above) to double,
330  * with progress information. Alters the  StringPiece parameter
331  * to get rid of the already-parsed characters.
332  * Expects string in form <floating point number> {space}* [<suffix>]
333  * If string is not in correct format, utility finds longest valid prefix and
334  * if there at least one, returns double value based on that prefix and
335  * modifies string to what is left after parsing. Throws and std::range_error
336  * exception if there is no correct parse.
337  * Examples(for PRETTY_UNITS_METRIC):
338  * '10M' => 10 000 000
339  * '10 M' => 10 000 000
340  * '10' => 10
341  * '10 Mx' => 10 000 000, prettyString == "x"
342  * 'abc' => throws std::range_error
343  */
344 double prettyToDouble(folly::StringPiece *const prettyString,
345                       const PrettyType type);
346
347 /*
348  * Same as prettyToDouble(folly::StringPiece*, PrettyType), but
349  * expects whole string to be correctly parseable. Throws std::range_error
350  * otherwise
351  */
352 double prettyToDouble(folly::StringPiece prettyString, const PrettyType type);
353
354 /**
355  * Write a hex dump of size bytes starting at ptr to out.
356  *
357  * The hex dump is formatted as follows:
358  *
359  * for the string "abcdefghijklmnopqrstuvwxyz\x02"
360 00000000  61 62 63 64 65 66 67 68  69 6a 6b 6c 6d 6e 6f 70  |abcdefghijklmnop|
361 00000010  71 72 73 74 75 76 77 78  79 7a 02                 |qrstuvwxyz.     |
362  *
363  * that is, we write 16 bytes per line, both as hex bytes and as printable
364  * characters.  Non-printable characters are replaced with '.'
365  * Lines are written to out one by one (one StringPiece at a time) without
366  * delimiters.
367  */
368 template <class OutIt>
369 void hexDump(const void* ptr, size_t size, OutIt out);
370
371 /**
372  * Return the hex dump of size bytes starting at ptr as a string.
373  */
374 std::string hexDump(const void* ptr, size_t size);
375
376 /**
377  * Return a fbstring containing the description of the given errno value.
378  * Takes care not to overwrite the actual system errno, so calling
379  * errnoStr(errno) is valid.
380  */
381 fbstring errnoStr(int err);
382
383 /*
384  * Split a string into a list of tokens by delimiter.
385  *
386  * The split interface here supports different output types, selected
387  * at compile time: StringPiece, fbstring, or std::string.  If you are
388  * using a vector to hold the output, it detects the type based on
389  * what your vector contains.  If the output vector is not empty, split
390  * will append to the end of the vector.
391  *
392  * You can also use splitTo() to write the output to an arbitrary
393  * OutputIterator (e.g. std::inserter() on a std::set<>), in which
394  * case you have to tell the function the type.  (Rationale:
395  * OutputIterators don't have a value_type, so we can't detect the
396  * type in splitTo without being told.)
397  *
398  * Examples:
399  *
400  *   std::vector<folly::StringPiece> v;
401  *   folly::split(":", "asd:bsd", v);
402  *
403  *   std::set<StringPiece> s;
404  *   folly::splitTo<StringPiece>(":", "asd:bsd:asd:csd",
405  *    std::inserter(s, s.begin()));
406  *
407  * Split also takes a flag (ignoreEmpty) that indicates whether adjacent
408  * delimiters should be treated as one single separator (ignoring empty tokens)
409  * or not (generating empty tokens).
410  */
411
412 template<class Delim, class String, class OutputType>
413 void split(const Delim& delimiter,
414            const String& input,
415            std::vector<OutputType>& out,
416            const bool ignoreEmpty = false);
417
418 template<class Delim, class String, class OutputType>
419 void split(const Delim& delimiter,
420            const String& input,
421            folly::fbvector<OutputType>& out,
422            const bool ignoreEmpty = false);
423
424 template<class OutputValueType, class Delim, class String,
425          class OutputIterator>
426 void splitTo(const Delim& delimiter,
427              const String& input,
428              OutputIterator out,
429              const bool ignoreEmpty = false);
430
431 /*
432  * Split a string into a fixed number of string pieces and/or numeric types
433  * by delimiter. Conversions are supported for any type which folly:to<> can
434  * target, including all overloads of parseTo(). Returns 'true' if the fields
435  * were all successfully populated.  Returns 'false' if there were too few
436  * fields in the input, or too many fields if exact=true.  Casting exceptions
437  * will not be caught.
438  *
439  * Examples:
440  *
441  *  folly::StringPiece name, key, value;
442  *  if (folly::split('\t', line, name, key, value))
443  *    ...
444  *
445  *  folly::StringPiece name;
446  *  double value;
447  *  int id;
448  *  if (folly::split('\t', line, name, value, id))
449  *    ...
450  *
451  * The 'exact' template parameter specifies how the function behaves when too
452  * many fields are present in the input string. When 'exact' is set to its
453  * default value of 'true', a call to split will fail if the number of fields in
454  * the input string does not exactly match the number of output parameters
455  * passed. If 'exact' is overridden to 'false', all remaining fields will be
456  * stored, unsplit, in the last field, as shown below:
457  *
458  *  folly::StringPiece x, y.
459  *  if (folly::split<false>(':', "a:b:c", x, y))
460  *    assert(x == "a" && y == "b:c");
461  *
462  * Note that this will likely not work if the last field's target is of numeric
463  * type, in which case folly::to<> will throw an exception.
464  */
465 template <class T, class Enable = void>
466 struct IsSomeVector {
467   enum { value = false };
468 };
469
470 template <class T>
471 struct IsSomeVector<std::vector<T>, void> {
472   enum { value = true };
473 };
474
475 template <class T>
476 struct IsSomeVector<fbvector<T>, void> {
477   enum { value = true };
478 };
479
480 template <class T, class Enable = void>
481 struct IsConvertible {
482   enum { value = false };
483 };
484
485 template <class T>
486 struct IsConvertible<
487     T,
488     decltype(static_cast<void>(
489         parseTo(std::declval<folly::StringPiece>(), std::declval<T&>())))> {
490   enum { value = true };
491 };
492
493 template <class... Types>
494 struct AllConvertible;
495
496 template <class Head, class... Tail>
497 struct AllConvertible<Head, Tail...> {
498   enum { value = IsConvertible<Head>::value && AllConvertible<Tail...>::value };
499 };
500
501 template <>
502 struct AllConvertible<> {
503   enum { value = true };
504 };
505
506 static_assert(AllConvertible<float>::value, "");
507 static_assert(AllConvertible<int>::value, "");
508 static_assert(AllConvertible<bool>::value, "");
509 static_assert(AllConvertible<int>::value, "");
510 static_assert(!AllConvertible<std::vector<int>>::value, "");
511
512 template <bool exact = true, class Delim, class... OutputTypes>
513 typename std::enable_if<
514     AllConvertible<OutputTypes...>::value && sizeof...(OutputTypes) >= 1,
515     bool>::type
516 split(const Delim& delimiter, StringPiece input, OutputTypes&... outputs);
517
518 /*
519  * Join list of tokens.
520  *
521  * Stores a string representation of tokens in the same order with
522  * deliminer between each element.
523  */
524
525 template <class Delim, class Iterator, class String>
526 void join(const Delim& delimiter,
527           Iterator begin,
528           Iterator end,
529           String& output);
530
531 template <class Delim, class Container, class String>
532 void join(const Delim& delimiter,
533           const Container& container,
534           String& output) {
535   join(delimiter, container.begin(), container.end(), output);
536 }
537
538 template <class Delim, class Value, class String>
539 void join(const Delim& delimiter,
540           const std::initializer_list<Value>& values,
541           String& output) {
542   join(delimiter, values.begin(), values.end(), output);
543 }
544
545 template <class Delim, class Container>
546 std::string join(const Delim& delimiter,
547                  const Container& container) {
548   std::string output;
549   join(delimiter, container.begin(), container.end(), output);
550   return output;
551 }
552
553 template <class Delim, class Value>
554 std::string join(const Delim& delimiter,
555                  const std::initializer_list<Value>& values) {
556   std::string output;
557   join(delimiter, values.begin(), values.end(), output);
558   return output;
559 }
560
561 template <class Delim,
562           class Iterator,
563           typename std::enable_if<std::is_same<
564               typename std::iterator_traits<Iterator>::iterator_category,
565               std::random_access_iterator_tag>::value>::type* = nullptr>
566 std::string join(const Delim& delimiter, Iterator begin, Iterator end) {
567   std::string output;
568   join(delimiter, begin, end, output);
569   return output;
570 }
571
572 /**
573  * Returns a subpiece with all whitespace removed from the front of @sp.
574  * Whitespace means any of [' ', '\n', '\r', '\t'].
575  */
576 StringPiece ltrimWhitespace(StringPiece sp);
577
578 /**
579  * Returns a subpiece with all whitespace removed from the back of @sp.
580  * Whitespace means any of [' ', '\n', '\r', '\t'].
581  */
582 StringPiece rtrimWhitespace(StringPiece sp);
583
584 /**
585  * Returns a subpiece with all whitespace removed from the back and front of @sp.
586  * Whitespace means any of [' ', '\n', '\r', '\t'].
587  */
588 inline StringPiece trimWhitespace(StringPiece sp) {
589   return ltrimWhitespace(rtrimWhitespace(sp));
590 }
591
592 /**
593  * Returns a subpiece with all whitespace removed from the front of @sp.
594  * Whitespace means any of [' ', '\n', '\r', '\t'].
595  * DEPRECATED: @see ltrimWhitespace @see rtrimWhitespace
596  */
597 inline StringPiece skipWhitespace(StringPiece sp) {
598   return ltrimWhitespace(sp);
599 }
600
601 /**
602  *  Strips the leading and the trailing whitespace-only lines. Then looks for
603  *  the least indented non-whitespace-only line and removes its amount of
604  *  leading whitespace from every line. Assumes leading whitespace is either all
605  *  spaces or all tabs.
606  *
607  *  Purpose: including a multiline string literal in source code, indented to
608  *  the level expected from context.
609  */
610 std::string stripLeftMargin(std::string s);
611
612 /**
613  * Fast, in-place lowercasing of ASCII alphabetic characters in strings.
614  * Leaves all other characters unchanged, including those with the 0x80
615  * bit set.
616  * @param str String to convert
617  * @param len Length of str, in bytes
618  */
619 void toLowerAscii(char* str, size_t length);
620
621 inline void toLowerAscii(MutableStringPiece str) {
622   toLowerAscii(str.begin(), str.size());
623 }
624
625 template <class Iterator = const char*,
626           class Base = folly::Range<boost::u8_to_u32_iterator<Iterator>>>
627 class UTF8Range : public Base {
628  public:
629   /* implicit */ UTF8Range(const folly::Range<Iterator> baseRange)
630       : Base(boost::u8_to_u32_iterator<Iterator>(
631                  baseRange.begin(), baseRange.begin(), baseRange.end()),
632              boost::u8_to_u32_iterator<Iterator>(
633                  baseRange.end(), baseRange.begin(), baseRange.end())) {}
634   /* implicit */ UTF8Range(const std::string& baseString)
635       : Base(folly::Range<Iterator>(baseString)) {}
636 };
637
638 using UTF8StringPiece = UTF8Range<const char*>;
639
640 } // namespace folly
641
642 #include <folly/String-inl.h>