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