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