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