Performance Improvement for AsciiCaseInsensitive
[folly.git] / folly / Range.h
1 /*
2  * Copyright 2014 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 // @author Mark Rabkin (mrabkin@fb.com)
18 // @author Andrei Alexandrescu (andrei.alexandrescu@fb.com)
19
20 #ifndef FOLLY_RANGE_H_
21 #define FOLLY_RANGE_H_
22
23 #include "folly/Portability.h"
24 #include "folly/FBString.h"
25 #include <algorithm>
26 #include <boost/operators.hpp>
27 #include <cstring>
28 #include <glog/logging.h>
29 #include <iosfwd>
30 #include <stdexcept>
31 #include <string>
32 #include <type_traits>
33
34 // libc++ doesn't provide this header
35 #if !FOLLY_USE_LIBCPP
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
39 // c++config.h:
40 //   _LIBSTDCXX_FBSTRING - Set inside libstdc++.  This is useful to
41 //      gate use inside fbcode v. libstdc++
42 #include <bits/c++config.h>
43 #endif
44
45 #include "folly/CpuId.h"
46 #include "folly/Traits.h"
47 #include "folly/Likely.h"
48
49 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
50 #pragma GCC diagnostic push
51 #pragma GCC diagnostic ignored "-Wshadow"
52
53 namespace folly {
54
55 template <class T> class Range;
56
57 /**
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.
62  */
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,
66                     Comp eq = Comp());
67
68 /**
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.
72  */
73 template <class T>
74 size_t qfind(const Range<T> & haystack,
75              const typename Range<T>::value_type& needle);
76
77 /**
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.
81  */
82 template <class T>
83 size_t rfind(const Range<T> & haystack,
84              const typename Range<T>::value_type& needle);
85
86
87 /**
88  * Finds the first occurrence of any element of needle in
89  * haystack. The algorithm is O(haystack.size() * needle.size()).
90  */
91 template <class T>
92 inline size_t qfind_first_of(const Range<T> & haystack,
93                              const Range<T> & needle);
94
95 /**
96  * Small internal helper - returns the value just before an iterator.
97  */
98 namespace detail {
99
100 /**
101  * For random-access iterators, the value before is simply i[-1].
102  */
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) {
109   return i[-1];
110 }
111
112 /**
113  * For all other iterators, we need to use the decrement operator.
114  */
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) {
121   return *--i;
122 }
123
124 } // namespace detail
125
126 /**
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.
132  *
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
135  * wouldn't.)
136  */
137 template <class Iter>
138 class Range : private boost::totally_ordered<Range<Iter> > {
139 public:
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
145   value_type;
146   typedef typename std::iterator_traits<Iter>::reference reference;
147   typedef std::char_traits<typename std::remove_const<value_type>::type>
148     traits_type;
149
150   static const size_type npos;
151
152   // Works for all iterators
153   Range() : b_(), e_() {
154   }
155
156 public:
157   // Works for all iterators
158   Range(Iter start, Iter end) : b_(start), e_(end) {
159   }
160
161   // Works only for random-access iterators
162   Range(Iter start, size_t size)
163       : b_(start), e_(start + size) { }
164
165 #if FOLLY_HAVE_CONSTEXPR_STRLEN
166   // Works only for Range<const char*>
167   /* implicit */ constexpr Range(Iter str)
168       : b_(str), e_(str + strlen(str)) {}
169 #else
170   // Works only for Range<const char*>
171   /* implicit */ Range(Iter str)
172       : b_(str), e_(str + strlen(str)) {}
173 #endif
174   // Works only for Range<const char*>
175   /* implicit */ Range(const std::string& str)
176       : b_(str.data()), e_(b_ + str.size()) {}
177
178   // Works only for Range<const char*>
179   Range(const std::string& str, std::string::size_type startFrom) {
180     if (UNLIKELY(startFrom > str.size())) {
181       throw std::out_of_range("index out of range");
182     }
183     b_ = str.data() + startFrom;
184     e_ = str.data() + str.size();
185   }
186   // Works only for Range<const char*>
187   Range(const std::string& str,
188         std::string::size_type startFrom,
189         std::string::size_type size) {
190     if (UNLIKELY(startFrom > str.size())) {
191       throw std::out_of_range("index out of range");
192     }
193     b_ = str.data() + startFrom;
194     if (str.size() - startFrom < size) {
195       e_ = str.data() + str.size();
196     } else {
197       e_ = b_ + size;
198     }
199   }
200   Range(const Range<Iter>& str,
201         size_t startFrom,
202         size_t size) {
203     if (UNLIKELY(startFrom > str.size())) {
204       throw std::out_of_range("index out of range");
205     }
206     b_ = str.b_ + startFrom;
207     if (str.size() - startFrom < size) {
208       e_ = str.e_;
209     } else {
210       e_ = b_ + size;
211     }
212   }
213   // Works only for Range<const char*>
214   /* implicit */ Range(const fbstring& str)
215     : b_(str.data()), e_(b_ + str.size()) { }
216   // Works only for Range<const char*>
217   Range(const fbstring& str, fbstring::size_type startFrom) {
218     if (UNLIKELY(startFrom > str.size())) {
219       throw std::out_of_range("index out of range");
220     }
221     b_ = str.data() + startFrom;
222     e_ = str.data() + str.size();
223   }
224   // Works only for Range<const char*>
225   Range(const fbstring& str, fbstring::size_type startFrom,
226         fbstring::size_type size) {
227     if (UNLIKELY(startFrom > str.size())) {
228       throw std::out_of_range("index out of range");
229     }
230     b_ = str.data() + startFrom;
231     if (str.size() - startFrom < size) {
232       e_ = str.data() + str.size();
233     } else {
234       e_ = b_ + size;
235     }
236   }
237
238   // Allow implicit conversion from Range<const char*> (aka StringPiece) to
239   // Range<const unsigned char*> (aka ByteRange), as they're both frequently
240   // used to represent ranges of bytes.  Allow explicit conversion in the other
241   // direction.
242   template <class OtherIter, typename std::enable_if<
243       (std::is_same<Iter, const unsigned char*>::value &&
244        (std::is_same<OtherIter, const char*>::value ||
245         std::is_same<OtherIter, char*>::value)), int>::type = 0>
246   /* implicit */ Range(const Range<OtherIter>& other)
247     : b_(reinterpret_cast<const unsigned char*>(other.begin())),
248       e_(reinterpret_cast<const unsigned char*>(other.end())) {
249   }
250
251   template <class OtherIter, typename std::enable_if<
252       (std::is_same<Iter, unsigned char*>::value &&
253        std::is_same<OtherIter, char*>::value), int>::type = 0>
254   /* implicit */ Range(const Range<OtherIter>& other)
255     : b_(reinterpret_cast<unsigned char*>(other.begin())),
256       e_(reinterpret_cast<unsigned char*>(other.end())) {
257   }
258
259   template <class OtherIter, typename std::enable_if<
260       (std::is_same<Iter, const char*>::value &&
261        (std::is_same<OtherIter, const unsigned char*>::value ||
262         std::is_same<OtherIter, unsigned char*>::value)), int>::type = 0>
263   explicit Range(const Range<OtherIter>& other)
264     : b_(reinterpret_cast<const char*>(other.begin())),
265       e_(reinterpret_cast<const char*>(other.end())) {
266   }
267
268   template <class OtherIter, typename std::enable_if<
269       (std::is_same<Iter, char*>::value &&
270        std::is_same<OtherIter, unsigned char*>::value), int>::type = 0>
271   explicit Range(const Range<OtherIter>& other)
272     : b_(reinterpret_cast<char*>(other.begin())),
273       e_(reinterpret_cast<char*>(other.end())) {
274   }
275
276   // Allow implicit conversion from Range<From> to Range<To> if From is
277   // implicitly convertible to To.
278   template <class OtherIter, typename std::enable_if<
279      (!std::is_same<Iter, OtherIter>::value &&
280       std::is_convertible<OtherIter, Iter>::value), int>::type = 0>
281   /* implicit */ Range(const Range<OtherIter>& other)
282     : b_(other.begin()),
283       e_(other.end()) {
284   }
285
286   // Allow explicit conversion from Range<From> to Range<To> if From is
287   // explicitly convertible to To.
288   template <class OtherIter, typename std::enable_if<
289     (!std::is_same<Iter, OtherIter>::value &&
290      !std::is_convertible<OtherIter, Iter>::value &&
291      std::is_constructible<Iter, const OtherIter&>::value), int>::type = 0>
292   explicit Range(const Range<OtherIter>& other)
293     : b_(other.begin()),
294       e_(other.end()) {
295   }
296
297   void clear() {
298     b_ = Iter();
299     e_ = Iter();
300   }
301
302   void assign(Iter start, Iter end) {
303     b_ = start;
304     e_ = end;
305   }
306
307   void reset(Iter start, size_type size) {
308     b_ = start;
309     e_ = start + size;
310   }
311
312   // Works only for Range<const char*>
313   void reset(const std::string& str) {
314     reset(str.data(), str.size());
315   }
316
317   size_type size() const {
318     assert(b_ <= e_);
319     return e_ - b_;
320   }
321   size_type walk_size() const {
322     assert(b_ <= e_);
323     return std::distance(b_, e_);
324   }
325   bool empty() const { return b_ == e_; }
326   Iter data() const { return b_; }
327   Iter start() const { return b_; }
328   Iter begin() const { return b_; }
329   Iter end() const { return e_; }
330   Iter cbegin() const { return b_; }
331   Iter cend() const { return e_; }
332   value_type& front() {
333     assert(b_ < e_);
334     return *b_;
335   }
336   value_type& back() {
337     assert(b_ < e_);
338     return detail::value_before(e_);
339   }
340   const value_type& front() const {
341     assert(b_ < e_);
342     return *b_;
343   }
344   const value_type& back() const {
345     assert(b_ < e_);
346     return detail::value_before(e_);
347   }
348   // Works only for Range<const char*>
349   std::string str() const { return std::string(b_, size()); }
350   std::string toString() const { return str(); }
351   // Works only for Range<const char*>
352   fbstring fbstr() const { return fbstring(b_, size()); }
353   fbstring toFbstring() const { return fbstr(); }
354
355   // Works only for Range<const char*>
356   int compare(const Range& o) const {
357     const size_type tsize = this->size();
358     const size_type osize = o.size();
359     const size_type msize = std::min(tsize, osize);
360     int r = traits_type::compare(data(), o.data(), msize);
361     if (r == 0) r = tsize - osize;
362     return r;
363   }
364
365   value_type& operator[](size_t i) {
366     DCHECK_GT(size(), i);
367     return b_[i];
368   }
369
370   const value_type& operator[](size_t i) const {
371     DCHECK_GT(size(), i);
372     return b_[i];
373   }
374
375   value_type& at(size_t i) {
376     if (i >= size()) throw std::out_of_range("index out of range");
377     return b_[i];
378   }
379
380   const value_type& at(size_t i) const {
381     if (i >= size()) throw std::out_of_range("index out of range");
382     return b_[i];
383   }
384
385   // Works only for Range<const char*>
386   uint32_t hash() const {
387     // Taken from fbi/nstring.h:
388     //    Quick and dirty bernstein hash...fine for short ascii strings
389     uint32_t hash = 5381;
390     for (size_t ix = 0; ix < size(); ix++) {
391       hash = ((hash << 5) + hash) + b_[ix];
392     }
393     return hash;
394   }
395
396   void advance(size_type n) {
397     if (UNLIKELY(n > size())) {
398       throw std::out_of_range("index out of range");
399     }
400     b_ += n;
401   }
402
403   void subtract(size_type n) {
404     if (UNLIKELY(n > size())) {
405       throw std::out_of_range("index out of range");
406     }
407     e_ -= n;
408   }
409
410   void pop_front() {
411     assert(b_ < e_);
412     ++b_;
413   }
414
415   void pop_back() {
416     assert(b_ < e_);
417     --e_;
418   }
419
420   Range subpiece(size_type first,
421                  size_type length = std::string::npos) const {
422     if (UNLIKELY(first > size())) {
423       throw std::out_of_range("index out of range");
424     }
425     return Range(b_ + first,
426                  std::min<std::string::size_type>(length, size() - first));
427   }
428
429   // string work-alike functions
430   size_type find(Range str) const {
431     return qfind(*this, str);
432   }
433
434   size_type find(Range str, size_t pos) const {
435     if (pos > size()) return std::string::npos;
436     size_t ret = qfind(subpiece(pos), str);
437     return ret == npos ? ret : ret + pos;
438   }
439
440   size_type find(Iter s, size_t pos, size_t n) const {
441     if (pos > size()) return std::string::npos;
442     size_t ret = qfind(pos ? subpiece(pos) : *this, Range(s, n));
443     return ret == npos ? ret : ret + pos;
444   }
445
446   // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
447   size_type find(const Iter s) const {
448     return qfind(*this, Range(s));
449   }
450
451   // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
452   size_type find(const Iter s, size_t pos) const {
453     if (pos > size()) return std::string::npos;
454     size_type ret = qfind(subpiece(pos), Range(s));
455     return ret == npos ? ret : ret + pos;
456   }
457
458   size_type find(value_type c) const {
459     return qfind(*this, c);
460   }
461
462   size_type rfind(value_type c) const {
463     return folly::rfind(*this, c);
464   }
465
466   size_type find(value_type c, size_t pos) const {
467     if (pos > size()) return std::string::npos;
468     size_type ret = qfind(subpiece(pos), c);
469     return ret == npos ? ret : ret + pos;
470   }
471
472   size_type find_first_of(Range needles) const {
473     return qfind_first_of(*this, needles);
474   }
475
476   size_type find_first_of(Range needles, size_t pos) const {
477     if (pos > size()) return std::string::npos;
478     size_type ret = qfind_first_of(subpiece(pos), needles);
479     return ret == npos ? ret : ret + pos;
480   }
481
482   // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
483   size_type find_first_of(Iter needles) const {
484     return find_first_of(Range(needles));
485   }
486
487   // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
488   size_type find_first_of(Iter needles, size_t pos) const {
489     return find_first_of(Range(needles), pos);
490   }
491
492   size_type find_first_of(Iter needles, size_t pos, size_t n) const {
493     return find_first_of(Range(needles, n), pos);
494   }
495
496   size_type find_first_of(value_type c) const {
497     return find(c);
498   }
499
500   size_type find_first_of(value_type c, size_t pos) const {
501     return find(c, pos);
502   }
503
504   void swap(Range& rhs) {
505     std::swap(b_, rhs.b_);
506     std::swap(e_, rhs.e_);
507   }
508
509   /**
510    * Does this Range start with another range?
511    */
512   bool startsWith(const Range& other) const {
513     return size() >= other.size() && subpiece(0, other.size()) == other;
514   }
515   bool startsWith(value_type c) const {
516     return !empty() && front() == c;
517   }
518
519   /**
520    * Does this Range end with another range?
521    */
522   bool endsWith(const Range& other) const {
523     return size() >= other.size() && subpiece(size() - other.size()) == other;
524   }
525   bool endsWith(value_type c) const {
526     return !empty() && back() == c;
527   }
528
529   /**
530    * Remove the given prefix and return true if the range starts with the given
531    * prefix; return false otherwise.
532    */
533   bool removePrefix(const Range& prefix) {
534     return startsWith(prefix) && (b_ += prefix.size(), true);
535   }
536   bool removePrefix(value_type prefix) {
537     return startsWith(prefix) && (++b_, true);
538   }
539
540   /**
541    * Remove the given suffix and return true if the range ends with the given
542    * suffix; return false otherwise.
543    */
544   bool removeSuffix(const Range& suffix) {
545     return endsWith(suffix) && (e_ -= suffix.size(), true);
546   }
547   bool removeSuffix(value_type suffix) {
548     return endsWith(suffix) && (--e_, true);
549   }
550
551   /**
552    * Splits this `Range` `[b, e)` in the position `i` dictated by the next
553    * occurence of `delimiter`.
554    *
555    * Returns a new `Range` `[b, i)` and adjusts this range to start right after
556    * the delimiter's position. This range will be empty if the delimiter is not
557    * found. If called on an empty `Range`, both this and the returned `Range`
558    * will be empty.
559    *
560    * Example:
561    *
562    *  folly::StringPiece s("sample string for split_next");
563    *  auto p = s.split_step(' ');
564    *
565    *  // prints "sample"
566    *  cout << s << endl;
567    *
568    *  // prints "string for split_next"
569    *  cout << p << endl;
570    *
571    * Example 2:
572    *
573    *  void tokenize(StringPiece s, char delimiter) {
574    *    while (!s.empty()) {
575    *      cout << s.split_step(delimiter);
576    *    }
577    *  }
578    *
579    * @author: Marcelo Juchem <marcelo@fb.com>
580    */
581   Range split_step(value_type delimiter) {
582     auto i = std::find(b_, e_, delimiter);
583     Range result(b_, i);
584
585     b_ = i == e_ ? e_ : std::next(i);
586
587     return result;
588   }
589
590   Range split_step(Range delimiter) {
591     auto i = find(delimiter);
592     Range result(b_, i == std::string::npos ? size() : i);
593
594     b_ = result.end() == e_ ? e_ : std::next(result.end(), delimiter.size());
595
596     return result;
597   }
598
599   /**
600    * Convenience method that calls `split_step()` and passes the result to a
601    * functor, returning whatever the functor does.
602    *
603    * Say you have a functor with this signature:
604    *
605    *  Foo fn(Range r) { }
606    *
607    * `split_step()`'s return type will be `Foo`. It works just like:
608    *
609    *  auto result = fn(myRange.split_step(' '));
610    *
611    * A functor returning `void` is also supported.
612    *
613    * Example:
614    *
615    *  void do_some_parsing(folly::StringPiece s) {
616    *    auto version = s.split_step(' ', [&](folly::StringPiece x) {
617    *      if (x.empty()) {
618    *        throw std::invalid_argument("empty string");
619    *      }
620    *      return std::strtoull(x.begin(), x.end(), 16);
621    *    });
622    *
623    *    // ...
624    *  }
625    *
626    * @author: Marcelo Juchem <marcelo@fb.com>
627    */
628   template <typename TProcess>
629   auto split_step(value_type delimiter, TProcess &&process)
630     -> decltype(process(std::declval<Range>()))
631   { return process(split_step(delimiter)); }
632
633   template <typename TProcess>
634   auto split_step(Range delimiter, TProcess &&process)
635     -> decltype(process(std::declval<Range>()))
636   { return process(split_step(delimiter)); }
637
638 private:
639   Iter b_, e_;
640 };
641
642 template <class Iter>
643 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
644
645 template <class T>
646 void swap(Range<T>& lhs, Range<T>& rhs) {
647   lhs.swap(rhs);
648 }
649
650 /**
651  * Create a range from two iterators, with type deduction.
652  */
653 template <class Iter>
654 Range<Iter> range(Iter first, Iter last) {
655   return Range<Iter>(first, last);
656 }
657
658 /*
659  * Creates a range to reference the contents of a contiguous-storage container.
660  */
661 // Use pointers for types with '.data()' member
662 template <class Collection,
663           class T = typename std::remove_pointer<
664               decltype(std::declval<Collection>().data())>::type>
665 Range<T*> range(Collection&& v) {
666   return Range<T*>(v.data(), v.data() + v.size());
667 }
668
669 template <class T, size_t n>
670 Range<T*> range(T (&array)[n]) {
671   return Range<T*>(array, array + n);
672 }
673
674 typedef Range<const char*> StringPiece;
675 typedef Range<char*> MutableStringPiece;
676 typedef Range<const unsigned char*> ByteRange;
677 typedef Range<unsigned char*> MutableByteRange;
678
679 std::ostream& operator<<(std::ostream& os, const StringPiece& piece);
680
681 /**
682  * Templated comparison operators
683  */
684
685 template <class T>
686 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
687   return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
688 }
689
690 template <class T>
691 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
692   return lhs.compare(rhs) < 0;
693 }
694
695 /**
696  * Specializations of comparison operators for StringPiece
697  */
698
699 namespace detail {
700
701 template <class A, class B>
702 struct ComparableAsStringPiece {
703   enum {
704     value =
705     (std::is_convertible<A, StringPiece>::value
706      && std::is_same<B, StringPiece>::value)
707     ||
708     (std::is_convertible<B, StringPiece>::value
709      && std::is_same<A, StringPiece>::value)
710   };
711 };
712
713 } // namespace detail
714
715 /**
716  * operator== through conversion for Range<const char*>
717  */
718 template <class T, class U>
719 typename
720 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
721 operator==(const T& lhs, const U& rhs) {
722   return StringPiece(lhs) == StringPiece(rhs);
723 }
724
725 /**
726  * operator< through conversion for Range<const char*>
727  */
728 template <class T, class U>
729 typename
730 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
731 operator<(const T& lhs, const U& rhs) {
732   return StringPiece(lhs) < StringPiece(rhs);
733 }
734
735 /**
736  * operator> through conversion for Range<const char*>
737  */
738 template <class T, class U>
739 typename
740 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
741 operator>(const T& lhs, const U& rhs) {
742   return StringPiece(lhs) > StringPiece(rhs);
743 }
744
745 /**
746  * operator< through conversion for Range<const char*>
747  */
748 template <class T, class U>
749 typename
750 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
751 operator<=(const T& lhs, const U& rhs) {
752   return StringPiece(lhs) <= StringPiece(rhs);
753 }
754
755 /**
756  * operator> through conversion for Range<const char*>
757  */
758 template <class T, class U>
759 typename
760 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
761 operator>=(const T& lhs, const U& rhs) {
762   return StringPiece(lhs) >= StringPiece(rhs);
763 }
764
765 struct StringPieceHash {
766   std::size_t operator()(const StringPiece& str) const {
767     return static_cast<std::size_t>(str.hash());
768   }
769 };
770
771 /**
772  * Finds substrings faster than brute force by borrowing from Boyer-Moore
773  */
774 template <class T, class Comp>
775 size_t qfind(const Range<T>& haystack,
776              const Range<T>& needle,
777              Comp eq) {
778   // Don't use std::search, use a Boyer-Moore-like trick by comparing
779   // the last characters first
780   auto const nsize = needle.size();
781   if (haystack.size() < nsize) {
782     return std::string::npos;
783   }
784   if (!nsize) return 0;
785   auto const nsize_1 = nsize - 1;
786   auto const lastNeedle = needle[nsize_1];
787
788   // Boyer-Moore skip value for the last char in the needle. Zero is
789   // not a valid value; skip will be computed the first time it's
790   // needed.
791   std::string::size_type skip = 0;
792
793   auto i = haystack.begin();
794   auto iEnd = haystack.end() - nsize_1;
795
796   while (i < iEnd) {
797     // Boyer-Moore: match the last element in the needle
798     while (!eq(i[nsize_1], lastNeedle)) {
799       if (++i == iEnd) {
800         // not found
801         return std::string::npos;
802       }
803     }
804     // Here we know that the last char matches
805     // Continue in pedestrian mode
806     for (size_t j = 0; ; ) {
807       assert(j < nsize);
808       if (!eq(i[j], needle[j])) {
809         // Not found, we can skip
810         // Compute the skip value lazily
811         if (skip == 0) {
812           skip = 1;
813           while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
814             ++skip;
815           }
816         }
817         i += skip;
818         break;
819       }
820       // Check if done searching
821       if (++j == nsize) {
822         // Yay
823         return i - haystack.begin();
824       }
825     }
826   }
827   return std::string::npos;
828 }
829
830 namespace detail {
831
832 size_t qfind_first_byte_of_nosse(const StringPiece& haystack,
833                                  const StringPiece& needles);
834
835 #if FOLLY_HAVE_EMMINTRIN_H && __GNUC_PREREQ(4, 6)
836 size_t qfind_first_byte_of_sse42(const StringPiece& haystack,
837                                  const StringPiece& needles);
838
839 inline size_t qfind_first_byte_of(const StringPiece& haystack,
840                                   const StringPiece& needles) {
841   static auto const qfind_first_byte_of_fn =
842     folly::CpuId().sse42() ? qfind_first_byte_of_sse42
843                            : qfind_first_byte_of_nosse;
844   return qfind_first_byte_of_fn(haystack, needles);
845 }
846
847 #else
848 inline size_t qfind_first_byte_of(const StringPiece& haystack,
849                                   const StringPiece& needles) {
850   return qfind_first_byte_of_nosse(haystack, needles);
851 }
852 #endif // FOLLY_HAVE_EMMINTRIN_H
853
854 } // namespace detail
855
856 template <class T, class Comp>
857 size_t qfind_first_of(const Range<T> & haystack,
858                       const Range<T> & needles,
859                       Comp eq) {
860   auto ret = std::find_first_of(haystack.begin(), haystack.end(),
861                                 needles.begin(), needles.end(),
862                                 eq);
863   return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
864 }
865
866 struct AsciiCaseSensitive {
867   bool operator()(char lhs, char rhs) const {
868     return lhs == rhs;
869   }
870 };
871
872 /**
873  * Check if two ascii characters are case insensitive equal.
874  * The difference between the lower/upper case characters are the 6-th bit.
875  * We also check they are alpha chars, in case of xor = 32.
876  */
877 struct AsciiCaseInsensitive {
878   bool operator()(char lhs, char rhs) const {
879     char k = lhs ^ rhs;
880     if (k == 0) return true;
881     if (k != 32) return false;
882     k = lhs | rhs;
883     return (k >= 'a' && k <= 'z');
884   }
885 };
886
887 extern const AsciiCaseSensitive asciiCaseSensitive;
888 extern const AsciiCaseInsensitive asciiCaseInsensitive;
889
890 template <class T>
891 size_t qfind(const Range<T>& haystack,
892              const typename Range<T>::value_type& needle) {
893   auto pos = std::find(haystack.begin(), haystack.end(), needle);
894   return pos == haystack.end() ? std::string::npos : pos - haystack.data();
895 }
896
897 template <class T>
898 size_t rfind(const Range<T>& haystack,
899              const typename Range<T>::value_type& needle) {
900   for (auto i = haystack.size(); i-- > 0; ) {
901     if (haystack[i] == needle) {
902       return i;
903     }
904   }
905   return std::string::npos;
906 }
907
908 // specialization for StringPiece
909 template <>
910 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
911   auto pos = static_cast<const char*>(
912     ::memchr(haystack.data(), needle, haystack.size()));
913   return pos == nullptr ? std::string::npos : pos - haystack.data();
914 }
915
916 #if FOLLY_HAVE_MEMRCHR
917 template <>
918 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
919   auto pos = static_cast<const char*>(
920     ::memrchr(haystack.data(), needle, haystack.size()));
921   return pos == nullptr ? std::string::npos : pos - haystack.data();
922 }
923 #endif
924
925 // specialization for ByteRange
926 template <>
927 inline size_t qfind(const Range<const unsigned char*>& haystack,
928                     const unsigned char& needle) {
929   auto pos = static_cast<const unsigned char*>(
930     ::memchr(haystack.data(), needle, haystack.size()));
931   return pos == nullptr ? std::string::npos : pos - haystack.data();
932 }
933
934 #if FOLLY_HAVE_MEMRCHR
935 template <>
936 inline size_t rfind(const Range<const unsigned char*>& haystack,
937                     const unsigned char& needle) {
938   auto pos = static_cast<const unsigned char*>(
939     ::memrchr(haystack.data(), needle, haystack.size()));
940   return pos == nullptr ? std::string::npos : pos - haystack.data();
941 }
942 #endif
943
944 template <class T>
945 size_t qfind_first_of(const Range<T>& haystack,
946                       const Range<T>& needles) {
947   return qfind_first_of(haystack, needles, asciiCaseSensitive);
948 }
949
950 // specialization for StringPiece
951 template <>
952 inline size_t qfind_first_of(const Range<const char*>& haystack,
953                              const Range<const char*>& needles) {
954   return detail::qfind_first_byte_of(haystack, needles);
955 }
956
957 // specialization for ByteRange
958 template <>
959 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
960                              const Range<const unsigned char*>& needles) {
961   return detail::qfind_first_byte_of(StringPiece(haystack),
962                                      StringPiece(needles));
963 }
964 }  // !namespace folly
965
966 #pragma GCC diagnostic pop
967
968 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);
969
970 #endif // FOLLY_RANGE_H_