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