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