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