2 * Copyright 2014 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 // @author Mark Rabkin (mrabkin@fb.com)
18 // @author Andrei Alexandrescu (andrei.alexandrescu@fb.com)
20 #ifndef FOLLY_RANGE_H_
21 #define FOLLY_RANGE_H_
23 #include <folly/Portability.h>
24 #include <folly/FBString.h>
26 #include <boost/operators.hpp>
28 #include <glog/logging.h>
32 #include <type_traits>
34 // libc++ doesn't provide this header, nor does msvc
35 #ifdef FOLLY_HAVE_BITS_CXXCONFIG_H
36 // This file appears in two locations: inside fbcode and in the
37 // libstdc++ source code (when embedding fbstring as std::string).
38 // To aid in this schizophrenic use, two macros are defined in
40 // _LIBSTDCXX_FBSTRING - Set inside libstdc++. This is useful to
41 // gate use inside fbcode v. libstdc++
42 #include <bits/c++config.h>
45 #include <folly/CpuId.h>
46 #include <folly/Traits.h>
47 #include <folly/Likely.h>
49 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
50 #pragma GCC diagnostic push
51 #pragma GCC diagnostic ignored "-Wshadow"
55 template <class T> class Range;
58 * Finds the first occurrence of needle in haystack. The algorithm is on
59 * average faster than O(haystack.size() * needle.size()) but not as fast
60 * as Boyer-Moore. On the upside, it does not do any upfront
61 * preprocessing and does not allocate memory.
63 template <class T, class Comp = std::equal_to<typename Range<T>::value_type>>
64 inline size_t qfind(const Range<T> & haystack,
65 const Range<T> & needle,
69 * Finds the first occurrence of needle in haystack. The result is the
70 * offset reported to the beginning of haystack, or string::npos if
71 * needle wasn't found.
74 size_t qfind(const Range<T> & haystack,
75 const typename Range<T>::value_type& needle);
78 * Finds the last occurrence of needle in haystack. The result is the
79 * offset reported to the beginning of haystack, or string::npos if
80 * needle wasn't found.
83 size_t rfind(const Range<T> & haystack,
84 const typename Range<T>::value_type& needle);
88 * Finds the first occurrence of any element of needle in
89 * haystack. The algorithm is O(haystack.size() * needle.size()).
92 inline size_t qfind_first_of(const Range<T> & haystack,
93 const Range<T> & needle);
96 * Small internal helper - returns the value just before an iterator.
101 * For random-access iterators, the value before is simply i[-1].
103 template <class Iter>
104 typename std::enable_if<
105 std::is_same<typename std::iterator_traits<Iter>::iterator_category,
106 std::random_access_iterator_tag>::value,
107 typename std::iterator_traits<Iter>::reference>::type
108 value_before(Iter i) {
113 * For all other iterators, we need to use the decrement operator.
115 template <class Iter>
116 typename std::enable_if<
117 !std::is_same<typename std::iterator_traits<Iter>::iterator_category,
118 std::random_access_iterator_tag>::value,
119 typename std::iterator_traits<Iter>::reference>::type
120 value_before(Iter i) {
124 } // namespace detail
127 * Range abstraction keeping a pair of iterators. We couldn't use
128 * boost's similar range abstraction because we need an API identical
129 * with the former StringPiece class, which is used by a lot of other
130 * code. This abstraction does fulfill the needs of boost's
131 * range-oriented algorithms though.
133 * (Keep memory lifetime in mind when using this class, since it
134 * doesn't manage the data it refers to - just like an iterator
137 template <class Iter>
138 class Range : private boost::totally_ordered<Range<Iter> > {
140 typedef std::size_t size_type;
141 typedef Iter iterator;
142 typedef Iter const_iterator;
143 typedef typename std::remove_reference<
144 typename std::iterator_traits<Iter>::reference>::type
146 typedef typename std::iterator_traits<Iter>::reference reference;
149 * For MutableStringPiece and MutableByteRange we define StringPiece
150 * and ByteRange as const_range_type (for everything else its just
151 * identity). We do that to enable operations such as find with
152 * args which are const.
154 typedef typename std::conditional<
155 std::is_same<Iter, char*>::value
156 || std::is_same<Iter, unsigned char*>::value,
157 Range<const value_type*>,
158 Range<Iter>>::type const_range_type;
160 typedef std::char_traits<typename std::remove_const<value_type>::type>
163 static const size_type npos;
165 // Works for all iterators
166 constexpr Range() : b_(), e_() {
170 // Works for all iterators
171 constexpr Range(Iter start, Iter end) : b_(start), e_(end) {
174 // Works only for random-access iterators
175 constexpr Range(Iter start, size_t size)
176 : b_(start), e_(start + size) { }
178 #if FOLLY_HAVE_CONSTEXPR_STRLEN
179 // Works only for Range<const char*>
180 constexpr /* implicit */ Range(Iter str)
181 : b_(str), e_(str + strlen(str)) {}
183 // Works only for Range<const char*>
184 /* implicit */ Range(Iter str)
185 : b_(str), e_(str + strlen(str)) {}
187 // Works only for Range<const char*>
188 /* implicit */ Range(const std::string& str)
189 : b_(str.data()), e_(b_ + str.size()) {}
191 // Works only for Range<const char*>
192 Range(const std::string& str, std::string::size_type startFrom) {
193 if (UNLIKELY(startFrom > str.size())) {
194 throw std::out_of_range("index out of range");
196 b_ = str.data() + startFrom;
197 e_ = str.data() + str.size();
199 // Works only for Range<const char*>
200 Range(const std::string& str,
201 std::string::size_type startFrom,
202 std::string::size_type size) {
203 if (UNLIKELY(startFrom > str.size())) {
204 throw std::out_of_range("index out of range");
206 b_ = str.data() + startFrom;
207 if (str.size() - startFrom < size) {
208 e_ = str.data() + str.size();
213 Range(const Range<Iter>& str,
216 if (UNLIKELY(startFrom > str.size())) {
217 throw std::out_of_range("index out of range");
219 b_ = str.b_ + startFrom;
220 if (str.size() - startFrom < size) {
226 // Works only for Range<const char*>
227 /* implicit */ Range(const fbstring& str)
228 : b_(str.data()), e_(b_ + str.size()) { }
229 // Works only for Range<const char*>
230 Range(const fbstring& str, fbstring::size_type startFrom) {
231 if (UNLIKELY(startFrom > str.size())) {
232 throw std::out_of_range("index out of range");
234 b_ = str.data() + startFrom;
235 e_ = str.data() + str.size();
237 // Works only for Range<const char*>
238 Range(const fbstring& str, fbstring::size_type startFrom,
239 fbstring::size_type size) {
240 if (UNLIKELY(startFrom > str.size())) {
241 throw std::out_of_range("index out of range");
243 b_ = str.data() + startFrom;
244 if (str.size() - startFrom < size) {
245 e_ = str.data() + str.size();
251 // Allow implicit conversion from Range<const char*> (aka StringPiece) to
252 // Range<const unsigned char*> (aka ByteRange), as they're both frequently
253 // used to represent ranges of bytes. Allow explicit conversion in the other
255 template <class OtherIter, typename std::enable_if<
256 (std::is_same<Iter, const unsigned char*>::value &&
257 (std::is_same<OtherIter, const char*>::value ||
258 std::is_same<OtherIter, char*>::value)), int>::type = 0>
259 /* implicit */ Range(const Range<OtherIter>& other)
260 : b_(reinterpret_cast<const unsigned char*>(other.begin())),
261 e_(reinterpret_cast<const unsigned char*>(other.end())) {
264 template <class OtherIter, typename std::enable_if<
265 (std::is_same<Iter, unsigned char*>::value &&
266 std::is_same<OtherIter, char*>::value), int>::type = 0>
267 /* implicit */ Range(const Range<OtherIter>& other)
268 : b_(reinterpret_cast<unsigned char*>(other.begin())),
269 e_(reinterpret_cast<unsigned char*>(other.end())) {
272 template <class OtherIter, typename std::enable_if<
273 (std::is_same<Iter, const char*>::value &&
274 (std::is_same<OtherIter, const unsigned char*>::value ||
275 std::is_same<OtherIter, unsigned char*>::value)), int>::type = 0>
276 explicit Range(const Range<OtherIter>& other)
277 : b_(reinterpret_cast<const char*>(other.begin())),
278 e_(reinterpret_cast<const char*>(other.end())) {
281 template <class OtherIter, typename std::enable_if<
282 (std::is_same<Iter, char*>::value &&
283 std::is_same<OtherIter, unsigned char*>::value), int>::type = 0>
284 explicit Range(const Range<OtherIter>& other)
285 : b_(reinterpret_cast<char*>(other.begin())),
286 e_(reinterpret_cast<char*>(other.end())) {
289 // Allow implicit conversion from Range<From> to Range<To> if From is
290 // implicitly convertible to To.
291 template <class OtherIter, typename std::enable_if<
292 (!std::is_same<Iter, OtherIter>::value &&
293 std::is_convertible<OtherIter, Iter>::value), int>::type = 0>
294 constexpr /* implicit */ Range(const Range<OtherIter>& other)
299 // Allow explicit conversion from Range<From> to Range<To> if From is
300 // explicitly convertible to To.
301 template <class OtherIter, typename std::enable_if<
302 (!std::is_same<Iter, OtherIter>::value &&
303 !std::is_convertible<OtherIter, Iter>::value &&
304 std::is_constructible<Iter, const OtherIter&>::value), int>::type = 0>
305 constexpr explicit Range(const Range<OtherIter>& other)
315 void assign(Iter start, Iter end) {
320 void reset(Iter start, size_type size) {
325 // Works only for Range<const char*>
326 void reset(const std::string& str) {
327 reset(str.data(), str.size());
330 size_type size() const {
334 size_type walk_size() const {
336 return std::distance(b_, e_);
338 bool empty() const { return b_ == e_; }
339 Iter data() const { return b_; }
340 Iter start() const { return b_; }
341 Iter begin() const { return b_; }
342 Iter end() const { return e_; }
343 Iter cbegin() const { return b_; }
344 Iter cend() const { return e_; }
345 value_type& front() {
351 return detail::value_before(e_);
353 const value_type& front() const {
357 const value_type& back() const {
359 return detail::value_before(e_);
361 // Works only for Range<const char*>
362 std::string str() const { return std::string(b_, size()); }
363 std::string toString() const { return str(); }
364 // Works only for Range<const char*>
365 fbstring fbstr() const { return fbstring(b_, size()); }
366 fbstring toFbstring() const { return fbstr(); }
368 const_range_type castToConst() const {
369 return const_range_type(*this);
372 // Works only for Range<const char*> (and Range<char*>)
373 int compare(const const_range_type& o) const {
374 const size_type tsize = this->size();
375 const size_type osize = o.size();
376 const size_type msize = std::min(tsize, osize);
377 int r = traits_type::compare(data(), o.data(), msize);
378 if (r == 0) r = tsize - osize;
382 value_type& operator[](size_t i) {
383 DCHECK_GT(size(), i);
387 const value_type& operator[](size_t i) const {
388 DCHECK_GT(size(), i);
392 value_type& at(size_t i) {
393 if (i >= size()) throw std::out_of_range("index out of range");
397 const value_type& at(size_t i) const {
398 if (i >= size()) throw std::out_of_range("index out of range");
402 // Works only for Range<const char*>
403 uint32_t hash() const {
404 // Taken from fbi/nstring.h:
405 // Quick and dirty bernstein hash...fine for short ascii strings
406 uint32_t hash = 5381;
407 for (size_t ix = 0; ix < size(); ix++) {
408 hash = ((hash << 5) + hash) + b_[ix];
413 void advance(size_type n) {
414 if (UNLIKELY(n > size())) {
415 throw std::out_of_range("index out of range");
420 void subtract(size_type n) {
421 if (UNLIKELY(n > size())) {
422 throw std::out_of_range("index out of range");
437 Range subpiece(size_type first,
438 size_type length = std::string::npos) const {
439 if (UNLIKELY(first > size())) {
440 throw std::out_of_range("index out of range");
442 return Range(b_ + first,
443 std::min<std::string::size_type>(length, size() - first));
446 // string work-alike functions
447 size_type find(const_range_type str) const {
448 return qfind(castToConst(), str);
451 size_type find(const_range_type str, size_t pos) const {
452 if (pos > size()) return std::string::npos;
453 size_t ret = qfind(castToConst().subpiece(pos), str);
454 return ret == npos ? ret : ret + pos;
457 size_type find(Iter s, size_t pos, size_t n) const {
458 if (pos > size()) return std::string::npos;
459 auto forFinding = castToConst();
461 pos ? forFinding.subpiece(pos) : forFinding, const_range_type(s, n));
462 return ret == npos ? ret : ret + pos;
465 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
466 size_type find(const Iter s) const {
467 return qfind(castToConst(), const_range_type(s));
470 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
471 size_type find(const Iter s, size_t pos) const {
472 if (pos > size()) return std::string::npos;
473 size_type ret = qfind(castToConst().subpiece(pos), const_range_type(s));
474 return ret == npos ? ret : ret + pos;
477 size_type find(value_type c) const {
478 return qfind(castToConst(), c);
481 size_type rfind(value_type c) const {
482 return folly::rfind(castToConst(), c);
485 size_type find(value_type c, size_t pos) const {
486 if (pos > size()) return std::string::npos;
487 size_type ret = qfind(castToConst().subpiece(pos), c);
488 return ret == npos ? ret : ret + pos;
491 size_type find_first_of(const_range_type needles) const {
492 return qfind_first_of(castToConst(), needles);
495 size_type find_first_of(const_range_type needles, size_t pos) const {
496 if (pos > size()) return std::string::npos;
497 size_type ret = qfind_first_of(castToConst().subpiece(pos), needles);
498 return ret == npos ? ret : ret + pos;
501 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
502 size_type find_first_of(Iter needles) const {
503 return find_first_of(const_range_type(needles));
506 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
507 size_type find_first_of(Iter needles, size_t pos) const {
508 return find_first_of(const_range_type(needles), pos);
511 size_type find_first_of(Iter needles, size_t pos, size_t n) const {
512 return find_first_of(const_range_type(needles, n), pos);
515 size_type find_first_of(value_type c) const {
519 size_type find_first_of(value_type c, size_t pos) const {
524 * Determine whether the range contains the given subrange or item.
526 * Note: Call find() directly if the index is needed.
528 bool contains(const const_range_type& other) const {
529 return find(other) != std::string::npos;
532 bool contains(const value_type& other) const {
533 return find(other) != std::string::npos;
536 void swap(Range& rhs) {
537 std::swap(b_, rhs.b_);
538 std::swap(e_, rhs.e_);
542 * Does this Range start with another range?
544 bool startsWith(const const_range_type& other) const {
545 return size() >= other.size()
546 && castToConst().subpiece(0, other.size()) == other;
548 bool startsWith(value_type c) const {
549 return !empty() && front() == c;
553 * Does this Range end with another range?
555 bool endsWith(const const_range_type& other) const {
556 return size() >= other.size()
557 && castToConst().subpiece(size() - other.size()) == other;
559 bool endsWith(value_type c) const {
560 return !empty() && back() == c;
564 * Remove the given prefix and return true if the range starts with the given
565 * prefix; return false otherwise.
567 bool removePrefix(const const_range_type& prefix) {
568 return startsWith(prefix) && (b_ += prefix.size(), true);
570 bool removePrefix(value_type prefix) {
571 return startsWith(prefix) && (++b_, true);
575 * Remove the given suffix and return true if the range ends with the given
576 * suffix; return false otherwise.
578 bool removeSuffix(const const_range_type& suffix) {
579 return endsWith(suffix) && (e_ -= suffix.size(), true);
581 bool removeSuffix(value_type suffix) {
582 return endsWith(suffix) && (--e_, true);
586 * Replaces the content of the range, starting at position 'pos', with
587 * contents of 'replacement'. Entire 'replacement' must fit into the
588 * range. Returns false if 'replacements' does not fit. Example use:
590 * char in[] = "buffer";
591 * auto msp = MutablesStringPiece(input);
592 * EXPECT_TRUE(msp.replaceAt(2, "tt"));
593 * EXPECT_EQ(msp, "butter");
595 * // not enough space
596 * EXPECT_FALSE(msp.replace(msp.size() - 1, "rr"));
597 * EXPECT_EQ(msp, "butter"); // unchanged
599 bool replaceAt(size_t pos, const_range_type replacement) {
600 if (size() < pos + replacement.size()) {
604 std::copy(replacement.begin(), replacement.end(), begin() + pos);
610 * Replaces all occurences of 'source' with 'dest'. Returns number
611 * of replacements made. Source and dest have to have the same
612 * length. Throws if the lengths are different. If 'source' is a
613 * pattern that is overlapping with itself, we perform sequential
614 * replacement: "aaaaaaa".replaceAll("aa", "ba") --> "bababaa"
618 * char in[] = "buffer";
619 * auto msp = MutablesStringPiece(input);
620 * EXPECT_EQ(msp.replaceAll("ff","tt"), 1);
621 * EXPECT_EQ(msp, "butter");
623 size_t replaceAll(const_range_type source, const_range_type dest) {
624 if (source.size() != dest.size()) {
625 throw std::invalid_argument(
626 "replacement must have the same size as source");
634 size_t num_replaced = 0;
635 size_type found = std::string::npos;
636 while ((found = find(source, pos)) != std::string::npos) {
637 replaceAt(found, dest);
638 pos += source.size();
646 * Splits this `Range` `[b, e)` in the position `i` dictated by the next
647 * occurence of `delimiter`.
649 * Returns a new `Range` `[b, i)` and adjusts this range to start right after
650 * the delimiter's position. This range will be empty if the delimiter is not
651 * found. If called on an empty `Range`, both this and the returned `Range`
656 * folly::StringPiece s("sample string for split_next");
657 * auto p = s.split_step(' ');
659 * // prints "string for split_next"
667 * void tokenize(StringPiece s, char delimiter) {
668 * while (!s.empty()) {
669 * cout << s.split_step(delimiter);
673 * @author: Marcelo Juchem <marcelo@fb.com>
675 Range split_step(value_type delimiter) {
676 auto i = std::find(b_, e_, delimiter);
679 b_ = i == e_ ? e_ : std::next(i);
684 Range split_step(Range delimiter) {
685 auto i = find(delimiter);
686 Range result(b_, i == std::string::npos ? size() : i);
688 b_ = result.end() == e_ ? e_ : std::next(result.end(), delimiter.size());
694 * Convenience method that calls `split_step()` and passes the result to a
695 * functor, returning whatever the functor does. Any additional arguments
696 * `args` passed to this function are perfectly forwarded to the functor.
698 * Say you have a functor with this signature:
700 * Foo fn(Range r) { }
702 * `split_step()`'s return type will be `Foo`. It works just like:
704 * auto result = fn(myRange.split_step(' '));
706 * A functor returning `void` is also supported.
710 * void do_some_parsing(folly::StringPiece s) {
711 * auto version = s.split_step(' ', [&](folly::StringPiece x) {
713 * throw std::invalid_argument("empty string");
715 * return std::strtoull(x.begin(), x.end(), 16);
722 * void parse(folly::StringPiece s) {
723 * s.split_step(' ', parse_field, bar, 10);
724 * s.split_step('\t', parse_field, baz, 20);
726 * auto const kludge = [](folly::StringPiece x, int &out, int def) {
730 * parse_field(x, out, def);
734 * s.split_step('\t', kludge, gaz);
735 * s.split_step(' ', kludge, foo);
744 * static parse_field(folly::StringPiece s, int &out, int def) {
746 * out = folly::to<int>(s);
747 * } catch (std::exception const &) {
753 * @author: Marcelo Juchem <marcelo@fb.com>
755 template <typename TProcess, typename... Args>
756 auto split_step(value_type delimiter, TProcess &&process, Args &&...args)
757 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
758 { return process(split_step(delimiter), std::forward<Args>(args)...); }
760 template <typename TProcess, typename... Args>
761 auto split_step(Range delimiter, TProcess &&process, Args &&...args)
762 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
763 { return process(split_step(delimiter), std::forward<Args>(args)...); }
769 template <class Iter>
770 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
773 void swap(Range<T>& lhs, Range<T>& rhs) {
778 * Create a range from two iterators, with type deduction.
780 template <class Iter>
781 Range<Iter> range(Iter first, Iter last) {
782 return Range<Iter>(first, last);
786 * Creates a range to reference the contents of a contiguous-storage container.
788 // Use pointers for types with '.data()' member
789 template <class Collection,
790 class T = typename std::remove_pointer<
791 decltype(std::declval<Collection>().data())>::type>
792 Range<T*> range(Collection&& v) {
793 return Range<T*>(v.data(), v.data() + v.size());
796 template <class T, size_t n>
797 Range<T*> range(T (&array)[n]) {
798 return Range<T*>(array, array + n);
801 typedef Range<const char*> StringPiece;
802 typedef Range<char*> MutableStringPiece;
803 typedef Range<const unsigned char*> ByteRange;
804 typedef Range<unsigned char*> MutableByteRange;
806 std::ostream& operator<<(std::ostream& os, const StringPiece& piece);
807 std::ostream& operator<<(std::ostream& os, const MutableStringPiece& piece);
810 * Templated comparison operators
814 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
815 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
819 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
820 return lhs.compare(rhs) < 0;
824 * Specializations of comparison operators for StringPiece
829 template <class A, class B>
830 struct ComparableAsStringPiece {
833 (std::is_convertible<A, StringPiece>::value
834 && std::is_same<B, StringPiece>::value)
836 (std::is_convertible<B, StringPiece>::value
837 && std::is_same<A, StringPiece>::value)
841 } // namespace detail
844 * operator== through conversion for Range<const char*>
846 template <class T, class U>
848 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
849 operator==(const T& lhs, const U& rhs) {
850 return StringPiece(lhs) == StringPiece(rhs);
854 * operator< through conversion for Range<const char*>
856 template <class T, class U>
858 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
859 operator<(const T& lhs, const U& rhs) {
860 return StringPiece(lhs) < StringPiece(rhs);
864 * operator> through conversion for Range<const char*>
866 template <class T, class U>
868 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
869 operator>(const T& lhs, const U& rhs) {
870 return StringPiece(lhs) > StringPiece(rhs);
874 * operator< through conversion for Range<const char*>
876 template <class T, class U>
878 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
879 operator<=(const T& lhs, const U& rhs) {
880 return StringPiece(lhs) <= StringPiece(rhs);
884 * operator> through conversion for Range<const char*>
886 template <class T, class U>
888 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
889 operator>=(const T& lhs, const U& rhs) {
890 return StringPiece(lhs) >= StringPiece(rhs);
893 struct StringPieceHash {
894 std::size_t operator()(const StringPiece& str) const {
895 return static_cast<std::size_t>(str.hash());
900 * Finds substrings faster than brute force by borrowing from Boyer-Moore
902 template <class T, class Comp>
903 size_t qfind(const Range<T>& haystack,
904 const Range<T>& needle,
906 // Don't use std::search, use a Boyer-Moore-like trick by comparing
907 // the last characters first
908 auto const nsize = needle.size();
909 if (haystack.size() < nsize) {
910 return std::string::npos;
912 if (!nsize) return 0;
913 auto const nsize_1 = nsize - 1;
914 auto const lastNeedle = needle[nsize_1];
916 // Boyer-Moore skip value for the last char in the needle. Zero is
917 // not a valid value; skip will be computed the first time it's
919 std::string::size_type skip = 0;
921 auto i = haystack.begin();
922 auto iEnd = haystack.end() - nsize_1;
925 // Boyer-Moore: match the last element in the needle
926 while (!eq(i[nsize_1], lastNeedle)) {
929 return std::string::npos;
932 // Here we know that the last char matches
933 // Continue in pedestrian mode
934 for (size_t j = 0; ; ) {
936 if (!eq(i[j], needle[j])) {
937 // Not found, we can skip
938 // Compute the skip value lazily
941 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
948 // Check if done searching
951 return i - haystack.begin();
955 return std::string::npos;
960 size_t qfind_first_byte_of_nosse(const StringPiece& haystack,
961 const StringPiece& needles);
963 #if FOLLY_HAVE_EMMINTRIN_H && __GNUC_PREREQ(4, 6)
964 size_t qfind_first_byte_of_sse42(const StringPiece& haystack,
965 const StringPiece& needles);
967 inline size_t qfind_first_byte_of(const StringPiece& haystack,
968 const StringPiece& needles) {
969 static auto const qfind_first_byte_of_fn =
970 folly::CpuId().sse42() ? qfind_first_byte_of_sse42
971 : qfind_first_byte_of_nosse;
972 return qfind_first_byte_of_fn(haystack, needles);
976 inline size_t qfind_first_byte_of(const StringPiece& haystack,
977 const StringPiece& needles) {
978 return qfind_first_byte_of_nosse(haystack, needles);
980 #endif // FOLLY_HAVE_EMMINTRIN_H
982 } // namespace detail
984 template <class T, class Comp>
985 size_t qfind_first_of(const Range<T> & haystack,
986 const Range<T> & needles,
988 auto ret = std::find_first_of(haystack.begin(), haystack.end(),
989 needles.begin(), needles.end(),
991 return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
994 struct AsciiCaseSensitive {
995 bool operator()(char lhs, char rhs) const {
1001 * Check if two ascii characters are case insensitive equal.
1002 * The difference between the lower/upper case characters are the 6-th bit.
1003 * We also check they are alpha chars, in case of xor = 32.
1005 struct AsciiCaseInsensitive {
1006 bool operator()(char lhs, char rhs) const {
1008 if (k == 0) return true;
1009 if (k != 32) return false;
1011 return (k >= 'a' && k <= 'z');
1015 extern const AsciiCaseSensitive asciiCaseSensitive;
1016 extern const AsciiCaseInsensitive asciiCaseInsensitive;
1019 size_t qfind(const Range<T>& haystack,
1020 const typename Range<T>::value_type& needle) {
1021 auto pos = std::find(haystack.begin(), haystack.end(), needle);
1022 return pos == haystack.end() ? std::string::npos : pos - haystack.data();
1026 size_t rfind(const Range<T>& haystack,
1027 const typename Range<T>::value_type& needle) {
1028 for (auto i = haystack.size(); i-- > 0; ) {
1029 if (haystack[i] == needle) {
1033 return std::string::npos;
1036 // specialization for StringPiece
1038 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
1039 auto pos = static_cast<const char*>(
1040 ::memchr(haystack.data(), needle, haystack.size()));
1041 return pos == nullptr ? std::string::npos : pos - haystack.data();
1044 #if FOLLY_HAVE_MEMRCHR
1046 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
1047 auto pos = static_cast<const char*>(
1048 ::memrchr(haystack.data(), needle, haystack.size()));
1049 return pos == nullptr ? std::string::npos : pos - haystack.data();
1053 // specialization for ByteRange
1055 inline size_t qfind(const Range<const unsigned char*>& haystack,
1056 const unsigned char& needle) {
1057 auto pos = static_cast<const unsigned char*>(
1058 ::memchr(haystack.data(), needle, haystack.size()));
1059 return pos == nullptr ? std::string::npos : pos - haystack.data();
1062 #if FOLLY_HAVE_MEMRCHR
1064 inline size_t rfind(const Range<const unsigned char*>& haystack,
1065 const unsigned char& needle) {
1066 auto pos = static_cast<const unsigned char*>(
1067 ::memrchr(haystack.data(), needle, haystack.size()));
1068 return pos == nullptr ? std::string::npos : pos - haystack.data();
1073 size_t qfind_first_of(const Range<T>& haystack,
1074 const Range<T>& needles) {
1075 return qfind_first_of(haystack, needles, asciiCaseSensitive);
1078 // specialization for StringPiece
1080 inline size_t qfind_first_of(const Range<const char*>& haystack,
1081 const Range<const char*>& needles) {
1082 return detail::qfind_first_byte_of(haystack, needles);
1085 // specialization for ByteRange
1087 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
1088 const Range<const unsigned char*>& needles) {
1089 return detail::qfind_first_byte_of(StringPiece(haystack),
1090 StringPiece(needles));
1092 } // !namespace folly
1094 #pragma GCC diagnostic pop
1096 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);
1098 #endif // FOLLY_RANGE_H_