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