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