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