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