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