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