folly: deprecate StringPiece::hash
[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 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 <class Collection,
876           class T = typename std::remove_pointer<
877               decltype(std::declval<Collection>().data())>::type>
878 Range<T*> range(Collection&& v) {
879   return Range<T*>(v.data(), v.data() + v.size());
880 }
881
882 template <class T, size_t n>
883 Range<T*> range(T (&array)[n]) {
884   return Range<T*>(array, array + n);
885 }
886
887 typedef Range<const char*> StringPiece;
888 typedef Range<char*> MutableStringPiece;
889 typedef Range<const unsigned char*> ByteRange;
890 typedef Range<unsigned char*> MutableByteRange;
891
892 inline std::ostream& operator<<(std::ostream& os,
893                                 const StringPiece piece) {
894   os.write(piece.start(), piece.size());
895   return os;
896 }
897
898 inline std::ostream& operator<<(std::ostream& os,
899                                 const MutableStringPiece piece) {
900   os.write(piece.start(), piece.size());
901   return os;
902 }
903
904 /**
905  * Templated comparison operators
906  */
907
908 template <class T>
909 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
910   return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
911 }
912
913 template <class T>
914 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
915   return lhs.compare(rhs) < 0;
916 }
917
918 /**
919  * Specializations of comparison operators for StringPiece
920  */
921
922 namespace detail {
923
924 template <class A, class B>
925 struct ComparableAsStringPiece {
926   enum {
927     value =
928     (std::is_convertible<A, StringPiece>::value
929      && std::is_same<B, StringPiece>::value)
930     ||
931     (std::is_convertible<B, StringPiece>::value
932      && std::is_same<A, StringPiece>::value)
933   };
934 };
935
936 } // namespace detail
937
938 /**
939  * operator== through conversion for Range<const char*>
940  */
941 template <class T, class U>
942 typename
943 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
944 operator==(const T& lhs, const U& rhs) {
945   return StringPiece(lhs) == StringPiece(rhs);
946 }
947
948 /**
949  * operator< through conversion for Range<const char*>
950  */
951 template <class T, class U>
952 typename
953 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
954 operator<(const T& lhs, const U& rhs) {
955   return StringPiece(lhs) < StringPiece(rhs);
956 }
957
958 /**
959  * operator> through conversion for Range<const char*>
960  */
961 template <class T, class U>
962 typename
963 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
964 operator>(const T& lhs, const U& rhs) {
965   return StringPiece(lhs) > StringPiece(rhs);
966 }
967
968 /**
969  * operator< through conversion for Range<const char*>
970  */
971 template <class T, class U>
972 typename
973 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
974 operator<=(const T& lhs, const U& rhs) {
975   return StringPiece(lhs) <= StringPiece(rhs);
976 }
977
978 /**
979  * operator> through conversion for Range<const char*>
980  */
981 template <class T, class U>
982 typename
983 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
984 operator>=(const T& lhs, const U& rhs) {
985   return StringPiece(lhs) >= StringPiece(rhs);
986 }
987
988 /**
989  * Finds substrings faster than brute force by borrowing from Boyer-Moore
990  */
991 template <class T, class Comp>
992 size_t qfind(const Range<T>& haystack,
993              const Range<T>& needle,
994              Comp eq) {
995   // Don't use std::search, use a Boyer-Moore-like trick by comparing
996   // the last characters first
997   auto const nsize = needle.size();
998   if (haystack.size() < nsize) {
999     return std::string::npos;
1000   }
1001   if (!nsize) return 0;
1002   auto const nsize_1 = nsize - 1;
1003   auto const lastNeedle = needle[nsize_1];
1004
1005   // Boyer-Moore skip value for the last char in the needle. Zero is
1006   // not a valid value; skip will be computed the first time it's
1007   // needed.
1008   std::string::size_type skip = 0;
1009
1010   auto i = haystack.begin();
1011   auto iEnd = haystack.end() - nsize_1;
1012
1013   while (i < iEnd) {
1014     // Boyer-Moore: match the last element in the needle
1015     while (!eq(i[nsize_1], lastNeedle)) {
1016       if (++i == iEnd) {
1017         // not found
1018         return std::string::npos;
1019       }
1020     }
1021     // Here we know that the last char matches
1022     // Continue in pedestrian mode
1023     for (size_t j = 0; ; ) {
1024       assert(j < nsize);
1025       if (!eq(i[j], needle[j])) {
1026         // Not found, we can skip
1027         // Compute the skip value lazily
1028         if (skip == 0) {
1029           skip = 1;
1030           while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
1031             ++skip;
1032           }
1033         }
1034         i += skip;
1035         break;
1036       }
1037       // Check if done searching
1038       if (++j == nsize) {
1039         // Yay
1040         return i - haystack.begin();
1041       }
1042     }
1043   }
1044   return std::string::npos;
1045 }
1046
1047 namespace detail {
1048
1049 inline size_t qfind_first_byte_of(const StringPiece haystack,
1050                                   const StringPiece needles) {
1051   static auto const qfind_first_byte_of_fn =
1052     folly::CpuId().sse42() ? qfind_first_byte_of_sse42
1053                            : qfind_first_byte_of_nosse;
1054   return qfind_first_byte_of_fn(haystack, needles);
1055 }
1056
1057 } // namespace detail
1058
1059 template <class T, class Comp>
1060 size_t qfind_first_of(const Range<T> & haystack,
1061                       const Range<T> & needles,
1062                       Comp eq) {
1063   auto ret = std::find_first_of(haystack.begin(), haystack.end(),
1064                                 needles.begin(), needles.end(),
1065                                 eq);
1066   return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
1067 }
1068
1069 struct AsciiCaseSensitive {
1070   bool operator()(char lhs, char rhs) const {
1071     return lhs == rhs;
1072   }
1073 };
1074
1075 /**
1076  * Check if two ascii characters are case insensitive equal.
1077  * The difference between the lower/upper case characters are the 6-th bit.
1078  * We also check they are alpha chars, in case of xor = 32.
1079  */
1080 struct AsciiCaseInsensitive {
1081   bool operator()(char lhs, char rhs) const {
1082     char k = lhs ^ rhs;
1083     if (k == 0) return true;
1084     if (k != 32) return false;
1085     k = lhs | rhs;
1086     return (k >= 'a' && k <= 'z');
1087   }
1088 };
1089
1090 template <class T>
1091 size_t qfind(const Range<T>& haystack,
1092              const typename Range<T>::value_type& needle) {
1093   auto pos = std::find(haystack.begin(), haystack.end(), needle);
1094   return pos == haystack.end() ? std::string::npos : pos - haystack.data();
1095 }
1096
1097 template <class T>
1098 size_t rfind(const Range<T>& haystack,
1099              const typename Range<T>::value_type& needle) {
1100   for (auto i = haystack.size(); i-- > 0; ) {
1101     if (haystack[i] == needle) {
1102       return i;
1103     }
1104   }
1105   return std::string::npos;
1106 }
1107
1108 // specialization for StringPiece
1109 template <>
1110 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
1111   // memchr expects a not-null pointer, early return if the range is empty.
1112   if (haystack.empty()) {
1113     return std::string::npos;
1114   }
1115   auto pos = static_cast<const char*>(
1116     ::memchr(haystack.data(), needle, haystack.size()));
1117   return pos == nullptr ? std::string::npos : pos - haystack.data();
1118 }
1119
1120 template <>
1121 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
1122   // memchr expects a not-null pointer, early return if the range is empty.
1123   if (haystack.empty()) {
1124     return std::string::npos;
1125   }
1126   auto pos = static_cast<const char*>(
1127     ::memrchr(haystack.data(), needle, haystack.size()));
1128   return pos == nullptr ? std::string::npos : pos - haystack.data();
1129 }
1130
1131 // specialization for ByteRange
1132 template <>
1133 inline size_t qfind(const Range<const unsigned char*>& haystack,
1134                     const unsigned char& needle) {
1135   // memchr expects a not-null pointer, early return if the range is empty.
1136   if (haystack.empty()) {
1137     return std::string::npos;
1138   }
1139   auto pos = static_cast<const unsigned char*>(
1140     ::memchr(haystack.data(), needle, haystack.size()));
1141   return pos == nullptr ? std::string::npos : pos - haystack.data();
1142 }
1143
1144 template <>
1145 inline size_t rfind(const Range<const unsigned char*>& haystack,
1146                     const unsigned char& needle) {
1147   // memchr expects a not-null pointer, early return if the range is empty.
1148   if (haystack.empty()) {
1149     return std::string::npos;
1150   }
1151   auto pos = static_cast<const unsigned char*>(
1152     ::memrchr(haystack.data(), needle, haystack.size()));
1153   return pos == nullptr ? std::string::npos : pos - haystack.data();
1154 }
1155
1156 template <class T>
1157 size_t qfind_first_of(const Range<T>& haystack,
1158                       const Range<T>& needles) {
1159   return qfind_first_of(haystack, needles, AsciiCaseSensitive());
1160 }
1161
1162 // specialization for StringPiece
1163 template <>
1164 inline size_t qfind_first_of(const Range<const char*>& haystack,
1165                              const Range<const char*>& needles) {
1166   return detail::qfind_first_byte_of(haystack, needles);
1167 }
1168
1169 // specialization for ByteRange
1170 template <>
1171 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
1172                              const Range<const unsigned char*>& needles) {
1173   return detail::qfind_first_byte_of(StringPiece(haystack),
1174                                      StringPiece(needles));
1175 }
1176
1177 template<class Key, class Enable>
1178 struct hasher;
1179
1180 template <class T>
1181 struct hasher<folly::Range<T*>,
1182               typename std::enable_if<std::is_pod<T>::value, void>::type> {
1183   size_t operator()(folly::Range<T*> r) const {
1184     return hash::SpookyHashV2::Hash64(r.begin(), r.size() * sizeof(T), 0);
1185   }
1186 };
1187
1188 /**
1189  * Ubiquitous helper template for knowing what's a string
1190  */
1191 template <class T> struct IsSomeString {
1192   enum { value = std::is_same<T, std::string>::value
1193          || std::is_same<T, fbstring>::value };
1194 };
1195
1196 }  // !namespace folly
1197
1198 #pragma GCC diagnostic pop
1199
1200 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);