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