Range<T>::rfind()
[folly.git] / folly / Range.h
1 /*
2  * Copyright 2013 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 <glog/logging.h>
26 #include <algorithm>
27 #include <cstring>
28 #include <iosfwd>
29 #include <string>
30 #include <stdexcept>
31 #include <type_traits>
32 #include <boost/operators.hpp>
33 #include <bits/c++config.h>
34 #include "folly/CpuId.h"
35 #include "folly/Traits.h"
36 #include "folly/Likely.h"
37
38 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
39 #pragma GCC diagnostic push
40 #pragma GCC diagnostic ignored "-Wshadow"
41
42 namespace folly {
43
44 template <class T> class Range;
45
46 /**
47  * Finds the first occurrence of needle in haystack. The algorithm is on
48  * average faster than O(haystack.size() * needle.size()) but not as fast
49  * as Boyer-Moore. On the upside, it does not do any upfront
50  * preprocessing and does not allocate memory.
51  */
52 template <class T>
53 inline size_t qfind(const Range<T> & haystack,
54                     const Range<T> & needle);
55
56 /**
57  * Finds the first occurrence of needle in haystack. The result is the
58  * offset reported to the beginning of haystack, or string::npos if
59  * needle wasn't found.
60  */
61 template <class T>
62 size_t qfind(const Range<T> & haystack,
63              const typename Range<T>::value_type& needle);
64
65 /**
66  * Finds the last occurrence of needle in haystack. The result is the
67  * offset reported to the beginning of haystack, or string::npos if
68  * needle wasn't found.
69  */
70 template <class T>
71 size_t rfind(const Range<T> & haystack,
72              const typename Range<T>::value_type& needle);
73
74
75 /**
76  * Finds the first occurrence of any element of needle in
77  * haystack. The algorithm is O(haystack.size() * needle.size()).
78  */
79 template <class T>
80 inline size_t qfind_first_of(const Range<T> & haystack,
81                              const Range<T> & needle);
82
83 /**
84  * Small internal helper - returns the value just before an iterator.
85  */
86 namespace detail {
87
88 /**
89  * For random-access iterators, the value before is simply i[-1].
90  */
91 template <class Iter>
92 typename std::enable_if<
93   std::is_same<typename std::iterator_traits<Iter>::iterator_category,
94                std::random_access_iterator_tag>::value,
95   typename std::iterator_traits<Iter>::reference>::type
96 value_before(Iter i) {
97   return i[-1];
98 }
99
100 /**
101  * For all other iterators, we need to use the decrement operator.
102  */
103 template <class Iter>
104 typename std::enable_if<
105   !std::is_same<typename std::iterator_traits<Iter>::iterator_category,
106                 std::random_access_iterator_tag>::value,
107   typename std::iterator_traits<Iter>::reference>::type
108 value_before(Iter i) {
109   return *--i;
110 }
111
112 } // namespace detail
113
114 /**
115  * Range abstraction keeping a pair of iterators. We couldn't use
116  * boost's similar range abstraction because we need an API identical
117  * with the former StringPiece class, which is used by a lot of other
118  * code. This abstraction does fulfill the needs of boost's
119  * range-oriented algorithms though.
120  *
121  * (Keep memory lifetime in mind when using this class, since it
122  * doesn't manage the data it refers to - just like an iterator
123  * wouldn't.)
124  */
125 template <class Iter>
126 class Range : private boost::totally_ordered<Range<Iter> > {
127 public:
128   typedef std::size_t size_type;
129   typedef Iter iterator;
130   typedef Iter const_iterator;
131   typedef typename std::remove_reference<
132     typename std::iterator_traits<Iter>::reference>::type
133   value_type;
134   typedef typename std::iterator_traits<Iter>::reference reference;
135   typedef std::char_traits<typename std::remove_const<value_type>::type>
136     traits_type;
137
138   static const size_type npos;
139
140   // Works for all iterators
141   Range() : b_(), e_() {
142   }
143
144 public:
145   // Works for all iterators
146   Range(Iter start, Iter end) : b_(start), e_(end) {
147   }
148
149   // Works only for random-access iterators
150   Range(Iter start, size_t size)
151       : b_(start), e_(start + size) { }
152
153   // Works only for Range<const char*>
154   /* implicit */ Range(Iter str)
155       : b_(str), e_(b_ + strlen(str)) {}
156   // Works only for Range<const char*>
157   /* implicit */ Range(const std::string& str)
158       : b_(str.data()), e_(b_ + str.size()) {}
159   // Works only for Range<const char*>
160   Range(const std::string& str, std::string::size_type startFrom) {
161     if (UNLIKELY(startFrom > str.size())) {
162       throw std::out_of_range("index out of range");
163     }
164     b_ = str.data() + startFrom;
165     e_ = str.data() + str.size();
166   }
167   // Works only for Range<const char*>
168   Range(const std::string& str,
169         std::string::size_type startFrom,
170         std::string::size_type size) {
171     if (UNLIKELY(startFrom > str.size())) {
172       throw std::out_of_range("index out of range");
173     }
174     b_ = str.data() + startFrom;
175     if (str.size() - startFrom < size) {
176       e_ = str.data() + str.size();
177     } else {
178       e_ = b_ + size;
179     }
180   }
181   Range(const Range<Iter>& str,
182         size_t startFrom,
183         size_t size) {
184     if (UNLIKELY(startFrom > str.size())) {
185       throw std::out_of_range("index out of range");
186     }
187     b_ = str.b_ + startFrom;
188     if (str.size() - startFrom < size) {
189       e_ = str.e_;
190     } else {
191       e_ = b_ + size;
192     }
193   }
194   // Works only for Range<const char*>
195   /* implicit */ Range(const fbstring& str)
196     : b_(str.data()), e_(b_ + str.size()) { }
197   // Works only for Range<const char*>
198   Range(const fbstring& str, fbstring::size_type startFrom) {
199     if (UNLIKELY(startFrom > str.size())) {
200       throw std::out_of_range("index out of range");
201     }
202     b_ = str.data() + startFrom;
203     e_ = str.data() + str.size();
204   }
205   // Works only for Range<const char*>
206   Range(const fbstring& str, fbstring::size_type startFrom,
207         fbstring::size_type size) {
208     if (UNLIKELY(startFrom > str.size())) {
209       throw std::out_of_range("index out of range");
210     }
211     b_ = str.data() + startFrom;
212     if (str.size() - startFrom < size) {
213       e_ = str.data() + str.size();
214     } else {
215       e_ = b_ + size;
216     }
217   }
218
219   // Allow implicit conversion from Range<const char*> (aka StringPiece) to
220   // Range<const unsigned char*> (aka ByteRange), as they're both frequently
221   // used to represent ranges of bytes.  Allow explicit conversion in the other
222   // direction.
223   template <class OtherIter, typename std::enable_if<
224       (std::is_same<Iter, const unsigned char*>::value &&
225        std::is_same<OtherIter, const char*>::value), int>::type = 0>
226   /* implicit */ Range(const Range<OtherIter>& other)
227     : b_(reinterpret_cast<const unsigned char*>(other.begin())),
228       e_(reinterpret_cast<const unsigned char*>(other.end())) {
229   }
230
231   template <class OtherIter, typename std::enable_if<
232       (std::is_same<Iter, const char*>::value &&
233        std::is_same<OtherIter, const unsigned char*>::value), int>::type = 0>
234   explicit Range(const Range<OtherIter>& other)
235     : b_(reinterpret_cast<const char*>(other.begin())),
236       e_(reinterpret_cast<const char*>(other.end())) {
237   }
238
239   void clear() {
240     b_ = Iter();
241     e_ = Iter();
242   }
243
244   void assign(Iter start, Iter end) {
245     b_ = start;
246     e_ = end;
247   }
248
249   void reset(Iter start, size_type size) {
250     b_ = start;
251     e_ = start + size;
252   }
253
254   // Works only for Range<const char*>
255   void reset(const std::string& str) {
256     reset(str.data(), str.size());
257   }
258
259   size_type size() const {
260     assert(b_ <= e_);
261     return e_ - b_;
262   }
263   size_type walk_size() const {
264     assert(b_ <= e_);
265     return std::distance(b_, e_);
266   }
267   bool empty() const { return b_ == e_; }
268   Iter data() const { return b_; }
269   Iter start() const { return b_; }
270   Iter begin() const { return b_; }
271   Iter end() const { return e_; }
272   Iter cbegin() const { return b_; }
273   Iter cend() const { return e_; }
274   value_type& front() {
275     assert(b_ < e_);
276     return *b_;
277   }
278   value_type& back() {
279     assert(b_ < e_);
280     return detail::value_before(e_);
281   }
282   const value_type& front() const {
283     assert(b_ < e_);
284     return *b_;
285   }
286   const value_type& back() const {
287     assert(b_ < e_);
288     return detail::value_before(e_);
289   }
290   // Works only for Range<const char*>
291   std::string str() const { return std::string(b_, size()); }
292   std::string toString() const { return str(); }
293   // Works only for Range<const char*>
294   fbstring fbstr() const { return fbstring(b_, size()); }
295   fbstring toFbstring() const { return fbstr(); }
296
297   // Works only for Range<const char*>
298   int compare(const Range& o) const {
299     const size_type tsize = this->size();
300     const size_type osize = o.size();
301     const size_type msize = std::min(tsize, osize);
302     int r = traits_type::compare(data(), o.data(), msize);
303     if (r == 0) r = tsize - osize;
304     return r;
305   }
306
307   value_type& operator[](size_t i) {
308     CHECK_GT(size(), i);
309     return b_[i];
310   }
311
312   const value_type& operator[](size_t i) const {
313     CHECK_GT(size(), i);
314     return b_[i];
315   }
316
317   value_type& at(size_t i) {
318     if (i >= size()) throw std::out_of_range("index out of range");
319     return b_[i];
320   }
321
322   const value_type& at(size_t i) const {
323     if (i >= size()) throw std::out_of_range("index out of range");
324     return b_[i];
325   }
326
327   // Works only for Range<const char*>
328   uint32_t hash() const {
329     // Taken from fbi/nstring.h:
330     //    Quick and dirty bernstein hash...fine for short ascii strings
331     uint32_t hash = 5381;
332     for (size_t ix = 0; ix < size(); ix++) {
333       hash = ((hash << 5) + hash) + b_[ix];
334     }
335     return hash;
336   }
337
338   void advance(size_type n) {
339     if (UNLIKELY(n > size())) {
340       throw std::out_of_range("index out of range");
341     }
342     b_ += n;
343   }
344
345   void subtract(size_type n) {
346     if (UNLIKELY(n > size())) {
347       throw std::out_of_range("index out of range");
348     }
349     e_ -= n;
350   }
351
352   void pop_front() {
353     assert(b_ < e_);
354     ++b_;
355   }
356
357   void pop_back() {
358     assert(b_ < e_);
359     --e_;
360   }
361
362   Range subpiece(size_type first,
363                  size_type length = std::string::npos) const {
364     if (UNLIKELY(first > size())) {
365       throw std::out_of_range("index out of range");
366     }
367     return Range(b_ + first,
368                  std::min<std::string::size_type>(length, size() - first));
369   }
370
371   // string work-alike functions
372   size_type find(Range str) const {
373     return qfind(*this, str);
374   }
375
376   size_type find(Range str, size_t pos) const {
377     if (pos > size()) return std::string::npos;
378     size_t ret = qfind(subpiece(pos), str);
379     return ret == npos ? ret : ret + pos;
380   }
381
382   size_type find(Iter s, size_t pos, size_t n) const {
383     if (pos > size()) return std::string::npos;
384     size_t ret = qfind(pos ? subpiece(pos) : *this, Range(s, n));
385     return ret == npos ? ret : ret + pos;
386   }
387
388   // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
389   size_type find(const Iter s) const {
390     return qfind(*this, Range(s));
391   }
392
393   // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
394   size_type find(const Iter s, size_t pos) const {
395     if (pos > size()) return std::string::npos;
396     size_type ret = qfind(subpiece(pos), Range(s));
397     return ret == npos ? ret : ret + pos;
398   }
399
400   size_type find(value_type c) const {
401     return qfind(*this, c);
402   }
403
404   size_type rfind(value_type c) const {
405     return folly::rfind(*this, c);
406   }
407
408   size_type find(value_type c, size_t pos) const {
409     if (pos > size()) return std::string::npos;
410     size_type ret = qfind(subpiece(pos), c);
411     return ret == npos ? ret : ret + pos;
412   }
413
414   size_type find_first_of(Range needles) const {
415     return qfind_first_of(*this, needles);
416   }
417
418   size_type find_first_of(Range needles, size_t pos) const {
419     if (pos > size()) return std::string::npos;
420     size_type ret = qfind_first_of(subpiece(pos), needles);
421     return ret == npos ? ret : ret + pos;
422   }
423
424   // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
425   size_type find_first_of(Iter needles) const {
426     return find_first_of(Range(needles));
427   }
428
429   // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
430   size_type find_first_of(Iter needles, size_t pos) const {
431     return find_first_of(Range(needles), pos);
432   }
433
434   size_type find_first_of(Iter needles, size_t pos, size_t n) const {
435     return find_first_of(Range(needles, n), pos);
436   }
437
438   size_type find_first_of(value_type c) const {
439     return find(c);
440   }
441
442   size_type find_first_of(value_type c, size_t pos) const {
443     return find(c, pos);
444   }
445
446   void swap(Range& rhs) {
447     std::swap(b_, rhs.b_);
448     std::swap(e_, rhs.e_);
449   }
450
451 private:
452   Iter b_, e_;
453 };
454
455 template <class Iter>
456 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
457
458 template <class T>
459 void swap(Range<T>& lhs, Range<T>& rhs) {
460   lhs.swap(rhs);
461 }
462
463 /**
464  * Create a range from two iterators, with type deduction.
465  */
466 template <class Iter>
467 Range<Iter> makeRange(Iter first, Iter last) {
468   return Range<Iter>(first, last);
469 }
470
471 typedef Range<const char*> StringPiece;
472 typedef Range<const unsigned char*> ByteRange;
473
474 std::ostream& operator<<(std::ostream& os, const StringPiece& piece);
475
476 /**
477  * Templated comparison operators
478  */
479
480 template <class T>
481 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
482   return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
483 }
484
485 template <class T>
486 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
487   return lhs.compare(rhs) < 0;
488 }
489
490 /**
491  * Specializations of comparison operators for StringPiece
492  */
493
494 namespace detail {
495
496 template <class A, class B>
497 struct ComparableAsStringPiece {
498   enum {
499     value =
500     (std::is_convertible<A, StringPiece>::value
501      && std::is_same<B, StringPiece>::value)
502     ||
503     (std::is_convertible<B, StringPiece>::value
504      && std::is_same<A, StringPiece>::value)
505   };
506 };
507
508 } // namespace detail
509
510 /**
511  * operator== through conversion for Range<const char*>
512  */
513 template <class T, class U>
514 typename
515 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
516 operator==(const T& lhs, const U& rhs) {
517   return StringPiece(lhs) == StringPiece(rhs);
518 }
519
520 /**
521  * operator< through conversion for Range<const char*>
522  */
523 template <class T, class U>
524 typename
525 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
526 operator<(const T& lhs, const U& rhs) {
527   return StringPiece(lhs) < StringPiece(rhs);
528 }
529
530 /**
531  * operator> through conversion for Range<const char*>
532  */
533 template <class T, class U>
534 typename
535 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
536 operator>(const T& lhs, const U& rhs) {
537   return StringPiece(lhs) > StringPiece(rhs);
538 }
539
540 /**
541  * operator< through conversion for Range<const char*>
542  */
543 template <class T, class U>
544 typename
545 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
546 operator<=(const T& lhs, const U& rhs) {
547   return StringPiece(lhs) <= StringPiece(rhs);
548 }
549
550 /**
551  * operator> through conversion for Range<const char*>
552  */
553 template <class T, class U>
554 typename
555 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
556 operator>=(const T& lhs, const U& rhs) {
557   return StringPiece(lhs) >= StringPiece(rhs);
558 }
559
560 struct StringPieceHash {
561   std::size_t operator()(const StringPiece& str) const {
562     return static_cast<std::size_t>(str.hash());
563   }
564 };
565
566 /**
567  * Finds substrings faster than brute force by borrowing from Boyer-Moore
568  */
569 template <class T, class Comp>
570 size_t qfind(const Range<T>& haystack,
571              const Range<T>& needle,
572              Comp eq) {
573   // Don't use std::search, use a Boyer-Moore-like trick by comparing
574   // the last characters first
575   auto const nsize = needle.size();
576   if (haystack.size() < nsize) {
577     return std::string::npos;
578   }
579   if (!nsize) return 0;
580   auto const nsize_1 = nsize - 1;
581   auto const lastNeedle = needle[nsize_1];
582
583   // Boyer-Moore skip value for the last char in the needle. Zero is
584   // not a valid value; skip will be computed the first time it's
585   // needed.
586   std::string::size_type skip = 0;
587
588   auto i = haystack.begin();
589   auto iEnd = haystack.end() - nsize_1;
590
591   while (i < iEnd) {
592     // Boyer-Moore: match the last element in the needle
593     while (!eq(i[nsize_1], lastNeedle)) {
594       if (++i == iEnd) {
595         // not found
596         return std::string::npos;
597       }
598     }
599     // Here we know that the last char matches
600     // Continue in pedestrian mode
601     for (size_t j = 0; ; ) {
602       assert(j < nsize);
603       if (!eq(i[j], needle[j])) {
604         // Not found, we can skip
605         // Compute the skip value lazily
606         if (skip == 0) {
607           skip = 1;
608           while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
609             ++skip;
610           }
611         }
612         i += skip;
613         break;
614       }
615       // Check if done searching
616       if (++j == nsize) {
617         // Yay
618         return i - haystack.begin();
619       }
620     }
621   }
622   return std::string::npos;
623 }
624
625 namespace detail {
626
627 size_t qfind_first_byte_of_nosse(const StringPiece& haystack,
628                                  const StringPiece& needles);
629
630 #if FOLLY_HAVE_EMMINTRIN_H
631 size_t qfind_first_byte_of_sse42(const StringPiece& haystack,
632                                  const StringPiece& needles);
633
634 inline size_t qfind_first_byte_of(const StringPiece& haystack,
635                                   const StringPiece& needles) {
636   static auto const qfind_first_byte_of_fn =
637     folly::CpuId().sse42() ? qfind_first_byte_of_sse42
638                            : qfind_first_byte_of_nosse;
639   return qfind_first_byte_of_fn(haystack, needles);
640 }
641
642 #else
643 inline size_t qfind_first_byte_of(const StringPiece& haystack,
644                                   const StringPiece& needles) {
645   return qfind_first_byte_of_nosse(haystack, needles);
646 }
647 #endif // FOLLY_HAVE_EMMINTRIN_H
648
649 } // namespace detail
650
651 template <class T, class Comp>
652 size_t qfind_first_of(const Range<T> & haystack,
653                       const Range<T> & needles,
654                       Comp eq) {
655   auto ret = std::find_first_of(haystack.begin(), haystack.end(),
656                                 needles.begin(), needles.end(),
657                                 eq);
658   return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
659 }
660
661 struct AsciiCaseSensitive {
662   bool operator()(char lhs, char rhs) const {
663     return lhs == rhs;
664   }
665 };
666
667 struct AsciiCaseInsensitive {
668   bool operator()(char lhs, char rhs) const {
669     return toupper(lhs) == toupper(rhs);
670   }
671 };
672
673 extern const AsciiCaseSensitive asciiCaseSensitive;
674 extern const AsciiCaseInsensitive asciiCaseInsensitive;
675
676 template <class T>
677 size_t qfind(const Range<T>& haystack,
678              const Range<T>& needle) {
679   return qfind(haystack, needle, asciiCaseSensitive);
680 }
681
682 template <class T>
683 size_t qfind(const Range<T>& haystack,
684              const typename Range<T>::value_type& needle) {
685   auto pos = std::find(haystack.begin(), haystack.end(), needle);
686   return pos == haystack.end() ? std::string::npos : pos - haystack.data();
687 }
688
689 template <class T>
690 size_t rfind(const Range<T>& haystack,
691              const typename Range<T>::value_type& needle) {
692   for (auto i = haystack.size(); i-- > 0; ) {
693     if (haystack[i] == needle) {
694       return i;
695     }
696   }
697   return std::string::npos;
698 }
699
700 // specialization for StringPiece
701 template <>
702 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
703   auto pos = static_cast<const char*>(
704     ::memchr(haystack.data(), needle, haystack.size()));
705   return pos == nullptr ? std::string::npos : pos - haystack.data();
706 }
707
708 template <>
709 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
710   auto pos = static_cast<const char*>(
711     ::memrchr(haystack.data(), needle, haystack.size()));
712   return pos == nullptr ? std::string::npos : pos - haystack.data();
713 }
714
715 // specialization for ByteRange
716 template <>
717 inline size_t qfind(const Range<const unsigned char*>& haystack,
718                     const unsigned char& needle) {
719   auto pos = static_cast<const unsigned char*>(
720     ::memchr(haystack.data(), needle, haystack.size()));
721   return pos == nullptr ? std::string::npos : pos - haystack.data();
722 }
723
724 template <>
725 inline size_t rfind(const Range<const unsigned char*>& haystack,
726                     const unsigned char& needle) {
727   auto pos = static_cast<const unsigned char*>(
728     ::memrchr(haystack.data(), needle, haystack.size()));
729   return pos == nullptr ? std::string::npos : pos - haystack.data();
730 }
731
732 template <class T>
733 size_t qfind_first_of(const Range<T>& haystack,
734                       const Range<T>& needles) {
735   return qfind_first_of(haystack, needles, asciiCaseSensitive);
736 }
737
738 // specialization for StringPiece
739 template <>
740 inline size_t qfind_first_of(const Range<const char*>& haystack,
741                              const Range<const char*>& needles) {
742   return detail::qfind_first_byte_of(haystack, needles);
743 }
744
745 // specialization for ByteRange
746 template <>
747 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
748                              const Range<const unsigned char*>& needles) {
749   return detail::qfind_first_byte_of(StringPiece(haystack),
750                                      StringPiece(needles));
751 }
752 }  // !namespace folly
753
754 #pragma GCC diagnostic pop
755
756 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);
757
758 #endif // FOLLY_RANGE_H_