02d376d82f06e02fd4b64b30f6758705091cc0ca
[folly.git] / folly / String-inl.h
1 /*
2  * Copyright 2012 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
154 /*
155  * The following functions are type-overloaded helpers for
156  * internalSplit().
157  */
158 inline size_t delimSize(char)          { return 1; }
159 inline size_t delimSize(StringPiece s) { return s.size(); }
160 inline bool atDelim(const char* s, char c) {
161  return *s == c;
162 }
163 inline bool atDelim(const char* s, StringPiece sp) {
164   return !std::memcmp(s, sp.start(), sp.size());
165 }
166
167 // These are used to short-circuit internalSplit() in the case of
168 // 1-character strings.
169 inline char delimFront(char c) {
170   // This one exists only for compile-time; it should never be called.
171   std::abort();
172   return c;
173 }
174 inline char delimFront(StringPiece s) {
175   assert(!s.empty() && s.start() != nullptr);
176   return *s.start();
177 }
178
179 /*
180  * These output conversion templates allow us to support multiple
181  * output string types, even when we are using an arbitrary
182  * OutputIterator.
183  */
184 template<class OutStringT> struct OutputConverter {};
185
186 template<> struct OutputConverter<std::string> {
187   std::string operator()(StringPiece sp) const {
188     return sp.toString();
189   }
190 };
191
192 template<> struct OutputConverter<fbstring> {
193   fbstring operator()(StringPiece sp) const {
194     return sp.toFbstring();
195   }
196 };
197
198 template<> struct OutputConverter<StringPiece> {
199   StringPiece operator()(StringPiece sp) const { return sp; }
200 };
201
202 /*
203  * Shared implementation for all the split() overloads.
204  *
205  * This uses some external helpers that are overloaded to let this
206  * algorithm be more performant if the deliminator is a single
207  * character instead of a whole string.
208  *
209  * @param ignoreEmpty iff true, don't copy empty segments to output
210  */
211 template<class OutStringT, class DelimT, class OutputIterator>
212 void internalSplit(DelimT delim, StringPiece sp, OutputIterator out,
213     bool ignoreEmpty) {
214   assert(sp.start() != nullptr);
215
216   const char* s = sp.start();
217   const size_t strSize = sp.size();
218   const size_t dSize = delimSize(delim);
219
220   OutputConverter<OutStringT> conv;
221
222   if (dSize > strSize || dSize == 0) {
223     if (!ignoreEmpty || strSize > 0) {
224       *out++ = conv(sp);
225     }
226     return;
227   }
228   if (boost::is_same<DelimT,StringPiece>::value && dSize == 1) {
229     // Call the char version because it is significantly faster.
230     return internalSplit<OutStringT>(delimFront(delim), sp, out,
231       ignoreEmpty);
232   }
233
234   int tokenStartPos = 0;
235   int tokenSize = 0;
236   for (int i = 0; i <= strSize - dSize; ++i) {
237     if (atDelim(&s[i], delim)) {
238       if (!ignoreEmpty || tokenSize > 0) {
239         *out++ = conv(StringPiece(&s[tokenStartPos], tokenSize));
240       }
241
242       tokenStartPos = i + dSize;
243       tokenSize = 0;
244       i += dSize - 1;
245     } else {
246       ++tokenSize;
247     }
248   }
249
250   if (!ignoreEmpty || tokenSize > 0) {
251     tokenSize = strSize - tokenStartPos;
252     *out++ = conv(StringPiece(&s[tokenStartPos], tokenSize));
253   }
254 }
255
256 template<class String> StringPiece prepareDelim(const String& s) {
257   return StringPiece(s);
258 }
259 inline char prepareDelim(char c) { return c; }
260
261 }
262
263 //////////////////////////////////////////////////////////////////////
264
265 template<class Delim, class String, class OutputType>
266 void split(const Delim& delimiter,
267            const String& input,
268            std::vector<OutputType>& out,
269            bool ignoreEmpty) {
270   detail::internalSplit<OutputType>(
271     detail::prepareDelim(delimiter),
272     StringPiece(input),
273     std::back_inserter(out),
274     ignoreEmpty);
275 }
276
277 template<class Delim, class String, class OutputType>
278 void split(const Delim& delimiter,
279            const String& input,
280            fbvector<OutputType>& out,
281            bool ignoreEmpty = false) {
282   detail::internalSplit<OutputType>(
283     detail::prepareDelim(delimiter),
284     StringPiece(input),
285     std::back_inserter(out),
286     ignoreEmpty);
287 }
288
289 template<class OutputValueType, class Delim, class String,
290          class OutputIterator>
291 void splitTo(const Delim& delimiter,
292              const String& input,
293              OutputIterator out,
294              bool ignoreEmpty) {
295   detail::internalSplit<OutputValueType>(
296     detail::prepareDelim(delimiter),
297     StringPiece(input),
298     out,
299     ignoreEmpty);
300 }
301
302 namespace detail {
303
304 template <class Iterator>
305 struct IsStringContainerIterator :
306   IsSomeString<typename std::iterator_traits<Iterator>::value_type> {
307 };
308
309 template <class Delim, class Iterator, class String>
310 void internalJoinAppend(Delim delimiter,
311                         Iterator begin,
312                         Iterator end,
313                         String& output) {
314   assert(begin != end);
315   toAppend(*begin, &output);
316   while (++begin != end) {
317     toAppend(delimiter, *begin, &output);
318   }
319 }
320
321 template <class Delim, class Iterator, class String>
322 typename std::enable_if<IsStringContainerIterator<Iterator>::value>::type
323 internalJoin(Delim delimiter,
324              Iterator begin,
325              Iterator end,
326              String& output) {
327   output.clear();
328   if (begin == end) {
329     return;
330   }
331   const size_t dsize = delimSize(delimiter);
332   Iterator it = begin;
333   size_t size = it->size();
334   while (++it != end) {
335     size += dsize + it->size();
336   }
337   output.reserve(size);
338   internalJoinAppend(delimiter, begin, end, output);
339 }
340
341 template <class Delim, class Iterator, class String>
342 typename std::enable_if<!IsStringContainerIterator<Iterator>::value>::type
343 internalJoin(Delim delimiter,
344              Iterator begin,
345              Iterator end,
346              String& output) {
347   output.clear();
348   if (begin == end) {
349     return;
350   }
351   internalJoinAppend(delimiter, begin, end, output);
352 }
353
354 }  // namespace detail
355
356 template <class Delim, class Iterator, class String>
357 void join(const Delim& delimiter,
358           Iterator begin,
359           Iterator end,
360           String& output) {
361   detail::internalJoin(
362     detail::prepareDelim(delimiter),
363     begin,
364     end,
365     output);
366 }
367
368 template <class String1, class String2>
369 void backslashify(const String1& input, String2& output, bool hex_style) {
370   static const char hexValues[] = "0123456789abcdef";
371   output.clear();
372   output.reserve(3 * input.size());
373   for (unsigned char c : input) {
374     // less than space or greater than '~' are considered unprintable
375     if (c < 0x20 || c > 0x7e || c == '\\') {
376       bool hex_append = false;
377       output.push_back('\\');
378       if (hex_style) {
379         hex_append = true;
380       } else {
381         if (c == '\r') output += 'r';
382         else if (c == '\n') output += 'n';
383         else if (c == '\t') output += 't';
384         else if (c == '\a') output += 'a';
385         else if (c == '\b') output += 'b';
386         else if (c == '\0') output += '0';
387         else if (c == '\\') output += '\\';
388         else {
389           hex_append = true;
390         }
391       }
392       if (hex_append) {
393         output.push_back('x');
394         output.push_back(hexValues[(c >> 4) & 0xf]);
395         output.push_back(hexValues[c & 0xf]);
396       }
397     } else {
398       output += c;
399     }
400   }
401 }
402
403 template <class String1, class String2>
404 void humanify(const String1& input, String2& output) {
405   int numUnprintable = 0;
406   int numPrintablePrefix = 0;
407   for (unsigned char c : input) {
408     if (c < 0x20 || c > 0x7e || c == '\\') {
409       ++numUnprintable;
410     }
411     if (numUnprintable == 0) {
412       ++numPrintablePrefix;
413     }
414   }
415
416   // hexlify doubles a string's size; backslashify can potentially
417   // explode it by 4x.  Now, the printable range of the ascii
418   // "spectrum" is around 95 out of 256 values, so a "random" binary
419   // string should be around 60% unprintable.  We use a 50% hueristic
420   // here, so if a string is 60% unprintable, then we just use hex
421   // output.  Otherwise we backslash.
422   //
423   // UTF8 is completely ignored; as a result, utf8 characters will
424   // likely be \x escaped (since most common glyphs fit in two bytes).
425   // This is a tradeoff of complexity/speed instead of a convenience
426   // that likely would rarely matter.  Moreover, this function is more
427   // about displaying underlying bytes, not about displaying glyphs
428   // from languages.
429   if (numUnprintable == 0) {
430     output = input;
431   } else if (5 * numUnprintable >= 3 * input.size()) {
432     // However!  If we have a "meaningful" prefix of printable
433     // characters, say 20% of the string, we backslashify under the
434     // assumption viewing the prefix as ascii is worth blowing the
435     // output size up a bit.
436     if (5 * numPrintablePrefix >= input.size()) {
437       backslashify(input, output);
438     } else {
439       output = "0x";
440       hexlify(input, output, true /* append output */);
441     }
442   } else {
443     backslashify(input, output);
444   }
445 }
446
447 template<class InputString, class OutputString>
448 bool hexlify(const InputString& input, OutputString& output,
449              bool append_output=false) {
450   if (!append_output) output.clear();
451
452   static char hexValues[] = "0123456789abcdef";
453   int j = output.size();
454   output.resize(2 * input.size() + output.size());
455   for (int i = 0; i < input.size(); ++i) {
456     int ch = input[i];
457     output[j++] = hexValues[(ch >> 4) & 0xf];
458     output[j++] = hexValues[ch & 0xf];
459   }
460   return true;
461 }
462
463 template<class InputString, class OutputString>
464 bool unhexlify(const InputString& input, OutputString& output) {
465   if (input.size() % 2 != 0) {
466     return false;
467   }
468   output.resize(input.size() / 2);
469   int j = 0;
470   auto unhex = [](char c) -> int {
471     return c >= '0' && c <= '9' ? c - '0' :
472            c >= 'A' && c <= 'F' ? c - 'A' + 10 :
473            c >= 'a' && c <= 'f' ? c - 'a' + 10 :
474            -1;
475   };
476
477   for (int i = 0; i < input.size(); i += 2) {
478     int highBits = unhex(input[i]);
479     int lowBits = unhex(input[i + 1]);
480     if (highBits < 0 || lowBits < 0) {
481       return false;
482     }
483     output[j++] = (highBits << 4) + lowBits;
484   }
485   return true;
486 }
487
488 namespace detail {
489 /**
490  * Hex-dump at most 16 bytes starting at offset from a memory area of size
491  * bytes.  Return the number of bytes actually dumped.
492  */
493 size_t hexDumpLine(const void* ptr, size_t offset, size_t size,
494                    std::string& line);
495 }  // namespace detail
496
497 template <class OutIt>
498 void hexDump(const void* ptr, size_t size, OutIt out) {
499   size_t offset = 0;
500   std::string line;
501   while (offset < size) {
502     offset += detail::hexDumpLine(ptr, offset, size, line);
503     *out++ = line;
504   }
505 }
506
507 }  // namespace folly
508
509 #endif /* FOLLY_STRING_INL_H_ */
510