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