fixing split_step documentation
[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, 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
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   /**
505    * Determine whether the range contains the given subrange or item.
506    *
507    * Note: Call find() directly if the index is needed.
508    */
509   bool contains(const Range& other) const {
510     return find(other) != std::string::npos;
511   }
512
513   bool contains(const value_type& other) const {
514     return find(other) != std::string::npos;
515   }
516
517   void swap(Range& rhs) {
518     std::swap(b_, rhs.b_);
519     std::swap(e_, rhs.e_);
520   }
521
522   /**
523    * Does this Range start with another range?
524    */
525   bool startsWith(const Range& other) const {
526     return size() >= other.size() && subpiece(0, other.size()) == other;
527   }
528   bool startsWith(value_type c) const {
529     return !empty() && front() == c;
530   }
531
532   /**
533    * Does this Range end with another range?
534    */
535   bool endsWith(const Range& other) const {
536     return size() >= other.size() && subpiece(size() - other.size()) == other;
537   }
538   bool endsWith(value_type c) const {
539     return !empty() && back() == c;
540   }
541
542   /**
543    * Remove the given prefix and return true if the range starts with the given
544    * prefix; return false otherwise.
545    */
546   bool removePrefix(const Range& prefix) {
547     return startsWith(prefix) && (b_ += prefix.size(), true);
548   }
549   bool removePrefix(value_type prefix) {
550     return startsWith(prefix) && (++b_, true);
551   }
552
553   /**
554    * Remove the given suffix and return true if the range ends with the given
555    * suffix; return false otherwise.
556    */
557   bool removeSuffix(const Range& suffix) {
558     return endsWith(suffix) && (e_ -= suffix.size(), true);
559   }
560   bool removeSuffix(value_type suffix) {
561     return endsWith(suffix) && (--e_, true);
562   }
563
564   /**
565    * Splits this `Range` `[b, e)` in the position `i` dictated by the next
566    * occurence of `delimiter`.
567    *
568    * Returns a new `Range` `[b, i)` and adjusts this range to start right after
569    * the delimiter's position. This range will be empty if the delimiter is not
570    * found. If called on an empty `Range`, both this and the returned `Range`
571    * will be empty.
572    *
573    * Example:
574    *
575    *  folly::StringPiece s("sample string for split_next");
576    *  auto p = s.split_step(' ');
577    *
578    *  // prints "string for split_next"
579    *  cout << s << endl;
580    *
581    *  // prints "sample"
582    *  cout << p << endl;
583    *
584    * Example 2:
585    *
586    *  void tokenize(StringPiece s, char delimiter) {
587    *    while (!s.empty()) {
588    *      cout << s.split_step(delimiter);
589    *    }
590    *  }
591    *
592    * @author: Marcelo Juchem <marcelo@fb.com>
593    */
594   Range split_step(value_type delimiter) {
595     auto i = std::find(b_, e_, delimiter);
596     Range result(b_, i);
597
598     b_ = i == e_ ? e_ : std::next(i);
599
600     return result;
601   }
602
603   Range split_step(Range delimiter) {
604     auto i = find(delimiter);
605     Range result(b_, i == std::string::npos ? size() : i);
606
607     b_ = result.end() == e_ ? e_ : std::next(result.end(), delimiter.size());
608
609     return result;
610   }
611
612   /**
613    * Convenience method that calls `split_step()` and passes the result to a
614    * functor, returning whatever the functor does.
615    *
616    * Say you have a functor with this signature:
617    *
618    *  Foo fn(Range r) { }
619    *
620    * `split_step()`'s return type will be `Foo`. It works just like:
621    *
622    *  auto result = fn(myRange.split_step(' '));
623    *
624    * A functor returning `void` is also supported.
625    *
626    * Example:
627    *
628    *  void do_some_parsing(folly::StringPiece s) {
629    *    auto version = s.split_step(' ', [&](folly::StringPiece x) {
630    *      if (x.empty()) {
631    *        throw std::invalid_argument("empty string");
632    *      }
633    *      return std::strtoull(x.begin(), x.end(), 16);
634    *    });
635    *
636    *    // ...
637    *  }
638    *
639    * @author: Marcelo Juchem <marcelo@fb.com>
640    */
641   template <typename TProcess>
642   auto split_step(value_type delimiter, TProcess &&process)
643     -> decltype(process(std::declval<Range>()))
644   { return process(split_step(delimiter)); }
645
646   template <typename TProcess>
647   auto split_step(Range delimiter, TProcess &&process)
648     -> decltype(process(std::declval<Range>()))
649   { return process(split_step(delimiter)); }
650
651 private:
652   Iter b_, e_;
653 };
654
655 template <class Iter>
656 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
657
658 template <class T>
659 void swap(Range<T>& lhs, Range<T>& rhs) {
660   lhs.swap(rhs);
661 }
662
663 /**
664  * Create a range from two iterators, with type deduction.
665  */
666 template <class Iter>
667 Range<Iter> range(Iter first, Iter last) {
668   return Range<Iter>(first, last);
669 }
670
671 /*
672  * Creates a range to reference the contents of a contiguous-storage container.
673  */
674 // Use pointers for types with '.data()' member
675 template <class Collection,
676           class T = typename std::remove_pointer<
677               decltype(std::declval<Collection>().data())>::type>
678 Range<T*> range(Collection&& v) {
679   return Range<T*>(v.data(), v.data() + v.size());
680 }
681
682 template <class T, size_t n>
683 Range<T*> range(T (&array)[n]) {
684   return Range<T*>(array, array + n);
685 }
686
687 typedef Range<const char*> StringPiece;
688 typedef Range<char*> MutableStringPiece;
689 typedef Range<const unsigned char*> ByteRange;
690 typedef Range<unsigned char*> MutableByteRange;
691
692 std::ostream& operator<<(std::ostream& os, const StringPiece& piece);
693
694 /**
695  * Templated comparison operators
696  */
697
698 template <class T>
699 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
700   return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
701 }
702
703 template <class T>
704 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
705   return lhs.compare(rhs) < 0;
706 }
707
708 /**
709  * Specializations of comparison operators for StringPiece
710  */
711
712 namespace detail {
713
714 template <class A, class B>
715 struct ComparableAsStringPiece {
716   enum {
717     value =
718     (std::is_convertible<A, StringPiece>::value
719      && std::is_same<B, StringPiece>::value)
720     ||
721     (std::is_convertible<B, StringPiece>::value
722      && std::is_same<A, StringPiece>::value)
723   };
724 };
725
726 } // namespace detail
727
728 /**
729  * operator== through conversion for Range<const char*>
730  */
731 template <class T, class U>
732 typename
733 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
734 operator==(const T& lhs, const U& rhs) {
735   return StringPiece(lhs) == StringPiece(rhs);
736 }
737
738 /**
739  * operator< through conversion for Range<const char*>
740  */
741 template <class T, class U>
742 typename
743 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
744 operator<(const T& lhs, const U& rhs) {
745   return StringPiece(lhs) < StringPiece(rhs);
746 }
747
748 /**
749  * operator> through conversion for Range<const char*>
750  */
751 template <class T, class U>
752 typename
753 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
754 operator>(const T& lhs, const U& rhs) {
755   return StringPiece(lhs) > StringPiece(rhs);
756 }
757
758 /**
759  * operator< through conversion for Range<const char*>
760  */
761 template <class T, class U>
762 typename
763 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
764 operator<=(const T& lhs, const U& rhs) {
765   return StringPiece(lhs) <= StringPiece(rhs);
766 }
767
768 /**
769  * operator> through conversion for Range<const char*>
770  */
771 template <class T, class U>
772 typename
773 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
774 operator>=(const T& lhs, const U& rhs) {
775   return StringPiece(lhs) >= StringPiece(rhs);
776 }
777
778 struct StringPieceHash {
779   std::size_t operator()(const StringPiece& str) const {
780     return static_cast<std::size_t>(str.hash());
781   }
782 };
783
784 /**
785  * Finds substrings faster than brute force by borrowing from Boyer-Moore
786  */
787 template <class T, class Comp>
788 size_t qfind(const Range<T>& haystack,
789              const Range<T>& needle,
790              Comp eq) {
791   // Don't use std::search, use a Boyer-Moore-like trick by comparing
792   // the last characters first
793   auto const nsize = needle.size();
794   if (haystack.size() < nsize) {
795     return std::string::npos;
796   }
797   if (!nsize) return 0;
798   auto const nsize_1 = nsize - 1;
799   auto const lastNeedle = needle[nsize_1];
800
801   // Boyer-Moore skip value for the last char in the needle. Zero is
802   // not a valid value; skip will be computed the first time it's
803   // needed.
804   std::string::size_type skip = 0;
805
806   auto i = haystack.begin();
807   auto iEnd = haystack.end() - nsize_1;
808
809   while (i < iEnd) {
810     // Boyer-Moore: match the last element in the needle
811     while (!eq(i[nsize_1], lastNeedle)) {
812       if (++i == iEnd) {
813         // not found
814         return std::string::npos;
815       }
816     }
817     // Here we know that the last char matches
818     // Continue in pedestrian mode
819     for (size_t j = 0; ; ) {
820       assert(j < nsize);
821       if (!eq(i[j], needle[j])) {
822         // Not found, we can skip
823         // Compute the skip value lazily
824         if (skip == 0) {
825           skip = 1;
826           while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
827             ++skip;
828           }
829         }
830         i += skip;
831         break;
832       }
833       // Check if done searching
834       if (++j == nsize) {
835         // Yay
836         return i - haystack.begin();
837       }
838     }
839   }
840   return std::string::npos;
841 }
842
843 namespace detail {
844
845 size_t qfind_first_byte_of_nosse(const StringPiece& haystack,
846                                  const StringPiece& needles);
847
848 #if FOLLY_HAVE_EMMINTRIN_H && __GNUC_PREREQ(4, 6)
849 size_t qfind_first_byte_of_sse42(const StringPiece& haystack,
850                                  const StringPiece& needles);
851
852 inline size_t qfind_first_byte_of(const StringPiece& haystack,
853                                   const StringPiece& needles) {
854   static auto const qfind_first_byte_of_fn =
855     folly::CpuId().sse42() ? qfind_first_byte_of_sse42
856                            : qfind_first_byte_of_nosse;
857   return qfind_first_byte_of_fn(haystack, needles);
858 }
859
860 #else
861 inline size_t qfind_first_byte_of(const StringPiece& haystack,
862                                   const StringPiece& needles) {
863   return qfind_first_byte_of_nosse(haystack, needles);
864 }
865 #endif // FOLLY_HAVE_EMMINTRIN_H
866
867 } // namespace detail
868
869 template <class T, class Comp>
870 size_t qfind_first_of(const Range<T> & haystack,
871                       const Range<T> & needles,
872                       Comp eq) {
873   auto ret = std::find_first_of(haystack.begin(), haystack.end(),
874                                 needles.begin(), needles.end(),
875                                 eq);
876   return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
877 }
878
879 struct AsciiCaseSensitive {
880   bool operator()(char lhs, char rhs) const {
881     return lhs == rhs;
882   }
883 };
884
885 /**
886  * Check if two ascii characters are case insensitive equal.
887  * The difference between the lower/upper case characters are the 6-th bit.
888  * We also check they are alpha chars, in case of xor = 32.
889  */
890 struct AsciiCaseInsensitive {
891   bool operator()(char lhs, char rhs) const {
892     char k = lhs ^ rhs;
893     if (k == 0) return true;
894     if (k != 32) return false;
895     k = lhs | rhs;
896     return (k >= 'a' && k <= 'z');
897   }
898 };
899
900 extern const AsciiCaseSensitive asciiCaseSensitive;
901 extern const AsciiCaseInsensitive asciiCaseInsensitive;
902
903 template <class T>
904 size_t qfind(const Range<T>& haystack,
905              const typename Range<T>::value_type& needle) {
906   auto pos = std::find(haystack.begin(), haystack.end(), needle);
907   return pos == haystack.end() ? std::string::npos : pos - haystack.data();
908 }
909
910 template <class T>
911 size_t rfind(const Range<T>& haystack,
912              const typename Range<T>::value_type& needle) {
913   for (auto i = haystack.size(); i-- > 0; ) {
914     if (haystack[i] == needle) {
915       return i;
916     }
917   }
918   return std::string::npos;
919 }
920
921 // specialization for StringPiece
922 template <>
923 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
924   auto pos = static_cast<const char*>(
925     ::memchr(haystack.data(), needle, haystack.size()));
926   return pos == nullptr ? std::string::npos : pos - haystack.data();
927 }
928
929 #if FOLLY_HAVE_MEMRCHR
930 template <>
931 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
932   auto pos = static_cast<const char*>(
933     ::memrchr(haystack.data(), needle, haystack.size()));
934   return pos == nullptr ? std::string::npos : pos - haystack.data();
935 }
936 #endif
937
938 // specialization for ByteRange
939 template <>
940 inline size_t qfind(const Range<const unsigned char*>& haystack,
941                     const unsigned char& needle) {
942   auto pos = static_cast<const unsigned char*>(
943     ::memchr(haystack.data(), needle, haystack.size()));
944   return pos == nullptr ? std::string::npos : pos - haystack.data();
945 }
946
947 #if FOLLY_HAVE_MEMRCHR
948 template <>
949 inline size_t rfind(const Range<const unsigned char*>& haystack,
950                     const unsigned char& needle) {
951   auto pos = static_cast<const unsigned char*>(
952     ::memrchr(haystack.data(), needle, haystack.size()));
953   return pos == nullptr ? std::string::npos : pos - haystack.data();
954 }
955 #endif
956
957 template <class T>
958 size_t qfind_first_of(const Range<T>& haystack,
959                       const Range<T>& needles) {
960   return qfind_first_of(haystack, needles, asciiCaseSensitive);
961 }
962
963 // specialization for StringPiece
964 template <>
965 inline size_t qfind_first_of(const Range<const char*>& haystack,
966                              const Range<const char*>& needles) {
967   return detail::qfind_first_byte_of(haystack, needles);
968 }
969
970 // specialization for ByteRange
971 template <>
972 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
973                              const Range<const unsigned char*>& needles) {
974   return detail::qfind_first_byte_of(StringPiece(haystack),
975                                      StringPiece(needles));
976 }
977 }  // !namespace folly
978
979 #pragma GCC diagnostic pop
980
981 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);
982
983 #endif // FOLLY_RANGE_H_