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