Make IOBuf support 64-bit length and capacity
[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 <glog/logging.h>
26 #include <algorithm>
27 #include <cstring>
28 #include <iosfwd>
29 #include <string>
30 #include <stdexcept>
31 #include <type_traits>
32 #include <boost/operators.hpp>
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   // Works only for Range<const char*>
178   Range(const std::string& str, std::string::size_type startFrom) {
179     if (UNLIKELY(startFrom > str.size())) {
180       throw std::out_of_range("index out of range");
181     }
182     b_ = str.data() + startFrom;
183     e_ = str.data() + str.size();
184   }
185   // Works only for Range<const char*>
186   Range(const std::string& str,
187         std::string::size_type startFrom,
188         std::string::size_type size) {
189     if (UNLIKELY(startFrom > str.size())) {
190       throw std::out_of_range("index out of range");
191     }
192     b_ = str.data() + startFrom;
193     if (str.size() - startFrom < size) {
194       e_ = str.data() + str.size();
195     } else {
196       e_ = b_ + size;
197     }
198   }
199   Range(const Range<Iter>& str,
200         size_t startFrom,
201         size_t size) {
202     if (UNLIKELY(startFrom > str.size())) {
203       throw std::out_of_range("index out of range");
204     }
205     b_ = str.b_ + startFrom;
206     if (str.size() - startFrom < size) {
207       e_ = str.e_;
208     } else {
209       e_ = b_ + size;
210     }
211   }
212   // Works only for Range<const char*>
213   /* implicit */ Range(const fbstring& str)
214     : b_(str.data()), e_(b_ + str.size()) { }
215   // Works only for Range<const char*>
216   Range(const fbstring& str, fbstring::size_type startFrom) {
217     if (UNLIKELY(startFrom > str.size())) {
218       throw std::out_of_range("index out of range");
219     }
220     b_ = str.data() + startFrom;
221     e_ = str.data() + str.size();
222   }
223   // Works only for Range<const char*>
224   Range(const fbstring& str, fbstring::size_type startFrom,
225         fbstring::size_type size) {
226     if (UNLIKELY(startFrom > str.size())) {
227       throw std::out_of_range("index out of range");
228     }
229     b_ = str.data() + startFrom;
230     if (str.size() - startFrom < size) {
231       e_ = str.data() + str.size();
232     } else {
233       e_ = b_ + size;
234     }
235   }
236
237   // Allow implicit conversion from Range<const char*> (aka StringPiece) to
238   // Range<const unsigned char*> (aka ByteRange), as they're both frequently
239   // used to represent ranges of bytes.  Allow explicit conversion in the other
240   // direction.
241   template <class OtherIter, typename std::enable_if<
242       (std::is_same<Iter, const unsigned char*>::value &&
243        std::is_same<OtherIter, const char*>::value), int>::type = 0>
244   /* implicit */ Range(const Range<OtherIter>& other)
245     : b_(reinterpret_cast<const unsigned char*>(other.begin())),
246       e_(reinterpret_cast<const unsigned char*>(other.end())) {
247   }
248
249   template <class OtherIter, typename std::enable_if<
250       (std::is_same<Iter, const char*>::value &&
251        std::is_same<OtherIter, const unsigned char*>::value), int>::type = 0>
252   explicit Range(const Range<OtherIter>& other)
253     : b_(reinterpret_cast<const char*>(other.begin())),
254       e_(reinterpret_cast<const char*>(other.end())) {
255   }
256
257   void clear() {
258     b_ = Iter();
259     e_ = Iter();
260   }
261
262   void assign(Iter start, Iter end) {
263     b_ = start;
264     e_ = end;
265   }
266
267   void reset(Iter start, size_type size) {
268     b_ = start;
269     e_ = start + size;
270   }
271
272   // Works only for Range<const char*>
273   void reset(const std::string& str) {
274     reset(str.data(), str.size());
275   }
276
277   size_type size() const {
278     assert(b_ <= e_);
279     return e_ - b_;
280   }
281   size_type walk_size() const {
282     assert(b_ <= e_);
283     return std::distance(b_, e_);
284   }
285   bool empty() const { return b_ == e_; }
286   Iter data() const { return b_; }
287   Iter start() const { return b_; }
288   Iter begin() const { return b_; }
289   Iter end() const { return e_; }
290   Iter cbegin() const { return b_; }
291   Iter cend() const { return e_; }
292   value_type& front() {
293     assert(b_ < e_);
294     return *b_;
295   }
296   value_type& back() {
297     assert(b_ < e_);
298     return detail::value_before(e_);
299   }
300   const value_type& front() const {
301     assert(b_ < e_);
302     return *b_;
303   }
304   const value_type& back() const {
305     assert(b_ < e_);
306     return detail::value_before(e_);
307   }
308   // Works only for Range<const char*>
309   std::string str() const { return std::string(b_, size()); }
310   std::string toString() const { return str(); }
311   // Works only for Range<const char*>
312   fbstring fbstr() const { return fbstring(b_, size()); }
313   fbstring toFbstring() const { return fbstr(); }
314
315   // Works only for Range<const char*>
316   int compare(const Range& o) const {
317     const size_type tsize = this->size();
318     const size_type osize = o.size();
319     const size_type msize = std::min(tsize, osize);
320     int r = traits_type::compare(data(), o.data(), msize);
321     if (r == 0) r = tsize - osize;
322     return r;
323   }
324
325   value_type& operator[](size_t i) {
326     DCHECK_GT(size(), i);
327     return b_[i];
328   }
329
330   const value_type& operator[](size_t i) const {
331     DCHECK_GT(size(), i);
332     return b_[i];
333   }
334
335   value_type& at(size_t i) {
336     if (i >= size()) throw std::out_of_range("index out of range");
337     return b_[i];
338   }
339
340   const value_type& at(size_t i) const {
341     if (i >= size()) throw std::out_of_range("index out of range");
342     return b_[i];
343   }
344
345   // Works only for Range<const char*>
346   uint32_t hash() const {
347     // Taken from fbi/nstring.h:
348     //    Quick and dirty bernstein hash...fine for short ascii strings
349     uint32_t hash = 5381;
350     for (size_t ix = 0; ix < size(); ix++) {
351       hash = ((hash << 5) + hash) + b_[ix];
352     }
353     return hash;
354   }
355
356   void advance(size_type n) {
357     if (UNLIKELY(n > size())) {
358       throw std::out_of_range("index out of range");
359     }
360     b_ += n;
361   }
362
363   void subtract(size_type n) {
364     if (UNLIKELY(n > size())) {
365       throw std::out_of_range("index out of range");
366     }
367     e_ -= n;
368   }
369
370   void pop_front() {
371     assert(b_ < e_);
372     ++b_;
373   }
374
375   void pop_back() {
376     assert(b_ < e_);
377     --e_;
378   }
379
380   Range subpiece(size_type first,
381                  size_type length = std::string::npos) const {
382     if (UNLIKELY(first > size())) {
383       throw std::out_of_range("index out of range");
384     }
385     return Range(b_ + first,
386                  std::min<std::string::size_type>(length, size() - first));
387   }
388
389   // string work-alike functions
390   size_type find(Range str) const {
391     return qfind(*this, str);
392   }
393
394   size_type find(Range str, size_t pos) const {
395     if (pos > size()) return std::string::npos;
396     size_t ret = qfind(subpiece(pos), str);
397     return ret == npos ? ret : ret + pos;
398   }
399
400   size_type find(Iter s, size_t pos, size_t n) const {
401     if (pos > size()) return std::string::npos;
402     size_t ret = qfind(pos ? subpiece(pos) : *this, Range(s, n));
403     return ret == npos ? ret : ret + pos;
404   }
405
406   // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
407   size_type find(const Iter s) const {
408     return qfind(*this, Range(s));
409   }
410
411   // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
412   size_type find(const Iter s, size_t pos) const {
413     if (pos > size()) return std::string::npos;
414     size_type ret = qfind(subpiece(pos), Range(s));
415     return ret == npos ? ret : ret + pos;
416   }
417
418   size_type find(value_type c) const {
419     return qfind(*this, c);
420   }
421
422   size_type rfind(value_type c) const {
423     return folly::rfind(*this, c);
424   }
425
426   size_type find(value_type c, size_t pos) const {
427     if (pos > size()) return std::string::npos;
428     size_type ret = qfind(subpiece(pos), c);
429     return ret == npos ? ret : ret + pos;
430   }
431
432   size_type find_first_of(Range needles) const {
433     return qfind_first_of(*this, needles);
434   }
435
436   size_type find_first_of(Range needles, size_t pos) const {
437     if (pos > size()) return std::string::npos;
438     size_type ret = qfind_first_of(subpiece(pos), needles);
439     return ret == npos ? ret : ret + pos;
440   }
441
442   // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
443   size_type find_first_of(Iter needles) const {
444     return find_first_of(Range(needles));
445   }
446
447   // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
448   size_type find_first_of(Iter needles, size_t pos) const {
449     return find_first_of(Range(needles), pos);
450   }
451
452   size_type find_first_of(Iter needles, size_t pos, size_t n) const {
453     return find_first_of(Range(needles, n), pos);
454   }
455
456   size_type find_first_of(value_type c) const {
457     return find(c);
458   }
459
460   size_type find_first_of(value_type c, size_t pos) const {
461     return find(c, pos);
462   }
463
464   void swap(Range& rhs) {
465     std::swap(b_, rhs.b_);
466     std::swap(e_, rhs.e_);
467   }
468
469   /**
470    * Does this Range start with another range?
471    */
472   bool startsWith(const Range& other) const {
473     return size() >= other.size() && subpiece(0, other.size()) == other;
474   }
475   bool startsWith(value_type c) const {
476     return !empty() && front() == c;
477   }
478
479   /**
480    * Does this Range end with another range?
481    */
482   bool endsWith(const Range& other) const {
483     return size() >= other.size() && subpiece(size() - other.size()) == other;
484   }
485   bool endsWith(value_type c) const {
486     return !empty() && back() == c;
487   }
488
489   /**
490    * Remove the given prefix and return true if the range starts with the given
491    * prefix; return false otherwise.
492    */
493   bool removePrefix(const Range& prefix) {
494     return startsWith(prefix) && (b_ += prefix.size(), true);
495   }
496   bool removePrefix(value_type prefix) {
497     return startsWith(prefix) && (++b_, true);
498   }
499
500   /**
501    * Remove the given suffix and return true if the range ends with the given
502    * suffix; return false otherwise.
503    */
504   bool removeSuffix(const Range& suffix) {
505     return endsWith(suffix) && (e_ -= suffix.size(), true);
506   }
507   bool removeSuffix(value_type suffix) {
508     return endsWith(suffix) && (--e_, true);
509   }
510
511   /**
512    * Splits this `Range` `[b, e)` in the position `i` dictated by the next
513    * occurence of `delimiter`.
514    *
515    * Returns a new `Range` `[b, i)` and adjusts this range to start right after
516    * the delimiter's position. This range will be empty if the delimiter is not
517    * found. If called on an empty `Range`, both this and the returned `Range`
518    * will be empty.
519    *
520    * Example:
521    *
522    *  folly::StringPiece s("sample string for split_next");
523    *  auto p = s.split_step(' ');
524    *
525    *  // prints "sample"
526    *  cout << s << endl;
527    *
528    *  // prints "string for split_next"
529    *  cout << p << endl;
530    *
531    * Example 2:
532    *
533    *  void tokenize(StringPiece s, char delimiter) {
534    *    while (!s.empty()) {
535    *      cout << s.split_step(delimiter);
536    *    }
537    *  }
538    *
539    * @author: Marcelo Juchem <marcelo@fb.com>
540    */
541   Range split_step(value_type delimiter) {
542     auto i = std::find(b_, e_, delimiter);
543     Range result(b_, i);
544
545     b_ = i == e_ ? e_ : std::next(i);
546
547     return result;
548   }
549
550   Range split_step(Range delimiter) {
551     auto i = find(delimiter);
552     Range result(b_, i == std::string::npos ? size() : i);
553
554     b_ = result.end() == e_ ? e_ : std::next(result.end(), delimiter.size());
555
556     return result;
557   }
558
559   /**
560    * Convenience method that calls `split_step()` and passes the result to a
561    * functor, returning whatever the functor does.
562    *
563    * Say you have a functor with this signature:
564    *
565    *  Foo fn(Range r) { }
566    *
567    * `split_step()`'s return type will be `Foo`. It works just like:
568    *
569    *  auto result = fn(myRange.split_step(' '));
570    *
571    * A functor returning `void` is also supported.
572    *
573    * Example:
574    *
575    *  void do_some_parsing(folly::StringPiece s) {
576    *    auto version = s.split_step(' ', [&](folly::StringPiece x) {
577    *      if (x.empty()) {
578    *        throw std::invalid_argument("empty string");
579    *      }
580    *      return std::strtoull(x.begin(), x.end(), 16);
581    *    });
582    *
583    *    // ...
584    *  }
585    *
586    * @author: Marcelo Juchem <marcelo@fb.com>
587    */
588   template <typename TProcess>
589   auto split_step(value_type delimiter, TProcess &&process)
590     -> decltype(process(std::declval<Range>()))
591   { return process(split_step(delimiter)); }
592
593   template <typename TProcess>
594   auto split_step(Range delimiter, TProcess &&process)
595     -> decltype(process(std::declval<Range>()))
596   { return process(split_step(delimiter)); }
597
598 private:
599   Iter b_, e_;
600 };
601
602 template <class Iter>
603 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
604
605 template <class T>
606 void swap(Range<T>& lhs, Range<T>& rhs) {
607   lhs.swap(rhs);
608 }
609
610 /**
611  * Create a range from two iterators, with type deduction.
612  */
613 template <class Iter>
614 Range<Iter> makeRange(Iter first, Iter last) {
615   return Range<Iter>(first, last);
616 }
617
618 typedef Range<const char*> StringPiece;
619 typedef Range<const unsigned char*> ByteRange;
620
621 std::ostream& operator<<(std::ostream& os, const StringPiece& piece);
622
623 /**
624  * Templated comparison operators
625  */
626
627 template <class T>
628 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
629   return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
630 }
631
632 template <class T>
633 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
634   return lhs.compare(rhs) < 0;
635 }
636
637 /**
638  * Specializations of comparison operators for StringPiece
639  */
640
641 namespace detail {
642
643 template <class A, class B>
644 struct ComparableAsStringPiece {
645   enum {
646     value =
647     (std::is_convertible<A, StringPiece>::value
648      && std::is_same<B, StringPiece>::value)
649     ||
650     (std::is_convertible<B, StringPiece>::value
651      && std::is_same<A, StringPiece>::value)
652   };
653 };
654
655 } // namespace detail
656
657 /**
658  * operator== through conversion for Range<const char*>
659  */
660 template <class T, class U>
661 typename
662 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
663 operator==(const T& lhs, const U& rhs) {
664   return StringPiece(lhs) == StringPiece(rhs);
665 }
666
667 /**
668  * operator< through conversion for Range<const char*>
669  */
670 template <class T, class U>
671 typename
672 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
673 operator<(const T& lhs, const U& rhs) {
674   return StringPiece(lhs) < StringPiece(rhs);
675 }
676
677 /**
678  * operator> through conversion for Range<const char*>
679  */
680 template <class T, class U>
681 typename
682 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
683 operator>(const T& lhs, const U& rhs) {
684   return StringPiece(lhs) > StringPiece(rhs);
685 }
686
687 /**
688  * operator< through conversion for Range<const char*>
689  */
690 template <class T, class U>
691 typename
692 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
693 operator<=(const T& lhs, const U& rhs) {
694   return StringPiece(lhs) <= StringPiece(rhs);
695 }
696
697 /**
698  * operator> through conversion for Range<const char*>
699  */
700 template <class T, class U>
701 typename
702 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
703 operator>=(const T& lhs, const U& rhs) {
704   return StringPiece(lhs) >= StringPiece(rhs);
705 }
706
707 struct StringPieceHash {
708   std::size_t operator()(const StringPiece& str) const {
709     return static_cast<std::size_t>(str.hash());
710   }
711 };
712
713 /**
714  * Finds substrings faster than brute force by borrowing from Boyer-Moore
715  */
716 template <class T, class Comp>
717 size_t qfind(const Range<T>& haystack,
718              const Range<T>& needle,
719              Comp eq) {
720   // Don't use std::search, use a Boyer-Moore-like trick by comparing
721   // the last characters first
722   auto const nsize = needle.size();
723   if (haystack.size() < nsize) {
724     return std::string::npos;
725   }
726   if (!nsize) return 0;
727   auto const nsize_1 = nsize - 1;
728   auto const lastNeedle = needle[nsize_1];
729
730   // Boyer-Moore skip value for the last char in the needle. Zero is
731   // not a valid value; skip will be computed the first time it's
732   // needed.
733   std::string::size_type skip = 0;
734
735   auto i = haystack.begin();
736   auto iEnd = haystack.end() - nsize_1;
737
738   while (i < iEnd) {
739     // Boyer-Moore: match the last element in the needle
740     while (!eq(i[nsize_1], lastNeedle)) {
741       if (++i == iEnd) {
742         // not found
743         return std::string::npos;
744       }
745     }
746     // Here we know that the last char matches
747     // Continue in pedestrian mode
748     for (size_t j = 0; ; ) {
749       assert(j < nsize);
750       if (!eq(i[j], needle[j])) {
751         // Not found, we can skip
752         // Compute the skip value lazily
753         if (skip == 0) {
754           skip = 1;
755           while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
756             ++skip;
757           }
758         }
759         i += skip;
760         break;
761       }
762       // Check if done searching
763       if (++j == nsize) {
764         // Yay
765         return i - haystack.begin();
766       }
767     }
768   }
769   return std::string::npos;
770 }
771
772 namespace detail {
773
774 size_t qfind_first_byte_of_nosse(const StringPiece& haystack,
775                                  const StringPiece& needles);
776
777 #if FOLLY_HAVE_EMMINTRIN_H && __GNUC_PREREQ(4, 6)
778 size_t qfind_first_byte_of_sse42(const StringPiece& haystack,
779                                  const StringPiece& needles);
780
781 inline size_t qfind_first_byte_of(const StringPiece& haystack,
782                                   const StringPiece& needles) {
783   static auto const qfind_first_byte_of_fn =
784     folly::CpuId().sse42() ? qfind_first_byte_of_sse42
785                            : qfind_first_byte_of_nosse;
786   return qfind_first_byte_of_fn(haystack, needles);
787 }
788
789 #else
790 inline size_t qfind_first_byte_of(const StringPiece& haystack,
791                                   const StringPiece& needles) {
792   return qfind_first_byte_of_nosse(haystack, needles);
793 }
794 #endif // FOLLY_HAVE_EMMINTRIN_H
795
796 } // namespace detail
797
798 template <class T, class Comp>
799 size_t qfind_first_of(const Range<T> & haystack,
800                       const Range<T> & needles,
801                       Comp eq) {
802   auto ret = std::find_first_of(haystack.begin(), haystack.end(),
803                                 needles.begin(), needles.end(),
804                                 eq);
805   return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
806 }
807
808 struct AsciiCaseSensitive {
809   bool operator()(char lhs, char rhs) const {
810     return lhs == rhs;
811   }
812 };
813
814 struct AsciiCaseInsensitive {
815   bool operator()(char lhs, char rhs) const {
816     return toupper(lhs) == toupper(rhs);
817   }
818 };
819
820 extern const AsciiCaseSensitive asciiCaseSensitive;
821 extern const AsciiCaseInsensitive asciiCaseInsensitive;
822
823 template <class T>
824 size_t qfind(const Range<T>& haystack,
825              const typename Range<T>::value_type& needle) {
826   auto pos = std::find(haystack.begin(), haystack.end(), needle);
827   return pos == haystack.end() ? std::string::npos : pos - haystack.data();
828 }
829
830 template <class T>
831 size_t rfind(const Range<T>& haystack,
832              const typename Range<T>::value_type& needle) {
833   for (auto i = haystack.size(); i-- > 0; ) {
834     if (haystack[i] == needle) {
835       return i;
836     }
837   }
838   return std::string::npos;
839 }
840
841 // specialization for StringPiece
842 template <>
843 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
844   auto pos = static_cast<const char*>(
845     ::memchr(haystack.data(), needle, haystack.size()));
846   return pos == nullptr ? std::string::npos : pos - haystack.data();
847 }
848
849 #if FOLLY_HAVE_MEMRCHR
850 template <>
851 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
852   auto pos = static_cast<const char*>(
853     ::memrchr(haystack.data(), needle, haystack.size()));
854   return pos == nullptr ? std::string::npos : pos - haystack.data();
855 }
856 #endif
857
858 // specialization for ByteRange
859 template <>
860 inline size_t qfind(const Range<const unsigned char*>& haystack,
861                     const unsigned char& needle) {
862   auto pos = static_cast<const unsigned char*>(
863     ::memchr(haystack.data(), needle, haystack.size()));
864   return pos == nullptr ? std::string::npos : pos - haystack.data();
865 }
866
867 #if FOLLY_HAVE_MEMRCHR
868 template <>
869 inline size_t rfind(const Range<const unsigned char*>& haystack,
870                     const unsigned char& needle) {
871   auto pos = static_cast<const unsigned char*>(
872     ::memrchr(haystack.data(), needle, haystack.size()));
873   return pos == nullptr ? std::string::npos : pos - haystack.data();
874 }
875 #endif
876
877 template <class T>
878 size_t qfind_first_of(const Range<T>& haystack,
879                       const Range<T>& needles) {
880   return qfind_first_of(haystack, needles, asciiCaseSensitive);
881 }
882
883 // specialization for StringPiece
884 template <>
885 inline size_t qfind_first_of(const Range<const char*>& haystack,
886                              const Range<const char*>& needles) {
887   return detail::qfind_first_byte_of(haystack, needles);
888 }
889
890 // specialization for ByteRange
891 template <>
892 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
893                              const Range<const unsigned char*>& needles) {
894   return detail::qfind_first_byte_of(StringPiece(haystack),
895                                      StringPiece(needles));
896 }
897 }  // !namespace folly
898
899 #pragma GCC diagnostic pop
900
901 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);
902
903 #endif // FOLLY_RANGE_H_