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