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