+// Fast path to determine the longest prefix that can be left
+// unescaped in a string of sizeof(T) bytes packed in an integer of
+// type T.
+template <class T>
+size_t firstEscapableInWord(T s) {
+ static_assert(std::is_unsigned<T>::value, "Unsigned integer required");
+ static constexpr T kOnes = ~T() / 255; // 0x...0101
+ static constexpr T kMsbs = kOnes * 0x80; // 0x...8080
+
+ // Sets the MSB of bytes < b. Precondition: b < 128.
+ auto isLess = [](T w, uint8_t b) {
+ // A byte is < b iff subtracting b underflows, so we check that
+ // the MSB wasn't set before and it's set after the subtraction.
+ return (w - kOnes * b) & ~w & kMsbs;
+ };
+
+ auto isChar = [&](uint8_t c) {
+ // A byte is == c iff it is 0 if xored with c.
+ return isLess(s ^ (kOnes * c), 1);
+ };
+
+ // The following masks have the MSB set for each byte of the word
+ // that satisfies the corresponding condition.
+ auto isHigh = s & kMsbs; // >= 128
+ auto isLow = isLess(s, 0x20); // <= 0x1f
+ auto needsEscape = isHigh | isLow | isChar('\\') | isChar('"');
+
+ if (!needsEscape) {
+ return sizeof(T);
+ }
+
+ if (folly::kIsLittleEndian) {
+ return folly::findFirstSet(needsEscape) / 8 - 1;
+ } else {
+ return sizeof(T) - folly::findLastSet(needsEscape) / 8;
+ }
+}
+