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