Codemod: use #include angle brackets in folly and thrift
[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. Any additional arguments
615    * `args` passed to this function are perfectly forwarded to the functor.
616    *
617    * Say you have a functor with this signature:
618    *
619    *  Foo fn(Range r) { }
620    *
621    * `split_step()`'s return type will be `Foo`. It works just like:
622    *
623    *  auto result = fn(myRange.split_step(' '));
624    *
625    * A functor returning `void` is also supported.
626    *
627    * Example:
628    *
629    *  void do_some_parsing(folly::StringPiece s) {
630    *    auto version = s.split_step(' ', [&](folly::StringPiece x) {
631    *      if (x.empty()) {
632    *        throw std::invalid_argument("empty string");
633    *      }
634    *      return std::strtoull(x.begin(), x.end(), 16);
635    *    });
636    *
637    *    // ...
638    *  }
639    *
640    *  struct Foo {
641    *    void parse(folly::StringPiece s) {
642    *      s.split_step(' ', parse_field, bar, 10);
643    *      s.split_step('\t', parse_field, baz, 20);
644    *
645    *      auto const kludge = [](folly::StringPiece x, int &out, int def) {
646    *        if (x == "null") {
647    *          out = 0;
648    *        } else {
649    *          parse_field(x, out, def);
650    *        }
651    *      };
652    *
653    *      s.split_step('\t', kludge, gaz);
654    *      s.split_step(' ', kludge, foo);
655    *    }
656    *
657    *  private:
658    *    int bar;
659    *    int baz;
660    *    int gaz;
661    *    int foo;
662    *
663    *    static parse_field(folly::StringPiece s, int &out, int def) {
664    *      try {
665    *        out = folly::to<int>(s);
666    *      } catch (std::exception const &) {
667    *        value = def;
668    *      }
669    *    }
670    *  };
671    *
672    * @author: Marcelo Juchem <marcelo@fb.com>
673    */
674   template <typename TProcess, typename... Args>
675   auto split_step(value_type delimiter, TProcess &&process, Args &&...args)
676     -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
677   { return process(split_step(delimiter), std::forward<Args>(args)...); }
678
679   template <typename TProcess, typename... Args>
680   auto split_step(Range delimiter, TProcess &&process, Args &&...args)
681     -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
682   { return process(split_step(delimiter), std::forward<Args>(args)...); }
683
684 private:
685   Iter b_, e_;
686 };
687
688 template <class Iter>
689 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
690
691 template <class T>
692 void swap(Range<T>& lhs, Range<T>& rhs) {
693   lhs.swap(rhs);
694 }
695
696 /**
697  * Create a range from two iterators, with type deduction.
698  */
699 template <class Iter>
700 Range<Iter> range(Iter first, Iter last) {
701   return Range<Iter>(first, last);
702 }
703
704 /*
705  * Creates a range to reference the contents of a contiguous-storage container.
706  */
707 // Use pointers for types with '.data()' member
708 template <class Collection,
709           class T = typename std::remove_pointer<
710               decltype(std::declval<Collection>().data())>::type>
711 Range<T*> range(Collection&& v) {
712   return Range<T*>(v.data(), v.data() + v.size());
713 }
714
715 template <class T, size_t n>
716 Range<T*> range(T (&array)[n]) {
717   return Range<T*>(array, array + n);
718 }
719
720 typedef Range<const char*> StringPiece;
721 typedef Range<char*> MutableStringPiece;
722 typedef Range<const unsigned char*> ByteRange;
723 typedef Range<unsigned char*> MutableByteRange;
724
725 std::ostream& operator<<(std::ostream& os, const StringPiece& piece);
726
727 /**
728  * Templated comparison operators
729  */
730
731 template <class T>
732 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
733   return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
734 }
735
736 template <class T>
737 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
738   return lhs.compare(rhs) < 0;
739 }
740
741 /**
742  * Specializations of comparison operators for StringPiece
743  */
744
745 namespace detail {
746
747 template <class A, class B>
748 struct ComparableAsStringPiece {
749   enum {
750     value =
751     (std::is_convertible<A, StringPiece>::value
752      && std::is_same<B, StringPiece>::value)
753     ||
754     (std::is_convertible<B, StringPiece>::value
755      && std::is_same<A, StringPiece>::value)
756   };
757 };
758
759 } // namespace detail
760
761 /**
762  * operator== through conversion for Range<const char*>
763  */
764 template <class T, class U>
765 typename
766 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
767 operator==(const T& lhs, const U& rhs) {
768   return StringPiece(lhs) == StringPiece(rhs);
769 }
770
771 /**
772  * operator< through conversion for Range<const char*>
773  */
774 template <class T, class U>
775 typename
776 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
777 operator<(const T& lhs, const U& rhs) {
778   return StringPiece(lhs) < StringPiece(rhs);
779 }
780
781 /**
782  * operator> through conversion for Range<const char*>
783  */
784 template <class T, class U>
785 typename
786 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
787 operator>(const T& lhs, const U& rhs) {
788   return StringPiece(lhs) > StringPiece(rhs);
789 }
790
791 /**
792  * operator< through conversion for Range<const char*>
793  */
794 template <class T, class U>
795 typename
796 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
797 operator<=(const T& lhs, const U& rhs) {
798   return StringPiece(lhs) <= StringPiece(rhs);
799 }
800
801 /**
802  * operator> through conversion for Range<const char*>
803  */
804 template <class T, class U>
805 typename
806 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
807 operator>=(const T& lhs, const U& rhs) {
808   return StringPiece(lhs) >= StringPiece(rhs);
809 }
810
811 struct StringPieceHash {
812   std::size_t operator()(const StringPiece& str) const {
813     return static_cast<std::size_t>(str.hash());
814   }
815 };
816
817 /**
818  * Finds substrings faster than brute force by borrowing from Boyer-Moore
819  */
820 template <class T, class Comp>
821 size_t qfind(const Range<T>& haystack,
822              const Range<T>& needle,
823              Comp eq) {
824   // Don't use std::search, use a Boyer-Moore-like trick by comparing
825   // the last characters first
826   auto const nsize = needle.size();
827   if (haystack.size() < nsize) {
828     return std::string::npos;
829   }
830   if (!nsize) return 0;
831   auto const nsize_1 = nsize - 1;
832   auto const lastNeedle = needle[nsize_1];
833
834   // Boyer-Moore skip value for the last char in the needle. Zero is
835   // not a valid value; skip will be computed the first time it's
836   // needed.
837   std::string::size_type skip = 0;
838
839   auto i = haystack.begin();
840   auto iEnd = haystack.end() - nsize_1;
841
842   while (i < iEnd) {
843     // Boyer-Moore: match the last element in the needle
844     while (!eq(i[nsize_1], lastNeedle)) {
845       if (++i == iEnd) {
846         // not found
847         return std::string::npos;
848       }
849     }
850     // Here we know that the last char matches
851     // Continue in pedestrian mode
852     for (size_t j = 0; ; ) {
853       assert(j < nsize);
854       if (!eq(i[j], needle[j])) {
855         // Not found, we can skip
856         // Compute the skip value lazily
857         if (skip == 0) {
858           skip = 1;
859           while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
860             ++skip;
861           }
862         }
863         i += skip;
864         break;
865       }
866       // Check if done searching
867       if (++j == nsize) {
868         // Yay
869         return i - haystack.begin();
870       }
871     }
872   }
873   return std::string::npos;
874 }
875
876 namespace detail {
877
878 size_t qfind_first_byte_of_nosse(const StringPiece& haystack,
879                                  const StringPiece& needles);
880
881 #if FOLLY_HAVE_EMMINTRIN_H && __GNUC_PREREQ(4, 6)
882 size_t qfind_first_byte_of_sse42(const StringPiece& haystack,
883                                  const StringPiece& needles);
884
885 inline size_t qfind_first_byte_of(const StringPiece& haystack,
886                                   const StringPiece& needles) {
887   static auto const qfind_first_byte_of_fn =
888     folly::CpuId().sse42() ? qfind_first_byte_of_sse42
889                            : qfind_first_byte_of_nosse;
890   return qfind_first_byte_of_fn(haystack, needles);
891 }
892
893 #else
894 inline size_t qfind_first_byte_of(const StringPiece& haystack,
895                                   const StringPiece& needles) {
896   return qfind_first_byte_of_nosse(haystack, needles);
897 }
898 #endif // FOLLY_HAVE_EMMINTRIN_H
899
900 } // namespace detail
901
902 template <class T, class Comp>
903 size_t qfind_first_of(const Range<T> & haystack,
904                       const Range<T> & needles,
905                       Comp eq) {
906   auto ret = std::find_first_of(haystack.begin(), haystack.end(),
907                                 needles.begin(), needles.end(),
908                                 eq);
909   return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
910 }
911
912 struct AsciiCaseSensitive {
913   bool operator()(char lhs, char rhs) const {
914     return lhs == rhs;
915   }
916 };
917
918 /**
919  * Check if two ascii characters are case insensitive equal.
920  * The difference between the lower/upper case characters are the 6-th bit.
921  * We also check they are alpha chars, in case of xor = 32.
922  */
923 struct AsciiCaseInsensitive {
924   bool operator()(char lhs, char rhs) const {
925     char k = lhs ^ rhs;
926     if (k == 0) return true;
927     if (k != 32) return false;
928     k = lhs | rhs;
929     return (k >= 'a' && k <= 'z');
930   }
931 };
932
933 extern const AsciiCaseSensitive asciiCaseSensitive;
934 extern const AsciiCaseInsensitive asciiCaseInsensitive;
935
936 template <class T>
937 size_t qfind(const Range<T>& haystack,
938              const typename Range<T>::value_type& needle) {
939   auto pos = std::find(haystack.begin(), haystack.end(), needle);
940   return pos == haystack.end() ? std::string::npos : pos - haystack.data();
941 }
942
943 template <class T>
944 size_t rfind(const Range<T>& haystack,
945              const typename Range<T>::value_type& needle) {
946   for (auto i = haystack.size(); i-- > 0; ) {
947     if (haystack[i] == needle) {
948       return i;
949     }
950   }
951   return std::string::npos;
952 }
953
954 // specialization for StringPiece
955 template <>
956 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
957   auto pos = static_cast<const char*>(
958     ::memchr(haystack.data(), needle, haystack.size()));
959   return pos == nullptr ? std::string::npos : pos - haystack.data();
960 }
961
962 #if FOLLY_HAVE_MEMRCHR
963 template <>
964 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
965   auto pos = static_cast<const char*>(
966     ::memrchr(haystack.data(), needle, haystack.size()));
967   return pos == nullptr ? std::string::npos : pos - haystack.data();
968 }
969 #endif
970
971 // specialization for ByteRange
972 template <>
973 inline size_t qfind(const Range<const unsigned char*>& haystack,
974                     const unsigned char& needle) {
975   auto pos = static_cast<const unsigned char*>(
976     ::memchr(haystack.data(), needle, haystack.size()));
977   return pos == nullptr ? std::string::npos : pos - haystack.data();
978 }
979
980 #if FOLLY_HAVE_MEMRCHR
981 template <>
982 inline size_t rfind(const Range<const unsigned char*>& haystack,
983                     const unsigned char& needle) {
984   auto pos = static_cast<const unsigned char*>(
985     ::memrchr(haystack.data(), needle, haystack.size()));
986   return pos == nullptr ? std::string::npos : pos - haystack.data();
987 }
988 #endif
989
990 template <class T>
991 size_t qfind_first_of(const Range<T>& haystack,
992                       const Range<T>& needles) {
993   return qfind_first_of(haystack, needles, asciiCaseSensitive);
994 }
995
996 // specialization for StringPiece
997 template <>
998 inline size_t qfind_first_of(const Range<const char*>& haystack,
999                              const Range<const char*>& needles) {
1000   return detail::qfind_first_byte_of(haystack, needles);
1001 }
1002
1003 // specialization for ByteRange
1004 template <>
1005 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
1006                              const Range<const unsigned char*>& needles) {
1007   return detail::qfind_first_byte_of(StringPiece(haystack),
1008                                      StringPiece(needles));
1009 }
1010 }  // !namespace folly
1011
1012 #pragma GCC diagnostic pop
1013
1014 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);
1015
1016 #endif // FOLLY_RANGE_H_