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