2 * Copyright 2013 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #ifndef FOLLY_STRING_INL_H_
18 #define FOLLY_STRING_INL_H_
23 #ifndef FOLLY_BASE_STRING_H_
24 #error This file may only be included from String.h
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[];
37 template <class String>
38 void cEscape(StringPiece str, String& out) {
41 out.reserve(out.size() + str.size());
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
47 while (p != str.end()) {
49 unsigned char v = static_cast<unsigned char>(c);
50 char e = detail::cEscapeTable[v];
51 if (e == 'P') { // printable
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);
61 } else { // special 1-character escape
62 out.append(&*last, p - last);
69 out.append(&*last, p - last);
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[];
80 // Map from the character code to the hex value, or 16 if invalid hex char.
81 extern const unsigned char hexTable[];
84 template <class String>
85 void cUnescape(StringPiece str, String& out, bool strict) {
86 out.reserve(out.size() + str.size());
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()) {
93 if (c != '\\') { // normal case
97 out.append(&*last, p - last);
98 if (p == str.end()) { // backslash at end of string
100 throw std::invalid_argument("incomplete escape sequence");
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';
112 val = (val << 3) | (*p - '0');
116 } else if (e == 'X') { // hex
118 if (p == str.end()) { // \x at end of string
120 throw std::invalid_argument("incomplete hex escape sequence");
126 unsigned char val = 0;
128 for (; (p != str.end() &&
129 (h = detail::hexTable[static_cast<unsigned char>(*p)]) < 16);
131 val = (val << 4) | h;
135 } else if (e == 'I') { // invalid
137 throw std::invalid_argument("invalid escape sequence");
143 } else { // standard escape sequence, \' etc
149 out.append(&*last, p - last);
153 // Map from character code to escape mode:
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
162 template <class String>
163 void uriEscape(StringPiece str, String& out, UriEscapeMode mode) {
164 static const char hexValues[] = "0123456789abcdef";
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()) {
176 unsigned char v = static_cast<unsigned char>(c);
177 unsigned char discriminator = detail::uriEscapeTable[v];
178 if (LIKELY(discriminator <= minEncode)) {
180 } else if (mode == UriEscapeMode::QUERY && discriminator == 3) {
181 out.append(&*last, p - last);
186 out.append(&*last, p - last);
187 esc[1] = hexValues[v >> 4];
188 esc[2] = hexValues[v & 0x0f];
194 out.append(&*last, p - last);
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();
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()) {
206 unsigned char v = static_cast<unsigned char>(v);
210 if (UNLIKELY(std::distance(p, str.end()) < 3)) {
211 throw std::invalid_argument("incomplete percent encode sequence");
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");
218 out.append(&*last, p - last);
219 out.push_back((h1 << 4) | h2);
225 if (mode == UriEscapeMode::QUERY) {
226 out.append(&*last, p - last);
238 out.append(&*last, p - last);
244 * The following functions are type-overloaded helpers for
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) {
252 inline bool atDelim(const char* s, StringPiece sp) {
253 return !std::memcmp(s, sp.start(), sp.size());
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.
263 inline char delimFront(StringPiece s) {
264 assert(!s.empty() && s.start() != nullptr);
269 * These output conversion templates allow us to support multiple
270 * output string types, even when we are using an arbitrary
273 template<class OutStringT> struct OutputConverter {};
275 template<> struct OutputConverter<std::string> {
276 std::string operator()(StringPiece sp) const {
277 return sp.toString();
281 template<> struct OutputConverter<fbstring> {
282 fbstring operator()(StringPiece sp) const {
283 return sp.toFbstring();
287 template<> struct OutputConverter<StringPiece> {
288 StringPiece operator()(StringPiece sp) const { return sp; }
292 * Shared implementation for all the split() overloads.
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.
298 * @param ignoreEmpty iff true, don't copy empty segments to output
300 template<class OutStringT, class DelimT, class OutputIterator>
301 void internalSplit(DelimT delim, StringPiece sp, OutputIterator out,
303 assert(sp.start() != nullptr);
305 const char* s = sp.start();
306 const size_t strSize = sp.size();
307 const size_t dSize = delimSize(delim);
309 OutputConverter<OutStringT> conv;
311 if (dSize > strSize || dSize == 0) {
312 if (!ignoreEmpty || strSize > 0) {
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,
323 int tokenStartPos = 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));
331 tokenStartPos = i + dSize;
339 if (!ignoreEmpty || tokenSize > 0) {
340 tokenSize = strSize - tokenStartPos;
341 *out++ = conv(StringPiece(&s[tokenStartPos], tokenSize));
345 template<class String> StringPiece prepareDelim(const String& s) {
346 return StringPiece(s);
348 inline char prepareDelim(char c) { return c; }
352 //////////////////////////////////////////////////////////////////////
354 template<class Delim, class String, class OutputType>
355 void split(const Delim& delimiter,
357 std::vector<OutputType>& out,
359 detail::internalSplit<OutputType>(
360 detail::prepareDelim(delimiter),
362 std::back_inserter(out),
366 template<class Delim, class String, class OutputType>
367 void split(const Delim& delimiter,
369 fbvector<OutputType>& out,
371 detail::internalSplit<OutputType>(
372 detail::prepareDelim(delimiter),
374 std::back_inserter(out),
378 template<class OutputValueType, class Delim, class String,
379 class OutputIterator>
380 void splitTo(const Delim& delimiter,
384 detail::internalSplit<OutputValueType>(
385 detail::prepareDelim(delimiter),
393 template <class Iterator>
394 struct IsStringContainerIterator :
395 IsSomeString<typename std::iterator_traits<Iterator>::value_type> {
398 template <class Delim, class Iterator, class String>
399 void internalJoinAppend(Delim delimiter,
403 assert(begin != end);
404 if (std::is_same<Delim, StringPiece>::value &&
405 delimSize(delimiter) == 1) {
406 internalJoinAppend(delimFront(delimiter), begin, end, output);
409 toAppend(*begin, &output);
410 while (++begin != end) {
411 toAppend(delimiter, *begin, &output);
415 template <class Delim, class Iterator, class String>
416 typename std::enable_if<IsStringContainerIterator<Iterator>::value>::type
417 internalJoin(Delim delimiter,
425 const size_t dsize = delimSize(delimiter);
427 size_t size = it->size();
428 while (++it != end) {
429 size += dsize + it->size();
431 output.reserve(size);
432 internalJoinAppend(delimiter, begin, end, output);
435 template <class Delim, class Iterator, class String>
436 typename std::enable_if<!IsStringContainerIterator<Iterator>::value>::type
437 internalJoin(Delim delimiter,
445 internalJoinAppend(delimiter, begin, end, output);
448 } // namespace detail
450 template <class Delim, class Iterator, class String>
451 void join(const Delim& delimiter,
455 detail::internalJoin(
456 detail::prepareDelim(delimiter),
462 template <class String1, class String2>
463 void backslashify(const String1& input, String2& output, bool hex_style) {
464 static const char hexValues[] = "0123456789abcdef";
466 output.reserve(3 * input.size());
467 for (unsigned char c : input) {
468 // less than space or greater than '~' are considered unprintable
469 if (c < 0x20 || c > 0x7e || c == '\\') {
470 bool hex_append = false;
471 output.push_back('\\');
475 if (c == '\r') output += 'r';
476 else if (c == '\n') output += 'n';
477 else if (c == '\t') output += 't';
478 else if (c == '\a') output += 'a';
479 else if (c == '\b') output += 'b';
480 else if (c == '\0') output += '0';
481 else if (c == '\\') output += '\\';
487 output.push_back('x');
488 output.push_back(hexValues[(c >> 4) & 0xf]);
489 output.push_back(hexValues[c & 0xf]);
497 template <class String1, class String2>
498 void humanify(const String1& input, String2& output) {
499 int numUnprintable = 0;
500 int numPrintablePrefix = 0;
501 for (unsigned char c : input) {
502 if (c < 0x20 || c > 0x7e || c == '\\') {
505 if (numUnprintable == 0) {
506 ++numPrintablePrefix;
510 // hexlify doubles a string's size; backslashify can potentially
511 // explode it by 4x. Now, the printable range of the ascii
512 // "spectrum" is around 95 out of 256 values, so a "random" binary
513 // string should be around 60% unprintable. We use a 50% hueristic
514 // here, so if a string is 60% unprintable, then we just use hex
515 // output. Otherwise we backslash.
517 // UTF8 is completely ignored; as a result, utf8 characters will
518 // likely be \x escaped (since most common glyphs fit in two bytes).
519 // This is a tradeoff of complexity/speed instead of a convenience
520 // that likely would rarely matter. Moreover, this function is more
521 // about displaying underlying bytes, not about displaying glyphs
523 if (numUnprintable == 0) {
525 } else if (5 * numUnprintable >= 3 * input.size()) {
526 // However! If we have a "meaningful" prefix of printable
527 // characters, say 20% of the string, we backslashify under the
528 // assumption viewing the prefix as ascii is worth blowing the
529 // output size up a bit.
530 if (5 * numPrintablePrefix >= input.size()) {
531 backslashify(input, output);
534 hexlify(input, output, true /* append output */);
537 backslashify(input, output);
541 template<class InputString, class OutputString>
542 bool hexlify(const InputString& input, OutputString& output,
543 bool append_output) {
544 if (!append_output) output.clear();
546 static char hexValues[] = "0123456789abcdef";
547 int j = output.size();
548 output.resize(2 * input.size() + output.size());
549 for (int i = 0; i < input.size(); ++i) {
551 output[j++] = hexValues[(ch >> 4) & 0xf];
552 output[j++] = hexValues[ch & 0xf];
557 template<class InputString, class OutputString>
558 bool unhexlify(const InputString& input, OutputString& output) {
559 if (input.size() % 2 != 0) {
562 output.resize(input.size() / 2);
564 auto unhex = [](char c) -> int {
565 return c >= '0' && c <= '9' ? c - '0' :
566 c >= 'A' && c <= 'F' ? c - 'A' + 10 :
567 c >= 'a' && c <= 'f' ? c - 'a' + 10 :
571 for (int i = 0; i < input.size(); i += 2) {
572 int highBits = unhex(input[i]);
573 int lowBits = unhex(input[i + 1]);
574 if (highBits < 0 || lowBits < 0) {
577 output[j++] = (highBits << 4) + lowBits;
584 * Hex-dump at most 16 bytes starting at offset from a memory area of size
585 * bytes. Return the number of bytes actually dumped.
587 size_t hexDumpLine(const void* ptr, size_t offset, size_t size,
589 } // namespace detail
591 template <class OutIt>
592 void hexDump(const void* ptr, size_t size, OutIt out) {
595 while (offset < size) {
596 offset += detail::hexDumpLine(ptr, offset, size, line);
603 #endif /* FOLLY_STRING_INL_H_ */