add support for whenAll to waitWithSemaphore
[folly.git] / folly / String-inl.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_STRING_INL_H_
18 #define FOLLY_STRING_INL_H_
19
20 #include <stdexcept>
21 #include <iterator>
22
23 #ifndef FOLLY_BASE_STRING_H_
24 #error This file may only be included from String.h
25 #endif
26
27 namespace folly {
28
29 namespace detail {
30 // Map from character code to value of one-character escape sequence
31 // ('\n' = 10 maps to 'n'), 'O' if the character should be printed as
32 // an octal escape sequence, or 'P' if the character is printable and
33 // should be printed as is.
34 extern const char cEscapeTable[];
35 }  // namespace detail
36
37 template <class String>
38 void cEscape(StringPiece str, String& out) {
39   char esc[4];
40   esc[0] = '\\';
41   out.reserve(out.size() + str.size());
42   auto p = str.begin();
43   auto last = p;  // last regular character
44   // We advance over runs of regular characters (printable, not double-quote or
45   // backslash) and copy them in one go; this is faster than calling push_back
46   // repeatedly.
47   while (p != str.end()) {
48     char c = *p;
49     unsigned char v = static_cast<unsigned char>(c);
50     char e = detail::cEscapeTable[v];
51     if (e == 'P') {  // printable
52       ++p;
53     } else if (e == 'O') {  // octal
54       out.append(&*last, p - last);
55       esc[1] = '0' + ((v >> 6) & 7);
56       esc[2] = '0' + ((v >> 3) & 7);
57       esc[3] = '0' + (v & 7);
58       out.append(esc, 4);
59       ++p;
60       last = p;
61     } else {  // special 1-character escape
62       out.append(&*last, p - last);
63       esc[1] = e;
64       out.append(esc, 2);
65       ++p;
66       last = p;
67     }
68   }
69   out.append(&*last, p - last);
70 }
71
72 namespace detail {
73 // Map from the character code of the character following a backslash to
74 // the unescaped character if a valid one-character escape sequence
75 // ('n' maps to 10 = '\n'), 'O' if this is the first character of an
76 // octal escape sequence, 'X' if this is the first character of a
77 // hexadecimal escape sequence, or 'I' if this escape sequence is invalid.
78 extern const char cUnescapeTable[];
79
80 // Map from the character code to the hex value, or 16 if invalid hex char.
81 extern const unsigned char hexTable[];
82 }  // namespace detail
83
84 template <class String>
85 void cUnescape(StringPiece str, String& out, bool strict) {
86   out.reserve(out.size() + str.size());
87   auto p = str.begin();
88   auto last = p;  // last regular character (not part of an escape sequence)
89   // We advance over runs of regular characters (not backslash) and copy them
90   // in one go; this is faster than calling push_back repeatedly.
91   while (p != str.end()) {
92     char c = *p;
93     if (c != '\\') {  // normal case
94       ++p;
95       continue;
96     }
97     out.append(&*last, p - last);
98     if (p == str.end()) {  // backslash at end of string
99       if (strict) {
100         throw std::invalid_argument("incomplete escape sequence");
101       }
102       out.push_back('\\');
103       last = p;
104       continue;
105     }
106     ++p;
107     char e = detail::cUnescapeTable[static_cast<unsigned char>(*p)];
108     if (e == 'O') {  // octal
109       unsigned char val = 0;
110       for (int i = 0; i < 3 && p != str.end() && *p >= '0' && *p <= '7';
111            ++i, ++p) {
112         val = (val << 3) | (*p - '0');
113       }
114       out.push_back(val);
115       last = p;
116     } else if (e == 'X') {  // hex
117       ++p;
118       if (p == str.end()) {  // \x at end of string
119         if (strict) {
120           throw std::invalid_argument("incomplete hex escape sequence");
121         }
122         out.append("\\x");
123         last = p;
124         continue;
125       }
126       unsigned char val = 0;
127       unsigned char h;
128       for (; (p != str.end() &&
129               (h = detail::hexTable[static_cast<unsigned char>(*p)]) < 16);
130            ++p) {
131         val = (val << 4) | h;
132       }
133       out.push_back(val);
134       last = p;
135     } else if (e == 'I') {  // invalid
136       if (strict) {
137         throw std::invalid_argument("invalid escape sequence");
138       }
139       out.push_back('\\');
140       out.push_back(*p);
141       ++p;
142       last = p;
143     } else {  // standard escape sequence, \' etc
144       out.push_back(e);
145       ++p;
146       last = p;
147     }
148   }
149   out.append(&*last, p - last);
150 }
151
152 namespace detail {
153 // Map from character code to escape mode:
154 // 0 = pass through
155 // 1 = unused
156 // 2 = pass through in PATH mode
157 // 3 = space, replace with '+' in QUERY mode
158 // 4 = percent-encode
159 extern const unsigned char uriEscapeTable[];
160 }  // namespace detail
161
162 template <class String>
163 void uriEscape(StringPiece str, String& out, UriEscapeMode mode) {
164   static const char hexValues[] = "0123456789abcdef";
165   char esc[3];
166   esc[0] = '%';
167   // Preallocate assuming that 25% of the input string will be escaped
168   out.reserve(out.size() + str.size() + 3 * (str.size() / 4));
169   auto p = str.begin();
170   auto last = p;  // last regular character
171   // We advance over runs of passthrough characters and copy them in one go;
172   // this is faster than calling push_back repeatedly.
173   unsigned char minEncode = static_cast<unsigned char>(mode);
174   while (p != str.end()) {
175     char c = *p;
176     unsigned char v = static_cast<unsigned char>(c);
177     unsigned char discriminator = detail::uriEscapeTable[v];
178     if (LIKELY(discriminator <= minEncode)) {
179       ++p;
180     } else if (mode == UriEscapeMode::QUERY && discriminator == 3) {
181       out.append(&*last, p - last);
182       out.push_back('+');
183       ++p;
184       last = p;
185     } else {
186       out.append(&*last, p - last);
187       esc[1] = hexValues[v >> 4];
188       esc[2] = hexValues[v & 0x0f];
189       out.append(esc, 3);
190       ++p;
191       last = p;
192     }
193   }
194   out.append(&*last, p - last);
195 }
196
197 template <class String>
198 void uriUnescape(StringPiece str, String& out, UriEscapeMode mode) {
199   out.reserve(out.size() + str.size());
200   auto p = str.begin();
201   auto last = p;
202   // We advance over runs of passthrough characters and copy them in one go;
203   // this is faster than calling push_back repeatedly.
204   while (p != str.end()) {
205     char c = *p;
206     unsigned char v = static_cast<unsigned char>(v);
207     switch (c) {
208     case '%':
209       {
210         if (UNLIKELY(std::distance(p, str.end()) < 3)) {
211           throw std::invalid_argument("incomplete percent encode sequence");
212         }
213         auto h1 = detail::hexTable[static_cast<unsigned char>(p[1])];
214         auto h2 = detail::hexTable[static_cast<unsigned char>(p[2])];
215         if (UNLIKELY(h1 == 16 || h2 == 16)) {
216           throw std::invalid_argument("invalid percent encode sequence");
217         }
218         out.append(&*last, p - last);
219         out.push_back((h1 << 4) | h2);
220         p += 3;
221         last = p;
222         break;
223       }
224     case '+':
225       if (mode == UriEscapeMode::QUERY) {
226         out.append(&*last, p - last);
227         out.push_back(' ');
228         ++p;
229         last = p;
230         break;
231       }
232       // else fallthrough
233     default:
234       ++p;
235       break;
236     }
237   }
238   out.append(&*last, p - last);
239 }
240
241 namespace detail {
242
243 /*
244  * The following functions are type-overloaded helpers for
245  * internalSplit().
246  */
247 inline size_t delimSize(char)          { return 1; }
248 inline size_t delimSize(StringPiece s) { return s.size(); }
249 inline bool atDelim(const char* s, char c) {
250  return *s == c;
251 }
252 inline bool atDelim(const char* s, StringPiece sp) {
253   return !std::memcmp(s, sp.start(), sp.size());
254 }
255
256 // These are used to short-circuit internalSplit() in the case of
257 // 1-character strings.
258 inline char delimFront(char c) {
259   // This one exists only for compile-time; it should never be called.
260   std::abort();
261   return c;
262 }
263 inline char delimFront(StringPiece s) {
264   assert(!s.empty() && s.start() != nullptr);
265   return *s.start();
266 }
267
268 /*
269  * These output conversion templates allow us to support multiple
270  * output string types, even when we are using an arbitrary
271  * OutputIterator.
272  */
273 template<class OutStringT> struct OutputConverter {};
274
275 template<> struct OutputConverter<std::string> {
276   std::string operator()(StringPiece sp) const {
277     return sp.toString();
278   }
279 };
280
281 template<> struct OutputConverter<fbstring> {
282   fbstring operator()(StringPiece sp) const {
283     return sp.toFbstring();
284   }
285 };
286
287 template<> struct OutputConverter<StringPiece> {
288   StringPiece operator()(StringPiece sp) const { return sp; }
289 };
290
291 /*
292  * Shared implementation for all the split() overloads.
293  *
294  * This uses some external helpers that are overloaded to let this
295  * algorithm be more performant if the deliminator is a single
296  * character instead of a whole string.
297  *
298  * @param ignoreEmpty iff true, don't copy empty segments to output
299  */
300 template<class OutStringT, class DelimT, class OutputIterator>
301 void internalSplit(DelimT delim, StringPiece sp, OutputIterator out,
302     bool ignoreEmpty) {
303   assert(sp.empty() || sp.start() != nullptr);
304
305   const char* s = sp.start();
306   const size_t strSize = sp.size();
307   const size_t dSize = delimSize(delim);
308
309   OutputConverter<OutStringT> conv;
310
311   if (dSize > strSize || dSize == 0) {
312     if (!ignoreEmpty || strSize > 0) {
313       *out++ = conv(sp);
314     }
315     return;
316   }
317   if (boost::is_same<DelimT,StringPiece>::value && dSize == 1) {
318     // Call the char version because it is significantly faster.
319     return internalSplit<OutStringT>(delimFront(delim), sp, out,
320       ignoreEmpty);
321   }
322
323   int tokenStartPos = 0;
324   int tokenSize = 0;
325   for (int i = 0; i <= strSize - dSize; ++i) {
326     if (atDelim(&s[i], delim)) {
327       if (!ignoreEmpty || tokenSize > 0) {
328         *out++ = conv(StringPiece(&s[tokenStartPos], tokenSize));
329       }
330
331       tokenStartPos = i + dSize;
332       tokenSize = 0;
333       i += dSize - 1;
334     } else {
335       ++tokenSize;
336     }
337   }
338
339   if (!ignoreEmpty || tokenSize > 0) {
340     tokenSize = strSize - tokenStartPos;
341     *out++ = conv(StringPiece(&s[tokenStartPos], tokenSize));
342   }
343 }
344
345 template<class String> StringPiece prepareDelim(const String& s) {
346   return StringPiece(s);
347 }
348 inline char prepareDelim(char c) { return c; }
349
350 template <class Dst>
351 struct convertTo {
352   template <class Src>
353   static Dst from(const Src& src) { return folly::to<Dst>(src); }
354   static Dst from(const Dst& src) { return src; }
355 };
356
357 template<bool exact,
358          class Delim,
359          class OutputType>
360 typename std::enable_if<IsSplitTargetType<OutputType>::value, bool>::type
361 splitFixed(const Delim& delimiter,
362            StringPiece input,
363            OutputType& out) {
364   if (exact && UNLIKELY(std::string::npos != input.find(delimiter))) {
365     return false;
366   }
367   out = convertTo<OutputType>::from(input);
368   return true;
369 }
370
371 template<bool exact,
372          class Delim,
373          class OutputType,
374          class... OutputTypes>
375 typename std::enable_if<IsSplitTargetType<OutputType>::value, bool>::type
376 splitFixed(const Delim& delimiter,
377            StringPiece input,
378            OutputType& outHead,
379            OutputTypes&... outTail) {
380   size_t cut = input.find(delimiter);
381   if (UNLIKELY(cut == std::string::npos)) {
382     return false;
383   }
384   StringPiece head(input.begin(), input.begin() + cut);
385   StringPiece tail(input.begin() + cut + detail::delimSize(delimiter),
386                    input.end());
387   if (LIKELY(splitFixed<exact>(delimiter, tail, outTail...))) {
388     outHead = convertTo<OutputType>::from(head);
389     return true;
390   }
391   return false;
392 }
393
394 }
395
396 //////////////////////////////////////////////////////////////////////
397
398 template<class Delim, class String, class OutputType>
399 void split(const Delim& delimiter,
400            const String& input,
401            std::vector<OutputType>& out,
402            bool ignoreEmpty) {
403   detail::internalSplit<OutputType>(
404     detail::prepareDelim(delimiter),
405     StringPiece(input),
406     std::back_inserter(out),
407     ignoreEmpty);
408 }
409
410 template<class Delim, class String, class OutputType>
411 void split(const Delim& delimiter,
412            const String& input,
413            fbvector<OutputType>& out,
414            bool ignoreEmpty) {
415   detail::internalSplit<OutputType>(
416     detail::prepareDelim(delimiter),
417     StringPiece(input),
418     std::back_inserter(out),
419     ignoreEmpty);
420 }
421
422 template<class OutputValueType, class Delim, class String,
423          class OutputIterator>
424 void splitTo(const Delim& delimiter,
425              const String& input,
426              OutputIterator out,
427              bool ignoreEmpty) {
428   detail::internalSplit<OutputValueType>(
429     detail::prepareDelim(delimiter),
430     StringPiece(input),
431     out,
432     ignoreEmpty);
433 }
434
435 template<bool exact,
436          class Delim,
437          class OutputType,
438          class... OutputTypes>
439 typename std::enable_if<IsSplitTargetType<OutputType>::value, bool>::type
440 split(const Delim& delimiter,
441       StringPiece input,
442       OutputType& outHead,
443       OutputTypes&... outTail) {
444   return detail::splitFixed<exact>(
445     detail::prepareDelim(delimiter),
446     input,
447     outHead,
448     outTail...);
449 }
450
451 namespace detail {
452
453 /*
454  * If a type can have its string size determined cheaply, we can more
455  * efficiently append it in a loop (see internalJoinAppend). Note that the
456  * struct need not conform to the std::string api completely (ex. does not need
457  * to implement append()).
458  */
459 template <class T> struct IsSizableString {
460   enum { value = IsSomeString<T>::value
461          || std::is_same<T, StringPiece>::value };
462 };
463
464 template <class Iterator>
465 struct IsSizableStringContainerIterator :
466   IsSizableString<typename std::iterator_traits<Iterator>::value_type> {
467 };
468
469 template <class Delim, class Iterator, class String>
470 void internalJoinAppend(Delim delimiter,
471                         Iterator begin,
472                         Iterator end,
473                         String& output) {
474   assert(begin != end);
475   if (std::is_same<Delim, StringPiece>::value &&
476       delimSize(delimiter) == 1) {
477     internalJoinAppend(delimFront(delimiter), begin, end, output);
478     return;
479   }
480   toAppend(*begin, &output);
481   while (++begin != end) {
482     toAppend(delimiter, *begin, &output);
483   }
484 }
485
486 template <class Delim, class Iterator, class String>
487 typename std::enable_if<IsSizableStringContainerIterator<Iterator>::value>::type
488 internalJoin(Delim delimiter,
489              Iterator begin,
490              Iterator end,
491              String& output) {
492   output.clear();
493   if (begin == end) {
494     return;
495   }
496   const size_t dsize = delimSize(delimiter);
497   Iterator it = begin;
498   size_t size = it->size();
499   while (++it != end) {
500     size += dsize + it->size();
501   }
502   output.reserve(size);
503   internalJoinAppend(delimiter, begin, end, output);
504 }
505
506 template <class Delim, class Iterator, class String>
507 typename
508 std::enable_if<!IsSizableStringContainerIterator<Iterator>::value>::type
509 internalJoin(Delim delimiter,
510              Iterator begin,
511              Iterator end,
512              String& output) {
513   output.clear();
514   if (begin == end) {
515     return;
516   }
517   internalJoinAppend(delimiter, begin, end, output);
518 }
519
520 }  // namespace detail
521
522 template <class Delim, class Iterator, class String>
523 void join(const Delim& delimiter,
524           Iterator begin,
525           Iterator end,
526           String& output) {
527   detail::internalJoin(
528     detail::prepareDelim(delimiter),
529     begin,
530     end,
531     output);
532 }
533
534 template <class String1, class String2>
535 void backslashify(const String1& input, String2& output, bool hex_style) {
536   static const char hexValues[] = "0123456789abcdef";
537   output.clear();
538   output.reserve(3 * input.size());
539   for (unsigned char c : input) {
540     // less than space or greater than '~' are considered unprintable
541     if (c < 0x20 || c > 0x7e || c == '\\') {
542       bool hex_append = false;
543       output.push_back('\\');
544       if (hex_style) {
545         hex_append = true;
546       } else {
547         if (c == '\r') output += 'r';
548         else if (c == '\n') output += 'n';
549         else if (c == '\t') output += 't';
550         else if (c == '\a') output += 'a';
551         else if (c == '\b') output += 'b';
552         else if (c == '\0') output += '0';
553         else if (c == '\\') output += '\\';
554         else {
555           hex_append = true;
556         }
557       }
558       if (hex_append) {
559         output.push_back('x');
560         output.push_back(hexValues[(c >> 4) & 0xf]);
561         output.push_back(hexValues[c & 0xf]);
562       }
563     } else {
564       output += c;
565     }
566   }
567 }
568
569 template <class String1, class String2>
570 void humanify(const String1& input, String2& output) {
571   int numUnprintable = 0;
572   int numPrintablePrefix = 0;
573   for (unsigned char c : input) {
574     if (c < 0x20 || c > 0x7e || c == '\\') {
575       ++numUnprintable;
576     }
577     if (numUnprintable == 0) {
578       ++numPrintablePrefix;
579     }
580   }
581
582   // hexlify doubles a string's size; backslashify can potentially
583   // explode it by 4x.  Now, the printable range of the ascii
584   // "spectrum" is around 95 out of 256 values, so a "random" binary
585   // string should be around 60% unprintable.  We use a 50% hueristic
586   // here, so if a string is 60% unprintable, then we just use hex
587   // output.  Otherwise we backslash.
588   //
589   // UTF8 is completely ignored; as a result, utf8 characters will
590   // likely be \x escaped (since most common glyphs fit in two bytes).
591   // This is a tradeoff of complexity/speed instead of a convenience
592   // that likely would rarely matter.  Moreover, this function is more
593   // about displaying underlying bytes, not about displaying glyphs
594   // from languages.
595   if (numUnprintable == 0) {
596     output = input;
597   } else if (5 * numUnprintable >= 3 * input.size()) {
598     // However!  If we have a "meaningful" prefix of printable
599     // characters, say 20% of the string, we backslashify under the
600     // assumption viewing the prefix as ascii is worth blowing the
601     // output size up a bit.
602     if (5 * numPrintablePrefix >= input.size()) {
603       backslashify(input, output);
604     } else {
605       output = "0x";
606       hexlify(input, output, true /* append output */);
607     }
608   } else {
609     backslashify(input, output);
610   }
611 }
612
613 template<class InputString, class OutputString>
614 bool hexlify(const InputString& input, OutputString& output,
615              bool append_output) {
616   if (!append_output) output.clear();
617
618   static char hexValues[] = "0123456789abcdef";
619   int j = output.size();
620   output.resize(2 * input.size() + output.size());
621   for (int i = 0; i < input.size(); ++i) {
622     int ch = input[i];
623     output[j++] = hexValues[(ch >> 4) & 0xf];
624     output[j++] = hexValues[ch & 0xf];
625   }
626   return true;
627 }
628
629 template<class InputString, class OutputString>
630 bool unhexlify(const InputString& input, OutputString& output) {
631   if (input.size() % 2 != 0) {
632     return false;
633   }
634   output.resize(input.size() / 2);
635   int j = 0;
636   auto unhex = [](char c) -> int {
637     return c >= '0' && c <= '9' ? c - '0' :
638            c >= 'A' && c <= 'F' ? c - 'A' + 10 :
639            c >= 'a' && c <= 'f' ? c - 'a' + 10 :
640            -1;
641   };
642
643   for (int i = 0; i < input.size(); i += 2) {
644     int highBits = unhex(input[i]);
645     int lowBits = unhex(input[i + 1]);
646     if (highBits < 0 || lowBits < 0) {
647       return false;
648     }
649     output[j++] = (highBits << 4) + lowBits;
650   }
651   return true;
652 }
653
654 namespace detail {
655 /**
656  * Hex-dump at most 16 bytes starting at offset from a memory area of size
657  * bytes.  Return the number of bytes actually dumped.
658  */
659 size_t hexDumpLine(const void* ptr, size_t offset, size_t size,
660                    std::string& line);
661 }  // namespace detail
662
663 template <class OutIt>
664 void hexDump(const void* ptr, size_t size, OutIt out) {
665   size_t offset = 0;
666   std::string line;
667   while (offset < size) {
668     offset += detail::hexDumpLine(ptr, offset, size, line);
669     *out++ = line;
670   }
671 }
672
673 }  // namespace folly
674
675 #endif /* FOLLY_STRING_INL_H_ */