Refer to nullptr not NULL
[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 FOLLY_PUSH_WARNING
60 FOLLY_GCC_DISABLE_WARNING("-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   template <class Comp>
696   bool equals(const const_range_type& other, Comp&& eq) const {
697     return size() == other.size() &&
698         std::equal(begin(), end(), other.begin(), std::forward<Comp>(eq));
699   }
700
701   /**
702    * Remove the items in [b, e), as long as this subrange is at the beginning
703    * or end of the Range.
704    *
705    * Required for boost::algorithm::trim()
706    */
707   void erase(Iter b, Iter e) {
708     if (b == b_) {
709       b_ = e;
710     } else if (e == e_) {
711       e_ = b;
712     } else {
713       std::__throw_out_of_range("index out of range");
714     }
715   }
716
717   /**
718    * Remove the given prefix and return true if the range starts with the given
719    * prefix; return false otherwise.
720    */
721   bool removePrefix(const const_range_type& prefix) {
722     return startsWith(prefix) && (b_ += prefix.size(), true);
723   }
724   bool removePrefix(value_type prefix) {
725     return startsWith(prefix) && (++b_, true);
726   }
727
728   /**
729    * Remove the given suffix and return true if the range ends with the given
730    * suffix; return false otherwise.
731    */
732   bool removeSuffix(const const_range_type& suffix) {
733     return endsWith(suffix) && (e_ -= suffix.size(), true);
734   }
735   bool removeSuffix(value_type suffix) {
736     return endsWith(suffix) && (--e_, true);
737   }
738
739   /**
740    * Replaces the content of the range, starting at position 'pos', with
741    * contents of 'replacement'. Entire 'replacement' must fit into the
742    * range. Returns false if 'replacements' does not fit. Example use:
743    *
744    * char in[] = "buffer";
745    * auto msp = MutablesStringPiece(input);
746    * EXPECT_TRUE(msp.replaceAt(2, "tt"));
747    * EXPECT_EQ(msp, "butter");
748    *
749    * // not enough space
750    * EXPECT_FALSE(msp.replace(msp.size() - 1, "rr"));
751    * EXPECT_EQ(msp, "butter"); // unchanged
752    */
753   bool replaceAt(size_t pos, const_range_type replacement) {
754     if (size() < pos + replacement.size()) {
755       return false;
756     }
757
758     std::copy(replacement.begin(), replacement.end(), begin() + pos);
759
760     return true;
761   }
762
763   /**
764    * Replaces all occurences of 'source' with 'dest'. Returns number
765    * of replacements made. Source and dest have to have the same
766    * length. Throws if the lengths are different. If 'source' is a
767    * pattern that is overlapping with itself, we perform sequential
768    * replacement: "aaaaaaa".replaceAll("aa", "ba") --> "bababaa"
769    *
770    * Example use:
771    *
772    * char in[] = "buffer";
773    * auto msp = MutablesStringPiece(input);
774    * EXPECT_EQ(msp.replaceAll("ff","tt"), 1);
775    * EXPECT_EQ(msp, "butter");
776    */
777   size_t replaceAll(const_range_type source, const_range_type dest) {
778     if (source.size() != dest.size()) {
779       throw std::invalid_argument(
780           "replacement must have the same size as source");
781     }
782
783     if (dest.empty()) {
784       return 0;
785     }
786
787     size_t pos = 0;
788     size_t num_replaced = 0;
789     size_type found = std::string::npos;
790     while ((found = find(source, pos)) != std::string::npos) {
791       replaceAt(found, dest);
792       pos += source.size();
793       ++num_replaced;
794     }
795
796     return num_replaced;
797   }
798
799   /**
800    * Splits this `Range` `[b, e)` in the position `i` dictated by the next
801    * occurence of `delimiter`.
802    *
803    * Returns a new `Range` `[b, i)` and adjusts this range to start right after
804    * the delimiter's position. This range will be empty if the delimiter is not
805    * found. If called on an empty `Range`, both this and the returned `Range`
806    * will be empty.
807    *
808    * Example:
809    *
810    *  folly::StringPiece s("sample string for split_next");
811    *  auto p = s.split_step(' ');
812    *
813    *  // prints "string for split_next"
814    *  cout << s << endl;
815    *
816    *  // prints "sample"
817    *  cout << p << endl;
818    *
819    * Example 2:
820    *
821    *  void tokenize(StringPiece s, char delimiter) {
822    *    while (!s.empty()) {
823    *      cout << s.split_step(delimiter);
824    *    }
825    *  }
826    *
827    * @author: Marcelo Juchem <marcelo@fb.com>
828    */
829   Range split_step(value_type delimiter) {
830     auto i = std::find(b_, e_, delimiter);
831     Range result(b_, i);
832
833     b_ = i == e_ ? e_ : std::next(i);
834
835     return result;
836   }
837
838   Range split_step(Range delimiter) {
839     auto i = find(delimiter);
840     Range result(b_, i == std::string::npos ? size() : i);
841
842     b_ = result.end() == e_
843         ? e_
844         : std::next(
845               result.end(),
846               typename std::iterator_traits<Iter>::difference_type(
847                   delimiter.size()));
848
849     return result;
850   }
851
852   /**
853    * Convenience method that calls `split_step()` and passes the result to a
854    * functor, returning whatever the functor does. Any additional arguments
855    * `args` passed to this function are perfectly forwarded to the functor.
856    *
857    * Say you have a functor with this signature:
858    *
859    *  Foo fn(Range r) { }
860    *
861    * `split_step()`'s return type will be `Foo`. It works just like:
862    *
863    *  auto result = fn(myRange.split_step(' '));
864    *
865    * A functor returning `void` is also supported.
866    *
867    * Example:
868    *
869    *  void do_some_parsing(folly::StringPiece s) {
870    *    auto version = s.split_step(' ', [&](folly::StringPiece x) {
871    *      if (x.empty()) {
872    *        throw std::invalid_argument("empty string");
873    *      }
874    *      return std::strtoull(x.begin(), x.end(), 16);
875    *    });
876    *
877    *    // ...
878    *  }
879    *
880    *  struct Foo {
881    *    void parse(folly::StringPiece s) {
882    *      s.split_step(' ', parse_field, bar, 10);
883    *      s.split_step('\t', parse_field, baz, 20);
884    *
885    *      auto const kludge = [](folly::StringPiece x, int &out, int def) {
886    *        if (x == "null") {
887    *          out = 0;
888    *        } else {
889    *          parse_field(x, out, def);
890    *        }
891    *      };
892    *
893    *      s.split_step('\t', kludge, gaz);
894    *      s.split_step(' ', kludge, foo);
895    *    }
896    *
897    *  private:
898    *    int bar;
899    *    int baz;
900    *    int gaz;
901    *    int foo;
902    *
903    *    static parse_field(folly::StringPiece s, int &out, int def) {
904    *      try {
905    *        out = folly::to<int>(s);
906    *      } catch (std::exception const &) {
907    *        value = def;
908    *      }
909    *    }
910    *  };
911    *
912    * @author: Marcelo Juchem <marcelo@fb.com>
913    */
914   template <typename TProcess, typename... Args>
915   auto split_step(value_type delimiter, TProcess &&process, Args &&...args)
916     -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
917   { return process(split_step(delimiter), std::forward<Args>(args)...); }
918
919   template <typename TProcess, typename... Args>
920   auto split_step(Range delimiter, TProcess &&process, Args &&...args)
921     -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
922   { return process(split_step(delimiter), std::forward<Args>(args)...); }
923
924 private:
925   Iter b_, e_;
926 };
927
928 template <class Iter>
929 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
930
931 template <class Iter>
932 void swap(Range<Iter>& lhs, Range<Iter>& rhs) {
933   lhs.swap(rhs);
934 }
935
936 /**
937  * Create a range from two iterators, with type deduction.
938  */
939 template <class Iter>
940 constexpr Range<Iter> range(Iter first, Iter last) {
941   return Range<Iter>(first, last);
942 }
943
944 /*
945  * Creates a range to reference the contents of a contiguous-storage container.
946  */
947 // Use pointers for types with '.data()' member
948 template <
949     class Collection,
950     class T = typename std::remove_pointer<
951         decltype(std::declval<Collection>().data())>::type>
952 constexpr Range<T*> range(Collection&& v) {
953   return Range<T*>(v.data(), v.data() + v.size());
954 }
955
956 template <class T, size_t n>
957 constexpr Range<T*> range(T (&array)[n]) {
958   return Range<T*>(array, array + n);
959 }
960
961 template <class T, size_t n>
962 constexpr Range<const T*> range(const std::array<T, n>& array) {
963   return Range<const T*>{array};
964 }
965
966 typedef Range<const char*> StringPiece;
967 typedef Range<char*> MutableStringPiece;
968 typedef Range<const unsigned char*> ByteRange;
969 typedef Range<unsigned char*> MutableByteRange;
970
971 inline std::ostream& operator<<(std::ostream& os,
972                                 const StringPiece piece) {
973   os.write(piece.start(), std::streamsize(piece.size()));
974   return os;
975 }
976
977 inline std::ostream& operator<<(std::ostream& os,
978                                 const MutableStringPiece piece) {
979   os.write(piece.start(), std::streamsize(piece.size()));
980   return os;
981 }
982
983 /**
984  * Templated comparison operators
985  */
986
987 template <class Iter>
988 inline bool operator==(const Range<Iter>& lhs, const Range<Iter>& rhs) {
989   return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
990 }
991
992 template <class Iter>
993 inline bool operator<(const Range<Iter>& lhs, const Range<Iter>& rhs) {
994   return lhs.compare(rhs) < 0;
995 }
996
997 /**
998  * Specializations of comparison operators for StringPiece
999  */
1000
1001 namespace detail {
1002
1003 template <class A, class B>
1004 struct ComparableAsStringPiece {
1005   enum {
1006     value =
1007     (std::is_convertible<A, StringPiece>::value
1008      && std::is_same<B, StringPiece>::value)
1009     ||
1010     (std::is_convertible<B, StringPiece>::value
1011      && std::is_same<A, StringPiece>::value)
1012   };
1013 };
1014
1015 } // namespace detail
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  * operator> through conversion for Range<const char*>
1059  */
1060 template <class T, class U>
1061 typename
1062 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
1063 operator>=(const T& lhs, const U& rhs) {
1064   return StringPiece(lhs) >= StringPiece(rhs);
1065 }
1066
1067 /**
1068  * Finds substrings faster than brute force by borrowing from Boyer-Moore
1069  */
1070 template <class Iter, class Comp>
1071 size_t qfind(const Range<Iter>& haystack,
1072              const Range<Iter>& needle,
1073              Comp eq) {
1074   // Don't use std::search, use a Boyer-Moore-like trick by comparing
1075   // the last characters first
1076   auto const nsize = needle.size();
1077   if (haystack.size() < nsize) {
1078     return std::string::npos;
1079   }
1080   if (!nsize) return 0;
1081   auto const nsize_1 = nsize - 1;
1082   auto const lastNeedle = needle[nsize_1];
1083
1084   // Boyer-Moore skip value for the last char in the needle. Zero is
1085   // not a valid value; skip will be computed the first time it's
1086   // needed.
1087   std::string::size_type skip = 0;
1088
1089   auto i = haystack.begin();
1090   auto iEnd = haystack.end() - nsize_1;
1091
1092   while (i < iEnd) {
1093     // Boyer-Moore: match the last element in the needle
1094     while (!eq(i[nsize_1], lastNeedle)) {
1095       if (++i == iEnd) {
1096         // not found
1097         return std::string::npos;
1098       }
1099     }
1100     // Here we know that the last char matches
1101     // Continue in pedestrian mode
1102     for (size_t j = 0; ; ) {
1103       assert(j < nsize);
1104       if (!eq(i[j], needle[j])) {
1105         // Not found, we can skip
1106         // Compute the skip value lazily
1107         if (skip == 0) {
1108           skip = 1;
1109           while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
1110             ++skip;
1111           }
1112         }
1113         i += skip;
1114         break;
1115       }
1116       // Check if done searching
1117       if (++j == nsize) {
1118         // Yay
1119         return size_t(i - haystack.begin());
1120       }
1121     }
1122   }
1123   return std::string::npos;
1124 }
1125
1126 namespace detail {
1127
1128 inline size_t qfind_first_byte_of(const StringPiece haystack,
1129                                   const StringPiece needles) {
1130   static auto const qfind_first_byte_of_fn =
1131     folly::CpuId().sse42() ? qfind_first_byte_of_sse42
1132                            : qfind_first_byte_of_nosse;
1133   return qfind_first_byte_of_fn(haystack, needles);
1134 }
1135
1136 } // namespace detail
1137
1138 template <class Iter, class Comp>
1139 size_t qfind_first_of(const Range<Iter> & haystack,
1140                       const Range<Iter> & needles,
1141                       Comp eq) {
1142   auto ret = std::find_first_of(haystack.begin(), haystack.end(),
1143                                 needles.begin(), needles.end(),
1144                                 eq);
1145   return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
1146 }
1147
1148 struct AsciiCaseSensitive {
1149   bool operator()(char lhs, char rhs) const {
1150     return lhs == rhs;
1151   }
1152 };
1153
1154 /**
1155  * Check if two ascii characters are case insensitive equal.
1156  * The difference between the lower/upper case characters are the 6-th bit.
1157  * We also check they are alpha chars, in case of xor = 32.
1158  */
1159 struct AsciiCaseInsensitive {
1160   bool operator()(char lhs, char rhs) const {
1161     char k = lhs ^ rhs;
1162     if (k == 0) return true;
1163     if (k != 32) return false;
1164     k = lhs | rhs;
1165     return (k >= 'a' && k <= 'z');
1166   }
1167 };
1168
1169 template <class Iter>
1170 size_t qfind(const Range<Iter>& haystack,
1171              const typename Range<Iter>::value_type& needle) {
1172   auto pos = std::find(haystack.begin(), haystack.end(), needle);
1173   return pos == haystack.end() ? std::string::npos : pos - haystack.data();
1174 }
1175
1176 template <class Iter>
1177 size_t rfind(const Range<Iter>& haystack,
1178              const typename Range<Iter>::value_type& needle) {
1179   for (auto i = haystack.size(); i-- > 0; ) {
1180     if (haystack[i] == needle) {
1181       return i;
1182     }
1183   }
1184   return std::string::npos;
1185 }
1186
1187 // specialization for StringPiece
1188 template <>
1189 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
1190   // memchr expects a not-null pointer, early return if the range is empty.
1191   if (haystack.empty()) {
1192     return std::string::npos;
1193   }
1194   auto pos = static_cast<const char*>(
1195     ::memchr(haystack.data(), needle, haystack.size()));
1196   return pos == nullptr ? std::string::npos : pos - haystack.data();
1197 }
1198
1199 template <>
1200 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
1201   // memchr expects a not-null pointer, early return if the range is empty.
1202   if (haystack.empty()) {
1203     return std::string::npos;
1204   }
1205   auto pos = static_cast<const char*>(
1206     ::memrchr(haystack.data(), needle, haystack.size()));
1207   return pos == nullptr ? std::string::npos : pos - haystack.data();
1208 }
1209
1210 // specialization for ByteRange
1211 template <>
1212 inline size_t qfind(const Range<const unsigned char*>& haystack,
1213                     const unsigned char& needle) {
1214   // memchr expects a not-null pointer, early return if the range is empty.
1215   if (haystack.empty()) {
1216     return std::string::npos;
1217   }
1218   auto pos = static_cast<const unsigned char*>(
1219     ::memchr(haystack.data(), needle, haystack.size()));
1220   return pos == nullptr ? std::string::npos : pos - haystack.data();
1221 }
1222
1223 template <>
1224 inline size_t rfind(const Range<const unsigned char*>& haystack,
1225                     const unsigned char& needle) {
1226   // memchr expects a not-null pointer, early return if the range is empty.
1227   if (haystack.empty()) {
1228     return std::string::npos;
1229   }
1230   auto pos = static_cast<const unsigned char*>(
1231     ::memrchr(haystack.data(), needle, haystack.size()));
1232   return pos == nullptr ? std::string::npos : pos - haystack.data();
1233 }
1234
1235 template <class Iter>
1236 size_t qfind_first_of(const Range<Iter>& haystack,
1237                       const Range<Iter>& needles) {
1238   return qfind_first_of(haystack, needles, AsciiCaseSensitive());
1239 }
1240
1241 // specialization for StringPiece
1242 template <>
1243 inline size_t qfind_first_of(const Range<const char*>& haystack,
1244                              const Range<const char*>& needles) {
1245   return detail::qfind_first_byte_of(haystack, needles);
1246 }
1247
1248 // specialization for ByteRange
1249 template <>
1250 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
1251                              const Range<const unsigned char*>& needles) {
1252   return detail::qfind_first_byte_of(StringPiece(haystack),
1253                                      StringPiece(needles));
1254 }
1255
1256 template<class Key, class Enable>
1257 struct hasher;
1258
1259 template <class T>
1260 struct hasher<folly::Range<T*>,
1261               typename std::enable_if<std::is_pod<T>::value, void>::type> {
1262   size_t operator()(folly::Range<T*> r) const {
1263     return hash::SpookyHashV2::Hash64(r.begin(), r.size() * sizeof(T), 0);
1264   }
1265 };
1266
1267 /**
1268  * Ubiquitous helper template for knowing what's a string
1269  */
1270 template <class T> struct IsSomeString {
1271   enum { value = std::is_same<T, std::string>::value
1272          || std::is_same<T, fbstring>::value };
1273 };
1274
1275 }  // !namespace folly
1276
1277 FOLLY_POP_WARNING
1278
1279 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);