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