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