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