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