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