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