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