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