Fix a bad bug in folly::ThreadLocal (incorrect using of pthread)
[folly.git] / folly / Range.h
1 /*
2  * Copyright 2015 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 <folly/SpookyHashV2.h>
26
27 #include <algorithm>
28 #include <boost/operators.hpp>
29 #include <climits>
30 #include <cstring>
31 #include <glog/logging.h>
32 #include <iosfwd>
33 #include <stdexcept>
34 #include <string>
35 #include <type_traits>
36
37 // libc++ doesn't provide this header, nor does msvc
38 #ifdef FOLLY_HAVE_BITS_CXXCONFIG_H
39 // This file appears in two locations: inside fbcode and in the
40 // libstdc++ source code (when embedding fbstring as std::string).
41 // To aid in this schizophrenic use, two macros are defined in
42 // c++config.h:
43 //   _LIBSTDCXX_FBSTRING - Set inside libstdc++.  This is useful to
44 //      gate use inside fbcode v. libstdc++
45 #include <bits/c++config.h>
46 #endif
47
48 #include <folly/CpuId.h>
49 #include <folly/Traits.h>
50 #include <folly/Likely.h>
51
52 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
53 #pragma GCC diagnostic push
54 #pragma GCC diagnostic ignored "-Wshadow"
55
56 namespace folly {
57
58 template <class T> class Range;
59
60 /**
61  * Finds the first occurrence of needle in haystack. The algorithm is on
62  * average faster than O(haystack.size() * needle.size()) but not as fast
63  * as Boyer-Moore. On the upside, it does not do any upfront
64  * preprocessing and does not allocate memory.
65  */
66 template <class T, class Comp = std::equal_to<typename Range<T>::value_type>>
67 inline size_t qfind(const Range<T> & haystack,
68                     const Range<T> & needle,
69                     Comp eq = Comp());
70
71 /**
72  * Finds the first occurrence of needle in haystack. The result is the
73  * offset reported to the beginning of haystack, or string::npos if
74  * needle wasn't found.
75  */
76 template <class T>
77 size_t qfind(const Range<T> & haystack,
78              const typename Range<T>::value_type& needle);
79
80 /**
81  * Finds the last occurrence of needle in haystack. The result is the
82  * offset reported to the beginning of haystack, or string::npos if
83  * needle wasn't found.
84  */
85 template <class T>
86 size_t rfind(const Range<T> & haystack,
87              const typename Range<T>::value_type& needle);
88
89
90 /**
91  * Finds the first occurrence of any element of needle in
92  * haystack. The algorithm is O(haystack.size() * needle.size()).
93  */
94 template <class T>
95 inline size_t qfind_first_of(const Range<T> & haystack,
96                              const Range<T> & needle);
97
98 /**
99  * Small internal helper - returns the value just before an iterator.
100  */
101 namespace detail {
102
103 /**
104  * For random-access iterators, the value before is simply i[-1].
105  */
106 template <class Iter>
107 typename std::enable_if<
108   std::is_same<typename std::iterator_traits<Iter>::iterator_category,
109                std::random_access_iterator_tag>::value,
110   typename std::iterator_traits<Iter>::reference>::type
111 value_before(Iter i) {
112   return i[-1];
113 }
114
115 /**
116  * For all other iterators, we need to use the decrement operator.
117  */
118 template <class Iter>
119 typename std::enable_if<
120   !std::is_same<typename std::iterator_traits<Iter>::iterator_category,
121                 std::random_access_iterator_tag>::value,
122   typename std::iterator_traits<Iter>::reference>::type
123 value_before(Iter i) {
124   return *--i;
125 }
126
127 /*
128  * Use IsCharPointer<T>::type to enable const char* or char*.
129  * Use IsCharPointer<T>::const_type to enable only const char*.
130  */
131 template <class T> struct IsCharPointer {};
132
133 template <>
134 struct IsCharPointer<char*> {
135   typedef int type;
136 };
137
138 template <>
139 struct IsCharPointer<const char*> {
140   typedef int const_type;
141   typedef int type;
142 };
143
144 } // namespace detail
145
146 /**
147  * Range abstraction keeping a pair of iterators. We couldn't use
148  * boost's similar range abstraction because we need an API identical
149  * with the former StringPiece class, which is used by a lot of other
150  * code. This abstraction does fulfill the needs of boost's
151  * range-oriented algorithms though.
152  *
153  * (Keep memory lifetime in mind when using this class, since it
154  * doesn't manage the data it refers to - just like an iterator
155  * wouldn't.)
156  */
157 template <class Iter>
158 class Range : private boost::totally_ordered<Range<Iter> > {
159 public:
160   typedef std::size_t size_type;
161   typedef Iter iterator;
162   typedef Iter const_iterator;
163   typedef typename std::remove_reference<
164     typename std::iterator_traits<Iter>::reference>::type
165   value_type;
166   typedef typename std::iterator_traits<Iter>::reference reference;
167
168   /**
169    * For MutableStringPiece and MutableByteRange we define StringPiece
170    * and ByteRange as const_range_type (for everything else its just
171    * identity). We do that to enable operations such as find with
172    * args which are const.
173    */
174   typedef typename std::conditional<
175     std::is_same<Iter, char*>::value
176       || std::is_same<Iter, unsigned char*>::value,
177     Range<const value_type*>,
178     Range<Iter>>::type const_range_type;
179
180   typedef std::char_traits<typename std::remove_const<value_type>::type>
181     traits_type;
182
183   static const size_type npos;
184
185   // Works for all iterators
186   constexpr Range() : b_(), e_() {
187   }
188
189   constexpr Range(const Range&) = default;
190   constexpr Range(Range&&) = default;
191
192 public:
193   // Works for all iterators
194   constexpr Range(Iter start, Iter end) : b_(start), e_(end) {
195   }
196
197   // Works only for random-access iterators
198   constexpr Range(Iter start, size_t size)
199       : b_(start), e_(start + size) { }
200
201 #if FOLLY_HAVE_CONSTEXPR_STRLEN
202   template <class T = Iter, typename detail::IsCharPointer<T>::type = 0>
203   constexpr /* implicit */ Range(Iter str)
204       : b_(str), e_(str + strlen(str)) {}
205 #else
206   template <class T = Iter, typename detail::IsCharPointer<T>::type = 0>
207   /* implicit */ Range(Iter str)
208       : b_(str), e_(str + strlen(str)) {}
209 #endif
210   template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
211   /* implicit */ Range(const std::string& str)
212       : b_(str.data()), e_(b_ + str.size()) {}
213
214   template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
215   Range(const std::string& str, std::string::size_type startFrom) {
216     if (UNLIKELY(startFrom > str.size())) {
217       throw std::out_of_range("index out of range");
218     }
219     b_ = str.data() + startFrom;
220     e_ = str.data() + str.size();
221   }
222
223   template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
224   Range(const std::string& str,
225         std::string::size_type startFrom,
226         std::string::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   Range(const Range& other,
239         size_type first,
240         size_type length = npos)
241       : Range(other.subpiece(first, length))
242     { }
243
244   template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
245   /* implicit */ Range(const fbstring& str)
246     : b_(str.data()), e_(b_ + str.size()) { }
247
248   template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
249   Range(const fbstring& str, fbstring::size_type startFrom) {
250     if (UNLIKELY(startFrom > str.size())) {
251       throw std::out_of_range("index out of range");
252     }
253     b_ = str.data() + startFrom;
254     e_ = str.data() + str.size();
255   }
256
257   template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
258   Range(const fbstring& str, fbstring::size_type startFrom,
259         fbstring::size_type size) {
260     if (UNLIKELY(startFrom > str.size())) {
261       throw std::out_of_range("index out of range");
262     }
263     b_ = str.data() + startFrom;
264     if (str.size() - startFrom < size) {
265       e_ = str.data() + str.size();
266     } else {
267       e_ = b_ + size;
268     }
269   }
270
271   // Allow implicit conversion from Range<const char*> (aka StringPiece) to
272   // Range<const unsigned char*> (aka ByteRange), as they're both frequently
273   // used to represent ranges of bytes.  Allow explicit conversion in the other
274   // direction.
275   template <class OtherIter, typename std::enable_if<
276       (std::is_same<Iter, const unsigned char*>::value &&
277        (std::is_same<OtherIter, const char*>::value ||
278         std::is_same<OtherIter, char*>::value)), int>::type = 0>
279   /* implicit */ Range(const Range<OtherIter>& other)
280     : b_(reinterpret_cast<const unsigned char*>(other.begin())),
281       e_(reinterpret_cast<const unsigned char*>(other.end())) {
282   }
283
284   template <class OtherIter, typename std::enable_if<
285       (std::is_same<Iter, unsigned char*>::value &&
286        std::is_same<OtherIter, char*>::value), int>::type = 0>
287   /* implicit */ Range(const Range<OtherIter>& other)
288     : b_(reinterpret_cast<unsigned char*>(other.begin())),
289       e_(reinterpret_cast<unsigned char*>(other.end())) {
290   }
291
292   template <class OtherIter, typename std::enable_if<
293       (std::is_same<Iter, const char*>::value &&
294        (std::is_same<OtherIter, const unsigned char*>::value ||
295         std::is_same<OtherIter, unsigned char*>::value)), int>::type = 0>
296   explicit Range(const Range<OtherIter>& other)
297     : b_(reinterpret_cast<const char*>(other.begin())),
298       e_(reinterpret_cast<const char*>(other.end())) {
299   }
300
301   template <class OtherIter, typename std::enable_if<
302       (std::is_same<Iter, char*>::value &&
303        std::is_same<OtherIter, unsigned char*>::value), int>::type = 0>
304   explicit Range(const Range<OtherIter>& other)
305     : b_(reinterpret_cast<char*>(other.begin())),
306       e_(reinterpret_cast<char*>(other.end())) {
307   }
308
309   // Allow implicit conversion from Range<From> to Range<To> if From is
310   // implicitly convertible to To.
311   template <class OtherIter, typename std::enable_if<
312      (!std::is_same<Iter, OtherIter>::value &&
313       std::is_convertible<OtherIter, Iter>::value), int>::type = 0>
314   constexpr /* implicit */ Range(const Range<OtherIter>& other)
315     : b_(other.begin()),
316       e_(other.end()) {
317   }
318
319   // Allow explicit conversion from Range<From> to Range<To> if From is
320   // explicitly convertible to To.
321   template <class OtherIter, typename std::enable_if<
322     (!std::is_same<Iter, OtherIter>::value &&
323      !std::is_convertible<OtherIter, Iter>::value &&
324      std::is_constructible<Iter, const OtherIter&>::value), int>::type = 0>
325   constexpr explicit Range(const Range<OtherIter>& other)
326     : b_(other.begin()),
327       e_(other.end()) {
328   }
329
330   Range& operator=(const Range& rhs) & = default;
331   Range& operator=(Range&& rhs) & = default;
332
333   void clear() {
334     b_ = Iter();
335     e_ = Iter();
336   }
337
338   void assign(Iter start, Iter end) {
339     b_ = start;
340     e_ = end;
341   }
342
343   void reset(Iter start, size_type size) {
344     b_ = start;
345     e_ = start + size;
346   }
347
348   // Works only for Range<const char*>
349   void reset(const std::string& str) {
350     reset(str.data(), str.size());
351   }
352
353   size_type size() const {
354     assert(b_ <= e_);
355     return e_ - b_;
356   }
357   size_type walk_size() const {
358     assert(b_ <= e_);
359     return std::distance(b_, e_);
360   }
361   bool empty() const { return b_ == e_; }
362   Iter data() const { return b_; }
363   Iter start() const { return b_; }
364   Iter begin() const { return b_; }
365   Iter end() const { return e_; }
366   Iter cbegin() const { return b_; }
367   Iter cend() const { return e_; }
368   value_type& front() {
369     assert(b_ < e_);
370     return *b_;
371   }
372   value_type& back() {
373     assert(b_ < e_);
374     return detail::value_before(e_);
375   }
376   const value_type& front() const {
377     assert(b_ < e_);
378     return *b_;
379   }
380   const value_type& back() const {
381     assert(b_ < e_);
382     return detail::value_before(e_);
383   }
384   // Works only for Range<const char*> and Range<char*>
385   std::string str() const { return std::string(b_, size()); }
386   std::string toString() const { return str(); }
387   // Works only for Range<const char*> and Range<char*>
388   fbstring fbstr() const { return fbstring(b_, size()); }
389   fbstring toFbstring() const { return fbstr(); }
390
391   const_range_type castToConst() const {
392     return const_range_type(*this);
393   };
394
395   // Works only for Range<const char*> and Range<char*>
396   int compare(const const_range_type& o) const {
397     const size_type tsize = this->size();
398     const size_type osize = o.size();
399     const size_type msize = std::min(tsize, osize);
400     int r = traits_type::compare(data(), o.data(), msize);
401     if (r == 0 && tsize != osize) {
402       // We check the signed bit of the subtraction and bit shift it
403       // to produce either 0 or 2. The subtraction yields the
404       // comparison values of either -1 or 1.
405       r = (static_cast<int>(
406              (osize - tsize) >> (CHAR_BIT * sizeof(size_t) - 1)) << 1) - 1;
407     }
408     return r;
409   }
410
411   value_type& operator[](size_t i) {
412     DCHECK_GT(size(), i);
413     return b_[i];
414   }
415
416   const value_type& operator[](size_t i) const {
417     DCHECK_GT(size(), i);
418     return b_[i];
419   }
420
421   value_type& at(size_t i) {
422     if (i >= size()) throw std::out_of_range("index out of range");
423     return b_[i];
424   }
425
426   const value_type& at(size_t i) const {
427     if (i >= size()) throw std::out_of_range("index out of range");
428     return b_[i];
429   }
430
431   // Do NOT use this function, which was left behind for backwards
432   // compatibility.  Use SpookyHashV2 instead -- it is faster, and produces
433   // a 64-bit hash, which means dramatically fewer collisions in large maps.
434   // (The above advice does not apply if you are targeting a 32-bit system.)
435   //
436   // Works only for Range<const char*> and Range<char*>
437   uint32_t hash() const {
438     // Taken from fbi/nstring.h:
439     //    Quick and dirty bernstein hash...fine for short ascii strings
440     uint32_t hash = 5381;
441     for (size_t ix = 0; ix < size(); ix++) {
442       hash = ((hash << 5) + hash) + b_[ix];
443     }
444     return hash;
445   }
446
447   void advance(size_type n) {
448     if (UNLIKELY(n > size())) {
449       throw std::out_of_range("index out of range");
450     }
451     b_ += n;
452   }
453
454   void subtract(size_type n) {
455     if (UNLIKELY(n > size())) {
456       throw std::out_of_range("index out of range");
457     }
458     e_ -= n;
459   }
460
461   void pop_front() {
462     assert(b_ < e_);
463     ++b_;
464   }
465
466   void pop_back() {
467     assert(b_ < e_);
468     --e_;
469   }
470
471   Range subpiece(size_type first, size_type length = npos) const {
472     if (UNLIKELY(first > size())) {
473       throw std::out_of_range("index out of range");
474     }
475
476     return Range(b_ + first, std::min(length, size() - first));
477   }
478
479   // string work-alike functions
480   size_type find(const_range_type str) const {
481     return qfind(castToConst(), str);
482   }
483
484   size_type find(const_range_type str, size_t pos) const {
485     if (pos > size()) return std::string::npos;
486     size_t ret = qfind(castToConst().subpiece(pos), str);
487     return ret == npos ? ret : ret + pos;
488   }
489
490   size_type find(Iter s, size_t pos, size_t n) const {
491     if (pos > size()) return std::string::npos;
492     auto forFinding = castToConst();
493     size_t ret = qfind(
494         pos ? forFinding.subpiece(pos) : forFinding, const_range_type(s, n));
495     return ret == npos ? ret : ret + pos;
496   }
497
498   // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
499   size_type find(const Iter s) const {
500     return qfind(castToConst(), const_range_type(s));
501   }
502
503   // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
504   size_type find(const Iter s, size_t pos) const {
505     if (pos > size()) return std::string::npos;
506     size_type ret = qfind(castToConst().subpiece(pos), const_range_type(s));
507     return ret == npos ? ret : ret + pos;
508   }
509
510   size_type find(value_type c) const {
511     return qfind(castToConst(), c);
512   }
513
514   size_type rfind(value_type c) const {
515     return folly::rfind(castToConst(), c);
516   }
517
518   size_type find(value_type c, size_t pos) const {
519     if (pos > size()) return std::string::npos;
520     size_type ret = qfind(castToConst().subpiece(pos), c);
521     return ret == npos ? ret : ret + pos;
522   }
523
524   size_type find_first_of(const_range_type needles) const {
525     return qfind_first_of(castToConst(), needles);
526   }
527
528   size_type find_first_of(const_range_type needles, size_t pos) const {
529     if (pos > size()) return std::string::npos;
530     size_type ret = qfind_first_of(castToConst().subpiece(pos), needles);
531     return ret == npos ? ret : ret + pos;
532   }
533
534   // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
535   size_type find_first_of(Iter needles) const {
536     return find_first_of(const_range_type(needles));
537   }
538
539   // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
540   size_type find_first_of(Iter needles, size_t pos) const {
541     return find_first_of(const_range_type(needles), pos);
542   }
543
544   size_type find_first_of(Iter needles, size_t pos, size_t n) const {
545     return find_first_of(const_range_type(needles, n), pos);
546   }
547
548   size_type find_first_of(value_type c) const {
549     return find(c);
550   }
551
552   size_type find_first_of(value_type c, size_t pos) const {
553     return find(c, pos);
554   }
555
556   /**
557    * Determine whether the range contains the given subrange or item.
558    *
559    * Note: Call find() directly if the index is needed.
560    */
561   bool contains(const const_range_type& other) const {
562     return find(other) != std::string::npos;
563   }
564
565   bool contains(const value_type& other) const {
566     return find(other) != std::string::npos;
567   }
568
569   void swap(Range& rhs) {
570     std::swap(b_, rhs.b_);
571     std::swap(e_, rhs.e_);
572   }
573
574   /**
575    * Does this Range start with another range?
576    */
577   bool startsWith(const const_range_type& other) const {
578     return size() >= other.size()
579       && castToConst().subpiece(0, other.size()) == other;
580   }
581   bool startsWith(value_type c) const {
582     return !empty() && front() == c;
583   }
584
585   /**
586    * Does this Range end with another range?
587    */
588   bool endsWith(const const_range_type& other) const {
589     return size() >= other.size()
590       && castToConst().subpiece(size() - other.size()) == other;
591   }
592   bool endsWith(value_type c) const {
593     return !empty() && back() == c;
594   }
595
596   /**
597    * Remove the given prefix and return true if the range starts with the given
598    * prefix; return false otherwise.
599    */
600   bool removePrefix(const const_range_type& prefix) {
601     return startsWith(prefix) && (b_ += prefix.size(), true);
602   }
603   bool removePrefix(value_type prefix) {
604     return startsWith(prefix) && (++b_, true);
605   }
606
607   /**
608    * Remove the given suffix and return true if the range ends with the given
609    * suffix; return false otherwise.
610    */
611   bool removeSuffix(const const_range_type& suffix) {
612     return endsWith(suffix) && (e_ -= suffix.size(), true);
613   }
614   bool removeSuffix(value_type suffix) {
615     return endsWith(suffix) && (--e_, true);
616   }
617
618   /**
619    * Replaces the content of the range, starting at position 'pos', with
620    * contents of 'replacement'. Entire 'replacement' must fit into the
621    * range. Returns false if 'replacements' does not fit. Example use:
622    *
623    * char in[] = "buffer";
624    * auto msp = MutablesStringPiece(input);
625    * EXPECT_TRUE(msp.replaceAt(2, "tt"));
626    * EXPECT_EQ(msp, "butter");
627    *
628    * // not enough space
629    * EXPECT_FALSE(msp.replace(msp.size() - 1, "rr"));
630    * EXPECT_EQ(msp, "butter"); // unchanged
631    */
632   bool replaceAt(size_t pos, const_range_type replacement) {
633     if (size() < pos + replacement.size()) {
634       return false;
635     }
636
637     std::copy(replacement.begin(), replacement.end(), begin() + pos);
638
639     return true;
640   }
641
642   /**
643    * Replaces all occurences of 'source' with 'dest'. Returns number
644    * of replacements made. Source and dest have to have the same
645    * length. Throws if the lengths are different. If 'source' is a
646    * pattern that is overlapping with itself, we perform sequential
647    * replacement: "aaaaaaa".replaceAll("aa", "ba") --> "bababaa"
648    *
649    * Example use:
650    *
651    * char in[] = "buffer";
652    * auto msp = MutablesStringPiece(input);
653    * EXPECT_EQ(msp.replaceAll("ff","tt"), 1);
654    * EXPECT_EQ(msp, "butter");
655    */
656   size_t replaceAll(const_range_type source, const_range_type dest) {
657     if (source.size() != dest.size()) {
658       throw std::invalid_argument(
659           "replacement must have the same size as source");
660     }
661
662     if (dest.empty()) {
663       return 0;
664     }
665
666     size_t pos = 0;
667     size_t num_replaced = 0;
668     size_type found = std::string::npos;
669     while ((found = find(source, pos)) != std::string::npos) {
670       replaceAt(found, dest);
671       pos += source.size();
672       ++num_replaced;
673     }
674
675     return num_replaced;
676   }
677
678   /**
679    * Splits this `Range` `[b, e)` in the position `i` dictated by the next
680    * occurence of `delimiter`.
681    *
682    * Returns a new `Range` `[b, i)` and adjusts this range to start right after
683    * the delimiter's position. This range will be empty if the delimiter is not
684    * found. If called on an empty `Range`, both this and the returned `Range`
685    * will be empty.
686    *
687    * Example:
688    *
689    *  folly::StringPiece s("sample string for split_next");
690    *  auto p = s.split_step(' ');
691    *
692    *  // prints "string for split_next"
693    *  cout << s << endl;
694    *
695    *  // prints "sample"
696    *  cout << p << endl;
697    *
698    * Example 2:
699    *
700    *  void tokenize(StringPiece s, char delimiter) {
701    *    while (!s.empty()) {
702    *      cout << s.split_step(delimiter);
703    *    }
704    *  }
705    *
706    * @author: Marcelo Juchem <marcelo@fb.com>
707    */
708   Range split_step(value_type delimiter) {
709     auto i = std::find(b_, e_, delimiter);
710     Range result(b_, i);
711
712     b_ = i == e_ ? e_ : std::next(i);
713
714     return result;
715   }
716
717   Range split_step(Range delimiter) {
718     auto i = find(delimiter);
719     Range result(b_, i == std::string::npos ? size() : i);
720
721     b_ = result.end() == e_ ? e_ : std::next(result.end(), delimiter.size());
722
723     return result;
724   }
725
726   /**
727    * Convenience method that calls `split_step()` and passes the result to a
728    * functor, returning whatever the functor does. Any additional arguments
729    * `args` passed to this function are perfectly forwarded to the functor.
730    *
731    * Say you have a functor with this signature:
732    *
733    *  Foo fn(Range r) { }
734    *
735    * `split_step()`'s return type will be `Foo`. It works just like:
736    *
737    *  auto result = fn(myRange.split_step(' '));
738    *
739    * A functor returning `void` is also supported.
740    *
741    * Example:
742    *
743    *  void do_some_parsing(folly::StringPiece s) {
744    *    auto version = s.split_step(' ', [&](folly::StringPiece x) {
745    *      if (x.empty()) {
746    *        throw std::invalid_argument("empty string");
747    *      }
748    *      return std::strtoull(x.begin(), x.end(), 16);
749    *    });
750    *
751    *    // ...
752    *  }
753    *
754    *  struct Foo {
755    *    void parse(folly::StringPiece s) {
756    *      s.split_step(' ', parse_field, bar, 10);
757    *      s.split_step('\t', parse_field, baz, 20);
758    *
759    *      auto const kludge = [](folly::StringPiece x, int &out, int def) {
760    *        if (x == "null") {
761    *          out = 0;
762    *        } else {
763    *          parse_field(x, out, def);
764    *        }
765    *      };
766    *
767    *      s.split_step('\t', kludge, gaz);
768    *      s.split_step(' ', kludge, foo);
769    *    }
770    *
771    *  private:
772    *    int bar;
773    *    int baz;
774    *    int gaz;
775    *    int foo;
776    *
777    *    static parse_field(folly::StringPiece s, int &out, int def) {
778    *      try {
779    *        out = folly::to<int>(s);
780    *      } catch (std::exception const &) {
781    *        value = def;
782    *      }
783    *    }
784    *  };
785    *
786    * @author: Marcelo Juchem <marcelo@fb.com>
787    */
788   template <typename TProcess, typename... Args>
789   auto split_step(value_type delimiter, TProcess &&process, Args &&...args)
790     -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
791   { return process(split_step(delimiter), std::forward<Args>(args)...); }
792
793   template <typename TProcess, typename... Args>
794   auto split_step(Range delimiter, TProcess &&process, Args &&...args)
795     -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
796   { return process(split_step(delimiter), std::forward<Args>(args)...); }
797
798 private:
799   Iter b_, e_;
800 };
801
802 template <class Iter>
803 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
804
805 template <class T>
806 void swap(Range<T>& lhs, Range<T>& rhs) {
807   lhs.swap(rhs);
808 }
809
810 /**
811  * Create a range from two iterators, with type deduction.
812  */
813 template <class Iter>
814 Range<Iter> range(Iter first, Iter last) {
815   return Range<Iter>(first, last);
816 }
817
818 /*
819  * Creates a range to reference the contents of a contiguous-storage container.
820  */
821 // Use pointers for types with '.data()' member
822 template <class Collection,
823           class T = typename std::remove_pointer<
824               decltype(std::declval<Collection>().data())>::type>
825 Range<T*> range(Collection&& v) {
826   return Range<T*>(v.data(), v.data() + v.size());
827 }
828
829 template <class T, size_t n>
830 Range<T*> range(T (&array)[n]) {
831   return Range<T*>(array, array + n);
832 }
833
834 typedef Range<const char*> StringPiece;
835 typedef Range<char*> MutableStringPiece;
836 typedef Range<const unsigned char*> ByteRange;
837 typedef Range<unsigned char*> MutableByteRange;
838
839 inline std::ostream& operator<<(std::ostream& os,
840                                 const StringPiece piece) {
841   os.write(piece.start(), piece.size());
842   return os;
843 }
844
845 inline std::ostream& operator<<(std::ostream& os,
846                                 const MutableStringPiece piece) {
847   os.write(piece.start(), piece.size());
848   return os;
849 }
850
851 /**
852  * Templated comparison operators
853  */
854
855 template <class T>
856 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
857   return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
858 }
859
860 template <class T>
861 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
862   return lhs.compare(rhs) < 0;
863 }
864
865 /**
866  * Specializations of comparison operators for StringPiece
867  */
868
869 namespace detail {
870
871 template <class A, class B>
872 struct ComparableAsStringPiece {
873   enum {
874     value =
875     (std::is_convertible<A, StringPiece>::value
876      && std::is_same<B, StringPiece>::value)
877     ||
878     (std::is_convertible<B, StringPiece>::value
879      && std::is_same<A, StringPiece>::value)
880   };
881 };
882
883 } // namespace detail
884
885 /**
886  * operator== through conversion for Range<const char*>
887  */
888 template <class T, class U>
889 typename
890 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
891 operator==(const T& lhs, const U& rhs) {
892   return StringPiece(lhs) == StringPiece(rhs);
893 }
894
895 /**
896  * operator< through conversion for Range<const char*>
897  */
898 template <class T, class U>
899 typename
900 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
901 operator<(const T& lhs, const U& rhs) {
902   return StringPiece(lhs) < StringPiece(rhs);
903 }
904
905 /**
906  * operator> through conversion for Range<const char*>
907  */
908 template <class T, class U>
909 typename
910 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
911 operator>(const T& lhs, const U& rhs) {
912   return StringPiece(lhs) > StringPiece(rhs);
913 }
914
915 /**
916  * operator< through conversion for Range<const char*>
917  */
918 template <class T, class U>
919 typename
920 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
921 operator<=(const T& lhs, const U& rhs) {
922   return StringPiece(lhs) <= StringPiece(rhs);
923 }
924
925 /**
926  * operator> through conversion for Range<const char*>
927  */
928 template <class T, class U>
929 typename
930 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
931 operator>=(const T& lhs, const U& rhs) {
932   return StringPiece(lhs) >= StringPiece(rhs);
933 }
934
935 // Do NOT use this, use SpookyHashV2 instead, see commment on hash() above.
936 struct StringPieceHash {
937   std::size_t operator()(const StringPiece str) const {
938     return static_cast<std::size_t>(str.hash());
939   }
940 };
941
942 /**
943  * Finds substrings faster than brute force by borrowing from Boyer-Moore
944  */
945 template <class T, class Comp>
946 size_t qfind(const Range<T>& haystack,
947              const Range<T>& needle,
948              Comp eq) {
949   // Don't use std::search, use a Boyer-Moore-like trick by comparing
950   // the last characters first
951   auto const nsize = needle.size();
952   if (haystack.size() < nsize) {
953     return std::string::npos;
954   }
955   if (!nsize) return 0;
956   auto const nsize_1 = nsize - 1;
957   auto const lastNeedle = needle[nsize_1];
958
959   // Boyer-Moore skip value for the last char in the needle. Zero is
960   // not a valid value; skip will be computed the first time it's
961   // needed.
962   std::string::size_type skip = 0;
963
964   auto i = haystack.begin();
965   auto iEnd = haystack.end() - nsize_1;
966
967   while (i < iEnd) {
968     // Boyer-Moore: match the last element in the needle
969     while (!eq(i[nsize_1], lastNeedle)) {
970       if (++i == iEnd) {
971         // not found
972         return std::string::npos;
973       }
974     }
975     // Here we know that the last char matches
976     // Continue in pedestrian mode
977     for (size_t j = 0; ; ) {
978       assert(j < nsize);
979       if (!eq(i[j], needle[j])) {
980         // Not found, we can skip
981         // Compute the skip value lazily
982         if (skip == 0) {
983           skip = 1;
984           while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
985             ++skip;
986           }
987         }
988         i += skip;
989         break;
990       }
991       // Check if done searching
992       if (++j == nsize) {
993         // Yay
994         return i - haystack.begin();
995       }
996     }
997   }
998   return std::string::npos;
999 }
1000
1001 namespace detail {
1002
1003 size_t qfind_first_byte_of_nosse(const StringPiece haystack,
1004                                  const StringPiece needles);
1005
1006 #if FOLLY_HAVE_EMMINTRIN_H && __GNUC_PREREQ(4, 6)
1007 size_t qfind_first_byte_of_sse42(const StringPiece haystack,
1008                                  const StringPiece needles);
1009
1010 inline size_t qfind_first_byte_of(const StringPiece haystack,
1011                                   const StringPiece needles) {
1012   static auto const qfind_first_byte_of_fn =
1013     folly::CpuId().sse42() ? qfind_first_byte_of_sse42
1014                            : qfind_first_byte_of_nosse;
1015   return qfind_first_byte_of_fn(haystack, needles);
1016 }
1017
1018 #else
1019 inline size_t qfind_first_byte_of(const StringPiece haystack,
1020                                   const StringPiece needles) {
1021   return qfind_first_byte_of_nosse(haystack, needles);
1022 }
1023 #endif // FOLLY_HAVE_EMMINTRIN_H
1024
1025 } // namespace detail
1026
1027 template <class T, class Comp>
1028 size_t qfind_first_of(const Range<T> & haystack,
1029                       const Range<T> & needles,
1030                       Comp eq) {
1031   auto ret = std::find_first_of(haystack.begin(), haystack.end(),
1032                                 needles.begin(), needles.end(),
1033                                 eq);
1034   return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
1035 }
1036
1037 struct AsciiCaseSensitive {
1038   bool operator()(char lhs, char rhs) const {
1039     return lhs == rhs;
1040   }
1041 };
1042
1043 /**
1044  * Check if two ascii characters are case insensitive equal.
1045  * The difference between the lower/upper case characters are the 6-th bit.
1046  * We also check they are alpha chars, in case of xor = 32.
1047  */
1048 struct AsciiCaseInsensitive {
1049   bool operator()(char lhs, char rhs) const {
1050     char k = lhs ^ rhs;
1051     if (k == 0) return true;
1052     if (k != 32) return false;
1053     k = lhs | rhs;
1054     return (k >= 'a' && k <= 'z');
1055   }
1056 };
1057
1058 extern const AsciiCaseSensitive asciiCaseSensitive;
1059 extern const AsciiCaseInsensitive asciiCaseInsensitive;
1060
1061 template <class T>
1062 size_t qfind(const Range<T>& haystack,
1063              const typename Range<T>::value_type& needle) {
1064   auto pos = std::find(haystack.begin(), haystack.end(), needle);
1065   return pos == haystack.end() ? std::string::npos : pos - haystack.data();
1066 }
1067
1068 template <class T>
1069 size_t rfind(const Range<T>& haystack,
1070              const typename Range<T>::value_type& needle) {
1071   for (auto i = haystack.size(); i-- > 0; ) {
1072     if (haystack[i] == needle) {
1073       return i;
1074     }
1075   }
1076   return std::string::npos;
1077 }
1078
1079 // specialization for StringPiece
1080 template <>
1081 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
1082   auto pos = static_cast<const char*>(
1083     ::memchr(haystack.data(), needle, haystack.size()));
1084   return pos == nullptr ? std::string::npos : pos - haystack.data();
1085 }
1086
1087 #if FOLLY_HAVE_MEMRCHR
1088 template <>
1089 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
1090   auto pos = static_cast<const char*>(
1091     ::memrchr(haystack.data(), needle, haystack.size()));
1092   return pos == nullptr ? std::string::npos : pos - haystack.data();
1093 }
1094 #endif
1095
1096 // specialization for ByteRange
1097 template <>
1098 inline size_t qfind(const Range<const unsigned char*>& haystack,
1099                     const unsigned char& needle) {
1100   auto pos = static_cast<const unsigned char*>(
1101     ::memchr(haystack.data(), needle, haystack.size()));
1102   return pos == nullptr ? std::string::npos : pos - haystack.data();
1103 }
1104
1105 #if FOLLY_HAVE_MEMRCHR
1106 template <>
1107 inline size_t rfind(const Range<const unsigned char*>& haystack,
1108                     const unsigned char& needle) {
1109   auto pos = static_cast<const unsigned char*>(
1110     ::memrchr(haystack.data(), needle, haystack.size()));
1111   return pos == nullptr ? std::string::npos : pos - haystack.data();
1112 }
1113 #endif
1114
1115 template <class T>
1116 size_t qfind_first_of(const Range<T>& haystack,
1117                       const Range<T>& needles) {
1118   return qfind_first_of(haystack, needles, asciiCaseSensitive);
1119 }
1120
1121 // specialization for StringPiece
1122 template <>
1123 inline size_t qfind_first_of(const Range<const char*>& haystack,
1124                              const Range<const char*>& needles) {
1125   return detail::qfind_first_byte_of(haystack, needles);
1126 }
1127
1128 // specialization for ByteRange
1129 template <>
1130 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
1131                              const Range<const unsigned char*>& needles) {
1132   return detail::qfind_first_byte_of(StringPiece(haystack),
1133                                      StringPiece(needles));
1134 }
1135
1136 template<class Key, class Enable>
1137 struct hasher;
1138
1139 template <class T>
1140 struct hasher<folly::Range<T*>,
1141               typename std::enable_if<std::is_pod<T>::value, void>::type> {
1142   size_t operator()(folly::Range<T*> r) const {
1143     return hash::SpookyHashV2::Hash64(r.begin(), r.size() * sizeof(T), 0);
1144   }
1145 };
1146
1147 }  // !namespace folly
1148
1149 #pragma GCC diagnostic pop
1150
1151 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);
1152
1153 #endif // FOLLY_RANGE_H_