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