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