Add mechanizm for caching local and peer addresses in AsyncSSLSocket.
[folly.git] / folly / String-inl.h
1 /*
2  * Copyright 2015 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     switch (c) {
207     case '%':
208       {
209         if (UNLIKELY(std::distance(p, str.end()) < 3)) {
210           throw std::invalid_argument("incomplete percent encode sequence");
211         }
212         auto h1 = detail::hexTable[static_cast<unsigned char>(p[1])];
213         auto h2 = detail::hexTable[static_cast<unsigned char>(p[2])];
214         if (UNLIKELY(h1 == 16 || h2 == 16)) {
215           throw std::invalid_argument("invalid percent encode sequence");
216         }
217         out.append(&*last, p - last);
218         out.push_back((h1 << 4) | h2);
219         p += 3;
220         last = p;
221         break;
222       }
223     case '+':
224       if (mode == UriEscapeMode::QUERY) {
225         out.append(&*last, p - last);
226         out.push_back(' ');
227         ++p;
228         last = p;
229         break;
230       }
231       // else fallthrough
232     default:
233       ++p;
234       break;
235     }
236   }
237   out.append(&*last, p - last);
238 }
239
240 namespace detail {
241
242 /*
243  * The following functions are type-overloaded helpers for
244  * internalSplit().
245  */
246 inline size_t delimSize(char)          { return 1; }
247 inline size_t delimSize(StringPiece s) { return s.size(); }
248 inline bool atDelim(const char* s, char c) {
249  return *s == c;
250 }
251 inline bool atDelim(const char* s, StringPiece sp) {
252   return !std::memcmp(s, sp.start(), sp.size());
253 }
254
255 // These are used to short-circuit internalSplit() in the case of
256 // 1-character strings.
257 inline char delimFront(char c) {
258   // This one exists only for compile-time; it should never be called.
259   std::abort();
260   return c;
261 }
262 inline char delimFront(StringPiece s) {
263   assert(!s.empty() && s.start() != nullptr);
264   return *s.start();
265 }
266
267 /*
268  * These output conversion templates allow us to support multiple
269  * output string types, even when we are using an arbitrary
270  * OutputIterator.
271  */
272 template<class OutStringT> struct OutputConverter {};
273
274 template<> struct OutputConverter<std::string> {
275   std::string operator()(StringPiece sp) const {
276     return sp.toString();
277   }
278 };
279
280 template<> struct OutputConverter<fbstring> {
281   fbstring operator()(StringPiece sp) const {
282     return sp.toFbstring();
283   }
284 };
285
286 template<> struct OutputConverter<StringPiece> {
287   StringPiece operator()(StringPiece sp) const { return sp; }
288 };
289
290 /*
291  * Shared implementation for all the split() overloads.
292  *
293  * This uses some external helpers that are overloaded to let this
294  * algorithm be more performant if the deliminator is a single
295  * character instead of a whole string.
296  *
297  * @param ignoreEmpty iff true, don't copy empty segments to output
298  */
299 template<class OutStringT, class DelimT, class OutputIterator>
300 void internalSplit(DelimT delim, StringPiece sp, OutputIterator out,
301     bool ignoreEmpty) {
302   assert(sp.empty() || sp.start() != nullptr);
303
304   const char* s = sp.start();
305   const size_t strSize = sp.size();
306   const size_t dSize = delimSize(delim);
307
308   OutputConverter<OutStringT> conv;
309
310   if (dSize > strSize || dSize == 0) {
311     if (!ignoreEmpty || strSize > 0) {
312       *out++ = conv(sp);
313     }
314     return;
315   }
316   if (boost::is_same<DelimT,StringPiece>::value && dSize == 1) {
317     // Call the char version because it is significantly faster.
318     return internalSplit<OutStringT>(delimFront(delim), sp, out,
319       ignoreEmpty);
320   }
321
322   size_t tokenStartPos = 0;
323   size_t tokenSize = 0;
324   for (size_t i = 0; i <= strSize - dSize; ++i) {
325     if (atDelim(&s[i], delim)) {
326       if (!ignoreEmpty || tokenSize > 0) {
327         *out++ = conv(StringPiece(&s[tokenStartPos], tokenSize));
328       }
329
330       tokenStartPos = i + dSize;
331       tokenSize = 0;
332       i += dSize - 1;
333     } else {
334       ++tokenSize;
335     }
336   }
337   tokenSize = strSize - tokenStartPos;
338   if (!ignoreEmpty || tokenSize > 0) {
339     *out++ = conv(StringPiece(&s[tokenStartPos], tokenSize));
340   }
341 }
342
343 template<class String> StringPiece prepareDelim(const String& s) {
344   return StringPiece(s);
345 }
346 inline char prepareDelim(char c) { return c; }
347
348 template <class Dst>
349 struct convertTo {
350   template <class Src>
351   static Dst from(const Src& src) { return folly::to<Dst>(src); }
352   static Dst from(const Dst& src) { return src; }
353 };
354
355 template<bool exact,
356          class Delim,
357          class OutputType>
358 typename std::enable_if<IsSplitTargetType<OutputType>::value, bool>::type
359 splitFixed(const Delim& delimiter,
360            StringPiece input,
361            OutputType& out) {
362   if (exact && UNLIKELY(std::string::npos != input.find(delimiter))) {
363     return false;
364   }
365   out = convertTo<OutputType>::from(input);
366   return true;
367 }
368
369 template<bool exact,
370          class Delim,
371          class OutputType,
372          class... OutputTypes>
373 typename std::enable_if<IsSplitTargetType<OutputType>::value, bool>::type
374 splitFixed(const Delim& delimiter,
375            StringPiece input,
376            OutputType& outHead,
377            OutputTypes&... outTail) {
378   size_t cut = input.find(delimiter);
379   if (UNLIKELY(cut == std::string::npos)) {
380     return false;
381   }
382   StringPiece head(input.begin(), input.begin() + cut);
383   StringPiece tail(input.begin() + cut + detail::delimSize(delimiter),
384                    input.end());
385   if (LIKELY(splitFixed<exact>(delimiter, tail, outTail...))) {
386     outHead = convertTo<OutputType>::from(head);
387     return true;
388   }
389   return false;
390 }
391
392 }
393
394 //////////////////////////////////////////////////////////////////////
395
396 template<class Delim, class String, class OutputType>
397 void split(const Delim& delimiter,
398            const String& input,
399            std::vector<OutputType>& out,
400            bool ignoreEmpty) {
401   detail::internalSplit<OutputType>(
402     detail::prepareDelim(delimiter),
403     StringPiece(input),
404     std::back_inserter(out),
405     ignoreEmpty);
406 }
407
408 template<class Delim, class String, class OutputType>
409 void split(const Delim& delimiter,
410            const String& input,
411            fbvector<OutputType>& out,
412            bool ignoreEmpty) {
413   detail::internalSplit<OutputType>(
414     detail::prepareDelim(delimiter),
415     StringPiece(input),
416     std::back_inserter(out),
417     ignoreEmpty);
418 }
419
420 template<class OutputValueType, class Delim, class String,
421          class OutputIterator>
422 void splitTo(const Delim& delimiter,
423              const String& input,
424              OutputIterator out,
425              bool ignoreEmpty) {
426   detail::internalSplit<OutputValueType>(
427     detail::prepareDelim(delimiter),
428     StringPiece(input),
429     out,
430     ignoreEmpty);
431 }
432
433 template<bool exact,
434          class Delim,
435          class OutputType,
436          class... OutputTypes>
437 typename std::enable_if<IsSplitTargetType<OutputType>::value, bool>::type
438 split(const Delim& delimiter,
439       StringPiece input,
440       OutputType& outHead,
441       OutputTypes&... outTail) {
442   return detail::splitFixed<exact>(
443     detail::prepareDelim(delimiter),
444     input,
445     outHead,
446     outTail...);
447 }
448
449 namespace detail {
450
451 /*
452  * If a type can have its string size determined cheaply, we can more
453  * efficiently append it in a loop (see internalJoinAppend). Note that the
454  * struct need not conform to the std::string api completely (ex. does not need
455  * to implement append()).
456  */
457 template <class T> struct IsSizableString {
458   enum { value = IsSomeString<T>::value
459          || std::is_same<T, StringPiece>::value };
460 };
461
462 template <class Iterator>
463 struct IsSizableStringContainerIterator :
464   IsSizableString<typename std::iterator_traits<Iterator>::value_type> {
465 };
466
467 template <class Delim, class Iterator, class String>
468 void internalJoinAppend(Delim delimiter,
469                         Iterator begin,
470                         Iterator end,
471                         String& output) {
472   assert(begin != end);
473   if (std::is_same<Delim, StringPiece>::value &&
474       delimSize(delimiter) == 1) {
475     internalJoinAppend(delimFront(delimiter), begin, end, output);
476     return;
477   }
478   toAppend(*begin, &output);
479   while (++begin != end) {
480     toAppend(delimiter, *begin, &output);
481   }
482 }
483
484 template <class Delim, class Iterator, class String>
485 typename std::enable_if<IsSizableStringContainerIterator<Iterator>::value>::type
486 internalJoin(Delim delimiter,
487              Iterator begin,
488              Iterator end,
489              String& output) {
490   output.clear();
491   if (begin == end) {
492     return;
493   }
494   const size_t dsize = delimSize(delimiter);
495   Iterator it = begin;
496   size_t size = it->size();
497   while (++it != end) {
498     size += dsize + it->size();
499   }
500   output.reserve(size);
501   internalJoinAppend(delimiter, begin, end, output);
502 }
503
504 template <class Delim, class Iterator, class String>
505 typename
506 std::enable_if<!IsSizableStringContainerIterator<Iterator>::value>::type
507 internalJoin(Delim delimiter,
508              Iterator begin,
509              Iterator end,
510              String& output) {
511   output.clear();
512   if (begin == end) {
513     return;
514   }
515   internalJoinAppend(delimiter, begin, end, output);
516 }
517
518 }  // namespace detail
519
520 template <class Delim, class Iterator, class String>
521 void join(const Delim& delimiter,
522           Iterator begin,
523           Iterator end,
524           String& output) {
525   detail::internalJoin(
526     detail::prepareDelim(delimiter),
527     begin,
528     end,
529     output);
530 }
531
532 template <class String1, class String2>
533 void backslashify(const String1& input, String2& output, bool hex_style) {
534   static const char hexValues[] = "0123456789abcdef";
535   output.clear();
536   output.reserve(3 * input.size());
537   for (unsigned char c : input) {
538     // less than space or greater than '~' are considered unprintable
539     if (c < 0x20 || c > 0x7e || c == '\\') {
540       bool hex_append = false;
541       output.push_back('\\');
542       if (hex_style) {
543         hex_append = true;
544       } else {
545         if (c == '\r') output += 'r';
546         else if (c == '\n') output += 'n';
547         else if (c == '\t') output += 't';
548         else if (c == '\a') output += 'a';
549         else if (c == '\b') output += 'b';
550         else if (c == '\0') output += '0';
551         else if (c == '\\') output += '\\';
552         else {
553           hex_append = true;
554         }
555       }
556       if (hex_append) {
557         output.push_back('x');
558         output.push_back(hexValues[(c >> 4) & 0xf]);
559         output.push_back(hexValues[c & 0xf]);
560       }
561     } else {
562       output += c;
563     }
564   }
565 }
566
567 template <class String1, class String2>
568 void humanify(const String1& input, String2& output) {
569   size_t numUnprintable = 0;
570   size_t numPrintablePrefix = 0;
571   for (unsigned char c : input) {
572     if (c < 0x20 || c > 0x7e || c == '\\') {
573       ++numUnprintable;
574     }
575     if (numUnprintable == 0) {
576       ++numPrintablePrefix;
577     }
578   }
579
580   // hexlify doubles a string's size; backslashify can potentially
581   // explode it by 4x.  Now, the printable range of the ascii
582   // "spectrum" is around 95 out of 256 values, so a "random" binary
583   // string should be around 60% unprintable.  We use a 50% hueristic
584   // here, so if a string is 60% unprintable, then we just use hex
585   // output.  Otherwise we backslash.
586   //
587   // UTF8 is completely ignored; as a result, utf8 characters will
588   // likely be \x escaped (since most common glyphs fit in two bytes).
589   // This is a tradeoff of complexity/speed instead of a convenience
590   // that likely would rarely matter.  Moreover, this function is more
591   // about displaying underlying bytes, not about displaying glyphs
592   // from languages.
593   if (numUnprintable == 0) {
594     output = input;
595   } else if (5 * numUnprintable >= 3 * input.size()) {
596     // However!  If we have a "meaningful" prefix of printable
597     // characters, say 20% of the string, we backslashify under the
598     // assumption viewing the prefix as ascii is worth blowing the
599     // output size up a bit.
600     if (5 * numPrintablePrefix >= input.size()) {
601       backslashify(input, output);
602     } else {
603       output = "0x";
604       hexlify(input, output, true /* append output */);
605     }
606   } else {
607     backslashify(input, output);
608   }
609 }
610
611 template<class InputString, class OutputString>
612 bool hexlify(const InputString& input, OutputString& output,
613              bool append_output) {
614   if (!append_output) output.clear();
615
616   static char hexValues[] = "0123456789abcdef";
617   auto j = output.size();
618   output.resize(2 * input.size() + output.size());
619   for (size_t i = 0; i < input.size(); ++i) {
620     int ch = input[i];
621     output[j++] = hexValues[(ch >> 4) & 0xf];
622     output[j++] = hexValues[ch & 0xf];
623   }
624   return true;
625 }
626
627 template<class InputString, class OutputString>
628 bool unhexlify(const InputString& input, OutputString& output) {
629   if (input.size() % 2 != 0) {
630     return false;
631   }
632   output.resize(input.size() / 2);
633   int j = 0;
634   auto unhex = [](char c) -> int {
635     return c >= '0' && c <= '9' ? c - '0' :
636            c >= 'A' && c <= 'F' ? c - 'A' + 10 :
637            c >= 'a' && c <= 'f' ? c - 'a' + 10 :
638            -1;
639   };
640
641   for (size_t i = 0; i < input.size(); i += 2) {
642     int highBits = unhex(input[i]);
643     int lowBits = unhex(input[i + 1]);
644     if (highBits < 0 || lowBits < 0) {
645       return false;
646     }
647     output[j++] = (highBits << 4) + lowBits;
648   }
649   return true;
650 }
651
652 namespace detail {
653 /**
654  * Hex-dump at most 16 bytes starting at offset from a memory area of size
655  * bytes.  Return the number of bytes actually dumped.
656  */
657 size_t hexDumpLine(const void* ptr, size_t offset, size_t size,
658                    std::string& line);
659 }  // namespace detail
660
661 template <class OutIt>
662 void hexDump(const void* ptr, size_t size, OutIt out) {
663   size_t offset = 0;
664   std::string line;
665   while (offset < size) {
666     offset += detail::hexDumpLine(ptr, offset, size, line);
667     *out++ = line;
668   }
669 }
670
671 }  // namespace folly
672
673 #endif /* FOLLY_STRING_INL_H_ */