update FunctionScheduler to use std::chrono::steady_clock
[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   // Do NOT use this function, which was left behind for backwards
430   // compatibility.  Use SpookyHashV2 instead -- it is faster, and produces
431   // a 64-bit hash, which means dramatically fewer collisions in large maps.
432   // (The above advice does not apply if you are targeting a 32-bit system.)
433   //
434   // Works only for Range<const char*> and Range<char*>
435   uint32_t hash() const {
436     // Taken from fbi/nstring.h:
437     //    Quick and dirty bernstein hash...fine for short ascii strings
438     uint32_t hash = 5381;
439     for (size_t ix = 0; ix < size(); ix++) {
440       hash = ((hash << 5) + hash) + b_[ix];
441     }
442     return hash;
443   }
444
445   void advance(size_type n) {
446     if (UNLIKELY(n > size())) {
447       throw std::out_of_range("index out of range");
448     }
449     b_ += n;
450   }
451
452   void subtract(size_type n) {
453     if (UNLIKELY(n > size())) {
454       throw std::out_of_range("index out of range");
455     }
456     e_ -= n;
457   }
458
459   void pop_front() {
460     assert(b_ < e_);
461     ++b_;
462   }
463
464   void pop_back() {
465     assert(b_ < e_);
466     --e_;
467   }
468
469   Range subpiece(size_type first, size_type length = npos) const {
470     if (UNLIKELY(first > size())) {
471       throw std::out_of_range("index out of range");
472     }
473
474     return Range(b_ + first, std::min(length, size() - first));
475   }
476
477   // string work-alike functions
478   size_type find(const_range_type str) const {
479     return qfind(castToConst(), str);
480   }
481
482   size_type find(const_range_type str, size_t pos) const {
483     if (pos > size()) return std::string::npos;
484     size_t ret = qfind(castToConst().subpiece(pos), str);
485     return ret == npos ? ret : ret + pos;
486   }
487
488   size_type find(Iter s, size_t pos, size_t n) const {
489     if (pos > size()) return std::string::npos;
490     auto forFinding = castToConst();
491     size_t ret = qfind(
492         pos ? forFinding.subpiece(pos) : forFinding, const_range_type(s, n));
493     return ret == npos ? ret : ret + pos;
494   }
495
496   // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
497   size_type find(const Iter s) const {
498     return qfind(castToConst(), const_range_type(s));
499   }
500
501   // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
502   size_type find(const Iter s, size_t pos) const {
503     if (pos > size()) return std::string::npos;
504     size_type ret = qfind(castToConst().subpiece(pos), const_range_type(s));
505     return ret == npos ? ret : ret + pos;
506   }
507
508   size_type find(value_type c) const {
509     return qfind(castToConst(), c);
510   }
511
512   size_type rfind(value_type c) const {
513     return folly::rfind(castToConst(), c);
514   }
515
516   size_type find(value_type c, size_t pos) const {
517     if (pos > size()) return std::string::npos;
518     size_type ret = qfind(castToConst().subpiece(pos), c);
519     return ret == npos ? ret : ret + pos;
520   }
521
522   size_type find_first_of(const_range_type needles) const {
523     return qfind_first_of(castToConst(), needles);
524   }
525
526   size_type find_first_of(const_range_type needles, size_t pos) const {
527     if (pos > size()) return std::string::npos;
528     size_type ret = qfind_first_of(castToConst().subpiece(pos), needles);
529     return ret == npos ? ret : ret + pos;
530   }
531
532   // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
533   size_type find_first_of(Iter needles) const {
534     return find_first_of(const_range_type(needles));
535   }
536
537   // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
538   size_type find_first_of(Iter needles, size_t pos) const {
539     return find_first_of(const_range_type(needles), pos);
540   }
541
542   size_type find_first_of(Iter needles, size_t pos, size_t n) const {
543     return find_first_of(const_range_type(needles, n), pos);
544   }
545
546   size_type find_first_of(value_type c) const {
547     return find(c);
548   }
549
550   size_type find_first_of(value_type c, size_t pos) const {
551     return find(c, pos);
552   }
553
554   /**
555    * Determine whether the range contains the given subrange or item.
556    *
557    * Note: Call find() directly if the index is needed.
558    */
559   bool contains(const const_range_type& other) const {
560     return find(other) != std::string::npos;
561   }
562
563   bool contains(const value_type& other) const {
564     return find(other) != std::string::npos;
565   }
566
567   void swap(Range& rhs) {
568     std::swap(b_, rhs.b_);
569     std::swap(e_, rhs.e_);
570   }
571
572   /**
573    * Does this Range start with another range?
574    */
575   bool startsWith(const const_range_type& other) const {
576     return size() >= other.size()
577       && castToConst().subpiece(0, other.size()) == other;
578   }
579   bool startsWith(value_type c) const {
580     return !empty() && front() == c;
581   }
582
583   /**
584    * Does this Range end with another range?
585    */
586   bool endsWith(const const_range_type& other) const {
587     return size() >= other.size()
588       && castToConst().subpiece(size() - other.size()) == other;
589   }
590   bool endsWith(value_type c) const {
591     return !empty() && back() == c;
592   }
593
594   /**
595    * Remove the given prefix and return true if the range starts with the given
596    * prefix; return false otherwise.
597    */
598   bool removePrefix(const const_range_type& prefix) {
599     return startsWith(prefix) && (b_ += prefix.size(), true);
600   }
601   bool removePrefix(value_type prefix) {
602     return startsWith(prefix) && (++b_, true);
603   }
604
605   /**
606    * Remove the given suffix and return true if the range ends with the given
607    * suffix; return false otherwise.
608    */
609   bool removeSuffix(const const_range_type& suffix) {
610     return endsWith(suffix) && (e_ -= suffix.size(), true);
611   }
612   bool removeSuffix(value_type suffix) {
613     return endsWith(suffix) && (--e_, true);
614   }
615
616   /**
617    * Replaces the content of the range, starting at position 'pos', with
618    * contents of 'replacement'. Entire 'replacement' must fit into the
619    * range. Returns false if 'replacements' does not fit. Example use:
620    *
621    * char in[] = "buffer";
622    * auto msp = MutablesStringPiece(input);
623    * EXPECT_TRUE(msp.replaceAt(2, "tt"));
624    * EXPECT_EQ(msp, "butter");
625    *
626    * // not enough space
627    * EXPECT_FALSE(msp.replace(msp.size() - 1, "rr"));
628    * EXPECT_EQ(msp, "butter"); // unchanged
629    */
630   bool replaceAt(size_t pos, const_range_type replacement) {
631     if (size() < pos + replacement.size()) {
632       return false;
633     }
634
635     std::copy(replacement.begin(), replacement.end(), begin() + pos);
636
637     return true;
638   }
639
640   /**
641    * Replaces all occurences of 'source' with 'dest'. Returns number
642    * of replacements made. Source and dest have to have the same
643    * length. Throws if the lengths are different. If 'source' is a
644    * pattern that is overlapping with itself, we perform sequential
645    * replacement: "aaaaaaa".replaceAll("aa", "ba") --> "bababaa"
646    *
647    * Example use:
648    *
649    * char in[] = "buffer";
650    * auto msp = MutablesStringPiece(input);
651    * EXPECT_EQ(msp.replaceAll("ff","tt"), 1);
652    * EXPECT_EQ(msp, "butter");
653    */
654   size_t replaceAll(const_range_type source, const_range_type dest) {
655     if (source.size() != dest.size()) {
656       throw std::invalid_argument(
657           "replacement must have the same size as source");
658     }
659
660     if (dest.empty()) {
661       return 0;
662     }
663
664     size_t pos = 0;
665     size_t num_replaced = 0;
666     size_type found = std::string::npos;
667     while ((found = find(source, pos)) != std::string::npos) {
668       replaceAt(found, dest);
669       pos += source.size();
670       ++num_replaced;
671     }
672
673     return num_replaced;
674   }
675
676   /**
677    * Splits this `Range` `[b, e)` in the position `i` dictated by the next
678    * occurence of `delimiter`.
679    *
680    * Returns a new `Range` `[b, i)` and adjusts this range to start right after
681    * the delimiter's position. This range will be empty if the delimiter is not
682    * found. If called on an empty `Range`, both this and the returned `Range`
683    * will be empty.
684    *
685    * Example:
686    *
687    *  folly::StringPiece s("sample string for split_next");
688    *  auto p = s.split_step(' ');
689    *
690    *  // prints "string for split_next"
691    *  cout << s << endl;
692    *
693    *  // prints "sample"
694    *  cout << p << endl;
695    *
696    * Example 2:
697    *
698    *  void tokenize(StringPiece s, char delimiter) {
699    *    while (!s.empty()) {
700    *      cout << s.split_step(delimiter);
701    *    }
702    *  }
703    *
704    * @author: Marcelo Juchem <marcelo@fb.com>
705    */
706   Range split_step(value_type delimiter) {
707     auto i = std::find(b_, e_, delimiter);
708     Range result(b_, i);
709
710     b_ = i == e_ ? e_ : std::next(i);
711
712     return result;
713   }
714
715   Range split_step(Range delimiter) {
716     auto i = find(delimiter);
717     Range result(b_, i == std::string::npos ? size() : i);
718
719     b_ = result.end() == e_ ? e_ : std::next(result.end(), delimiter.size());
720
721     return result;
722   }
723
724   /**
725    * Convenience method that calls `split_step()` and passes the result to a
726    * functor, returning whatever the functor does. Any additional arguments
727    * `args` passed to this function are perfectly forwarded to the functor.
728    *
729    * Say you have a functor with this signature:
730    *
731    *  Foo fn(Range r) { }
732    *
733    * `split_step()`'s return type will be `Foo`. It works just like:
734    *
735    *  auto result = fn(myRange.split_step(' '));
736    *
737    * A functor returning `void` is also supported.
738    *
739    * Example:
740    *
741    *  void do_some_parsing(folly::StringPiece s) {
742    *    auto version = s.split_step(' ', [&](folly::StringPiece x) {
743    *      if (x.empty()) {
744    *        throw std::invalid_argument("empty string");
745    *      }
746    *      return std::strtoull(x.begin(), x.end(), 16);
747    *    });
748    *
749    *    // ...
750    *  }
751    *
752    *  struct Foo {
753    *    void parse(folly::StringPiece s) {
754    *      s.split_step(' ', parse_field, bar, 10);
755    *      s.split_step('\t', parse_field, baz, 20);
756    *
757    *      auto const kludge = [](folly::StringPiece x, int &out, int def) {
758    *        if (x == "null") {
759    *          out = 0;
760    *        } else {
761    *          parse_field(x, out, def);
762    *        }
763    *      };
764    *
765    *      s.split_step('\t', kludge, gaz);
766    *      s.split_step(' ', kludge, foo);
767    *    }
768    *
769    *  private:
770    *    int bar;
771    *    int baz;
772    *    int gaz;
773    *    int foo;
774    *
775    *    static parse_field(folly::StringPiece s, int &out, int def) {
776    *      try {
777    *        out = folly::to<int>(s);
778    *      } catch (std::exception const &) {
779    *        value = def;
780    *      }
781    *    }
782    *  };
783    *
784    * @author: Marcelo Juchem <marcelo@fb.com>
785    */
786   template <typename TProcess, typename... Args>
787   auto split_step(value_type 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   template <typename TProcess, typename... Args>
792   auto split_step(Range delimiter, TProcess &&process, Args &&...args)
793     -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
794   { return process(split_step(delimiter), std::forward<Args>(args)...); }
795
796 private:
797   Iter b_, e_;
798 };
799
800 template <class Iter>
801 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
802
803 template <class T>
804 void swap(Range<T>& lhs, Range<T>& rhs) {
805   lhs.swap(rhs);
806 }
807
808 /**
809  * Create a range from two iterators, with type deduction.
810  */
811 template <class Iter>
812 Range<Iter> range(Iter first, Iter last) {
813   return Range<Iter>(first, last);
814 }
815
816 /*
817  * Creates a range to reference the contents of a contiguous-storage container.
818  */
819 // Use pointers for types with '.data()' member
820 template <class Collection,
821           class T = typename std::remove_pointer<
822               decltype(std::declval<Collection>().data())>::type>
823 Range<T*> range(Collection&& v) {
824   return Range<T*>(v.data(), v.data() + v.size());
825 }
826
827 template <class T, size_t n>
828 Range<T*> range(T (&array)[n]) {
829   return Range<T*>(array, array + n);
830 }
831
832 typedef Range<const char*> StringPiece;
833 typedef Range<char*> MutableStringPiece;
834 typedef Range<const unsigned char*> ByteRange;
835 typedef Range<unsigned char*> MutableByteRange;
836
837 std::ostream& operator<<(std::ostream& os, const StringPiece piece);
838 std::ostream& operator<<(std::ostream& os, const MutableStringPiece piece);
839
840 /**
841  * Templated comparison operators
842  */
843
844 template <class T>
845 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
846   return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
847 }
848
849 template <class T>
850 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
851   return lhs.compare(rhs) < 0;
852 }
853
854 /**
855  * Specializations of comparison operators for StringPiece
856  */
857
858 namespace detail {
859
860 template <class A, class B>
861 struct ComparableAsStringPiece {
862   enum {
863     value =
864     (std::is_convertible<A, StringPiece>::value
865      && std::is_same<B, StringPiece>::value)
866     ||
867     (std::is_convertible<B, StringPiece>::value
868      && std::is_same<A, StringPiece>::value)
869   };
870 };
871
872 } // namespace detail
873
874 /**
875  * operator== through conversion for Range<const char*>
876  */
877 template <class T, class U>
878 typename
879 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
880 operator==(const T& lhs, const U& rhs) {
881   return StringPiece(lhs) == StringPiece(rhs);
882 }
883
884 /**
885  * operator< through conversion for Range<const char*>
886  */
887 template <class T, class U>
888 typename
889 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
890 operator<(const T& lhs, const U& rhs) {
891   return StringPiece(lhs) < StringPiece(rhs);
892 }
893
894 /**
895  * operator> through conversion for Range<const char*>
896  */
897 template <class T, class U>
898 typename
899 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
900 operator>(const T& lhs, const U& rhs) {
901   return StringPiece(lhs) > StringPiece(rhs);
902 }
903
904 /**
905  * operator< through conversion for Range<const char*>
906  */
907 template <class T, class U>
908 typename
909 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
910 operator<=(const T& lhs, const U& rhs) {
911   return StringPiece(lhs) <= StringPiece(rhs);
912 }
913
914 /**
915  * operator> through conversion for Range<const char*>
916  */
917 template <class T, class U>
918 typename
919 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
920 operator>=(const T& lhs, const U& rhs) {
921   return StringPiece(lhs) >= StringPiece(rhs);
922 }
923
924 // Do NOT use this, use SpookyHashV2 instead, see commment on hash() above.
925 struct StringPieceHash {
926   std::size_t operator()(const StringPiece str) const {
927     return static_cast<std::size_t>(str.hash());
928   }
929 };
930
931 /**
932  * Finds substrings faster than brute force by borrowing from Boyer-Moore
933  */
934 template <class T, class Comp>
935 size_t qfind(const Range<T>& haystack,
936              const Range<T>& needle,
937              Comp eq) {
938   // Don't use std::search, use a Boyer-Moore-like trick by comparing
939   // the last characters first
940   auto const nsize = needle.size();
941   if (haystack.size() < nsize) {
942     return std::string::npos;
943   }
944   if (!nsize) return 0;
945   auto const nsize_1 = nsize - 1;
946   auto const lastNeedle = needle[nsize_1];
947
948   // Boyer-Moore skip value for the last char in the needle. Zero is
949   // not a valid value; skip will be computed the first time it's
950   // needed.
951   std::string::size_type skip = 0;
952
953   auto i = haystack.begin();
954   auto iEnd = haystack.end() - nsize_1;
955
956   while (i < iEnd) {
957     // Boyer-Moore: match the last element in the needle
958     while (!eq(i[nsize_1], lastNeedle)) {
959       if (++i == iEnd) {
960         // not found
961         return std::string::npos;
962       }
963     }
964     // Here we know that the last char matches
965     // Continue in pedestrian mode
966     for (size_t j = 0; ; ) {
967       assert(j < nsize);
968       if (!eq(i[j], needle[j])) {
969         // Not found, we can skip
970         // Compute the skip value lazily
971         if (skip == 0) {
972           skip = 1;
973           while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
974             ++skip;
975           }
976         }
977         i += skip;
978         break;
979       }
980       // Check if done searching
981       if (++j == nsize) {
982         // Yay
983         return i - haystack.begin();
984       }
985     }
986   }
987   return std::string::npos;
988 }
989
990 namespace detail {
991
992 size_t qfind_first_byte_of_nosse(const StringPiece haystack,
993                                  const StringPiece needles);
994
995 #if FOLLY_HAVE_EMMINTRIN_H && __GNUC_PREREQ(4, 6)
996 size_t qfind_first_byte_of_sse42(const StringPiece haystack,
997                                  const StringPiece needles);
998
999 inline size_t qfind_first_byte_of(const StringPiece haystack,
1000                                   const StringPiece needles) {
1001   static auto const qfind_first_byte_of_fn =
1002     folly::CpuId().sse42() ? qfind_first_byte_of_sse42
1003                            : qfind_first_byte_of_nosse;
1004   return qfind_first_byte_of_fn(haystack, needles);
1005 }
1006
1007 #else
1008 inline size_t qfind_first_byte_of(const StringPiece haystack,
1009                                   const StringPiece needles) {
1010   return qfind_first_byte_of_nosse(haystack, needles);
1011 }
1012 #endif // FOLLY_HAVE_EMMINTRIN_H
1013
1014 } // namespace detail
1015
1016 template <class T, class Comp>
1017 size_t qfind_first_of(const Range<T> & haystack,
1018                       const Range<T> & needles,
1019                       Comp eq) {
1020   auto ret = std::find_first_of(haystack.begin(), haystack.end(),
1021                                 needles.begin(), needles.end(),
1022                                 eq);
1023   return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
1024 }
1025
1026 struct AsciiCaseSensitive {
1027   bool operator()(char lhs, char rhs) const {
1028     return lhs == rhs;
1029   }
1030 };
1031
1032 /**
1033  * Check if two ascii characters are case insensitive equal.
1034  * The difference between the lower/upper case characters are the 6-th bit.
1035  * We also check they are alpha chars, in case of xor = 32.
1036  */
1037 struct AsciiCaseInsensitive {
1038   bool operator()(char lhs, char rhs) const {
1039     char k = lhs ^ rhs;
1040     if (k == 0) return true;
1041     if (k != 32) return false;
1042     k = lhs | rhs;
1043     return (k >= 'a' && k <= 'z');
1044   }
1045 };
1046
1047 extern const AsciiCaseSensitive asciiCaseSensitive;
1048 extern const AsciiCaseInsensitive asciiCaseInsensitive;
1049
1050 template <class T>
1051 size_t qfind(const Range<T>& haystack,
1052              const typename Range<T>::value_type& needle) {
1053   auto pos = std::find(haystack.begin(), haystack.end(), needle);
1054   return pos == haystack.end() ? std::string::npos : pos - haystack.data();
1055 }
1056
1057 template <class T>
1058 size_t rfind(const Range<T>& haystack,
1059              const typename Range<T>::value_type& needle) {
1060   for (auto i = haystack.size(); i-- > 0; ) {
1061     if (haystack[i] == needle) {
1062       return i;
1063     }
1064   }
1065   return std::string::npos;
1066 }
1067
1068 // specialization for StringPiece
1069 template <>
1070 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
1071   auto pos = static_cast<const char*>(
1072     ::memchr(haystack.data(), needle, haystack.size()));
1073   return pos == nullptr ? std::string::npos : pos - haystack.data();
1074 }
1075
1076 #if FOLLY_HAVE_MEMRCHR
1077 template <>
1078 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
1079   auto pos = static_cast<const char*>(
1080     ::memrchr(haystack.data(), needle, haystack.size()));
1081   return pos == nullptr ? std::string::npos : pos - haystack.data();
1082 }
1083 #endif
1084
1085 // specialization for ByteRange
1086 template <>
1087 inline size_t qfind(const Range<const unsigned char*>& haystack,
1088                     const unsigned char& needle) {
1089   auto pos = static_cast<const unsigned char*>(
1090     ::memchr(haystack.data(), needle, haystack.size()));
1091   return pos == nullptr ? std::string::npos : pos - haystack.data();
1092 }
1093
1094 #if FOLLY_HAVE_MEMRCHR
1095 template <>
1096 inline size_t rfind(const Range<const unsigned char*>& haystack,
1097                     const unsigned char& needle) {
1098   auto pos = static_cast<const unsigned char*>(
1099     ::memrchr(haystack.data(), needle, haystack.size()));
1100   return pos == nullptr ? std::string::npos : pos - haystack.data();
1101 }
1102 #endif
1103
1104 template <class T>
1105 size_t qfind_first_of(const Range<T>& haystack,
1106                       const Range<T>& needles) {
1107   return qfind_first_of(haystack, needles, asciiCaseSensitive);
1108 }
1109
1110 // specialization for StringPiece
1111 template <>
1112 inline size_t qfind_first_of(const Range<const char*>& haystack,
1113                              const Range<const char*>& needles) {
1114   return detail::qfind_first_byte_of(haystack, needles);
1115 }
1116
1117 // specialization for ByteRange
1118 template <>
1119 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
1120                              const Range<const unsigned char*>& needles) {
1121   return detail::qfind_first_byte_of(StringPiece(haystack),
1122                                      StringPiece(needles));
1123 }
1124 }  // !namespace folly
1125
1126 #pragma GCC diagnostic pop
1127
1128 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);
1129
1130 #endif // FOLLY_RANGE_H_