2 * Copyright 2016 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.
21 #include <glog/logging.h>
22 #include <folly/Likely.h>
29 * The qfind_first_byte_of_* functions are declared here, before Range.h, so
30 * they cannot take StringPiece values. But they're there to operate on
31 * StringPiece values. Dependency cycles: fun.
33 * StringPieceLite is here to break that dependency cycle.
35 class StringPieceLite {
37 StringPieceLite(const char* b, const char* e) : b_(b), e_(e) {}
38 template <typename Range>
39 /* implicit */ StringPieceLite(const Range& r) :
40 StringPieceLite(r.data(), r.data() + r.size()) {}
41 const char* data() const { return b_; }
42 const char* begin() const { return b_; }
43 const char* end() const { return e_; }
44 size_t size() const { return e_ - b_; }
45 bool empty() const { return size() == 0; }
46 const char& operator[](size_t i) const { DCHECK_GT(size(), i); return b_[i]; }
47 template <typename Range>
48 explicit operator Range() const { return Range(begin(), end()); }
54 inline size_t qfind_first_byte_of_std(const StringPieceLite haystack,
55 const StringPieceLite needles) {
56 auto ret = std::find_first_of(haystack.begin(), haystack.end(),
57 needles.begin(), needles.end(),
58 [](char a, char b) { return a == b; });
59 return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
63 size_t qfind_first_byte_of_bitset(const StringPieceLite haystack,
64 const StringPieceLite needles);
66 size_t qfind_first_byte_of_byteset(const StringPieceLite haystack,
67 const StringPieceLite needles);
69 inline size_t qfind_first_byte_of_nosse(const StringPieceLite haystack,
70 const StringPieceLite needles) {
71 if (UNLIKELY(needles.empty() || haystack.empty())) {
72 return std::string::npos;
74 // The thresholds below were empirically determined by benchmarking.
75 // This is not an exact science since it depends on the CPU, the size of
76 // needles, and the size of haystack.
77 if ((needles.size() >= 4 && haystack.size() <= 10) ||
78 (needles.size() >= 16 && haystack.size() <= 64) ||
79 needles.size() >= 32) {
80 return qfind_first_byte_of_byteset(haystack, needles);
82 return qfind_first_byte_of_std(haystack, needles);