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