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