ac316bc53cb8b557ef34c7f8aec525aa8686a9ab
[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.  Allow explicit conversion in the other
191   // direction.
192   template <class OtherIter, typename std::enable_if<
193       (std::is_same<Iter, const unsigned char*>::value &&
194        std::is_same<OtherIter, const char*>::value), int>::type = 0>
195   /* implicit */ Range(const Range<OtherIter>& other)
196     : b_(reinterpret_cast<const unsigned char*>(other.begin())),
197       e_(reinterpret_cast<const unsigned char*>(other.end())) {
198   }
199
200   template <class OtherIter, typename std::enable_if<
201       (std::is_same<Iter, const char*>::value &&
202        std::is_same<OtherIter, const unsigned char*>::value), int>::type = 0>
203   explicit Range(const Range<OtherIter>& other)
204     : b_(reinterpret_cast<const char*>(other.begin())),
205       e_(reinterpret_cast<const char*>(other.end())) {
206   }
207
208   void clear() {
209     b_ = Iter();
210     e_ = Iter();
211   }
212
213   void assign(Iter start, Iter end) {
214     b_ = start;
215     e_ = end;
216   }
217
218   void reset(Iter start, size_type size) {
219     b_ = start;
220     e_ = start + size;
221   }
222
223   // Works only for Range<const char*>
224   void reset(const std::string& str) {
225     reset(str.data(), str.size());
226   }
227
228   size_type size() const {
229     assert(b_ <= e_);
230     return e_ - b_;
231   }
232   size_type walk_size() const {
233     assert(b_ <= e_);
234     return std::distance(b_, e_);
235   }
236   bool empty() const { return b_ == e_; }
237   Iter data() const { return b_; }
238   Iter start() const { return b_; }
239   Iter begin() const { return b_; }
240   Iter end() const { return e_; }
241   Iter cbegin() const { return b_; }
242   Iter cend() const { return e_; }
243   value_type& front() {
244     assert(b_ < e_);
245     return *b_;
246   }
247   value_type& back() {
248     assert(b_ < e_);
249     return detail::value_before(e_);
250   }
251   const value_type& front() const {
252     assert(b_ < e_);
253     return *b_;
254   }
255   const value_type& back() const {
256     assert(b_ < e_);
257     return detail::value_before(e_);
258   }
259   // Works only for Range<const char*>
260   std::string str() const { return std::string(b_, size()); }
261   std::string toString() const { return str(); }
262   // Works only for Range<const char*>
263   fbstring fbstr() const { return fbstring(b_, size()); }
264   fbstring toFbstring() const { return fbstr(); }
265
266   // Works only for Range<const char*>
267   int compare(const Range& o) const {
268     const size_type tsize = this->size();
269     const size_type osize = o.size();
270     const size_type msize = std::min(tsize, osize);
271     int r = traits_type::compare(data(), o.data(), msize);
272     if (r == 0) r = tsize - osize;
273     return r;
274   }
275
276   value_type& operator[](size_t i) {
277     CHECK_GT(size(), i);
278     return b_[i];
279   }
280
281   const value_type& operator[](size_t i) const {
282     CHECK_GT(size(), i);
283     return b_[i];
284   }
285
286   value_type& at(size_t i) {
287     if (i >= size()) throw std::out_of_range("index out of range");
288     return b_[i];
289   }
290
291   const value_type& at(size_t i) const {
292     if (i >= size()) throw std::out_of_range("index out of range");
293     return b_[i];
294   }
295
296   // Works only for Range<const char*>
297   uint32_t hash() const {
298     // Taken from fbi/nstring.h:
299     //    Quick and dirty bernstein hash...fine for short ascii strings
300     uint32_t hash = 5381;
301     for (size_t ix = 0; ix < size(); ix++) {
302       hash = ((hash << 5) + hash) + b_[ix];
303     }
304     return hash;
305   }
306
307   void advance(size_type n) {
308     CHECK_LE(n, size());
309     b_ += n;
310   }
311
312   void subtract(size_type n) {
313     CHECK_LE(n, size());
314     e_ -= n;
315   }
316
317   void pop_front() {
318     assert(b_ < e_);
319     ++b_;
320   }
321
322   void pop_back() {
323     assert(b_ < e_);
324     --e_;
325   }
326
327   Range subpiece(size_type first,
328                  size_type length = std::string::npos) const {
329     CHECK_LE(first, size());
330     return Range(b_ + first,
331                  std::min<std::string::size_type>(length, size() - first));
332   }
333
334   // string work-alike functions
335   size_type find(Range str) const {
336     return qfind(*this, str);
337   }
338
339   size_type find(Range str, size_t pos) const {
340     if (pos > size()) return std::string::npos;
341     size_t ret = qfind(subpiece(pos), str);
342     return ret == npos ? ret : ret + pos;
343   }
344
345   size_type find(Iter s, size_t pos, size_t n) const {
346     if (pos > size()) return std::string::npos;
347     size_t ret = qfind(pos ? subpiece(pos) : *this, Range(s, n));
348     return ret == npos ? ret : ret + pos;
349   }
350
351   size_type find(const Iter s) const {
352     return qfind(*this, Range(s));
353   }
354
355   size_type find(const Iter s, size_t pos) const {
356     if (pos > size()) return std::string::npos;
357     size_type ret = qfind(subpiece(pos), Range(s));
358     return ret == npos ? ret : ret + pos;
359   }
360
361   size_type find(value_type c) const {
362     return qfind(*this, c);
363   }
364
365   size_type find(value_type c, size_t pos) const {
366     if (pos > size()) return std::string::npos;
367     size_type ret = qfind(subpiece(pos), c);
368     return ret == npos ? ret : ret + pos;
369   }
370
371   void swap(Range& rhs) {
372     std::swap(b_, rhs.b_);
373     std::swap(e_, rhs.e_);
374   }
375
376 private:
377   Iter b_, e_;
378 };
379
380 template <class Iter>
381 const typename Range<Iter>::size_type Range<Iter>::npos;
382
383 template <class T>
384 void swap(Range<T>& lhs, Range<T>& rhs) {
385   lhs.swap(rhs);
386 }
387
388 /**
389  * Create a range from two iterators, with type deduction.
390  */
391 template <class Iter>
392 Range<Iter> makeRange(Iter first, Iter last) {
393   return Range<Iter>(first, last);
394 }
395
396 typedef Range<const char*> StringPiece;
397 typedef Range<const unsigned char*> ByteRange;
398
399 std::ostream& operator<<(std::ostream& os, const StringPiece& piece);
400
401 /**
402  * Templated comparison operators
403  */
404
405 template <class T>
406 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
407   return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
408 }
409
410 template <class T>
411 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
412   return lhs.compare(rhs) < 0;
413 }
414
415 /**
416  * Specializations of comparison operators for StringPiece
417  */
418
419 namespace detail {
420
421 template <class A, class B>
422 struct ComparableAsStringPiece {
423   enum {
424     value =
425     (boost::is_convertible<A, StringPiece>::value
426      && boost::is_same<B, StringPiece>::value)
427     ||
428     (boost::is_convertible<B, StringPiece>::value
429      && boost::is_same<A, StringPiece>::value)
430   };
431 };
432
433 } // namespace detail
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 /**
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 struct StringPieceHash {
486   std::size_t operator()(const StringPiece& str) const {
487     return static_cast<std::size_t>(str.hash());
488   }
489 };
490
491 /**
492  * Finds substrings faster than brute force by borrowing from Boyer-Moore
493  */
494 template <class T, class Comp>
495 size_t qfind(const Range<T>& haystack,
496              const Range<T>& needle,
497              Comp eq) {
498   // Don't use std::search, use a Boyer-Moore-like trick by comparing
499   // the last characters first
500   auto const nsize = needle.size();
501   if (haystack.size() < nsize) {
502     return std::string::npos;
503   }
504   if (!nsize) return 0;
505   auto const nsize_1 = nsize - 1;
506   auto const lastNeedle = needle[nsize_1];
507
508   // Boyer-Moore skip value for the last char in the needle. Zero is
509   // not a valid value; skip will be computed the first time it's
510   // needed.
511   std::string::size_type skip = 0;
512
513   auto i = haystack.begin();
514   auto iEnd = haystack.end() - nsize_1;
515
516   while (i < iEnd) {
517     // Boyer-Moore: match the last element in the needle
518     while (!eq(i[nsize_1], lastNeedle)) {
519       if (++i == iEnd) {
520         // not found
521         return std::string::npos;
522       }
523     }
524     // Here we know that the last char matches
525     // Continue in pedestrian mode
526     for (size_t j = 0; ; ) {
527       assert(j < nsize);
528       if (!eq(i[j], needle[j])) {
529         // Not found, we can skip
530         // Compute the skip value lazily
531         if (skip == 0) {
532           skip = 1;
533           while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
534             ++skip;
535           }
536         }
537         i += skip;
538         break;
539       }
540       // Check if done searching
541       if (++j == nsize) {
542         // Yay
543         return i - haystack.begin();
544       }
545     }
546   }
547   return std::string::npos;
548 }
549
550 struct AsciiCaseSensitive {
551   bool operator()(char lhs, char rhs) const {
552     return lhs == rhs;
553   }
554 };
555
556 struct AsciiCaseInsensitive {
557   bool operator()(char lhs, char rhs) const {
558     return toupper(lhs) == toupper(rhs);
559   }
560 };
561
562 extern const AsciiCaseSensitive asciiCaseSensitive;
563 extern const AsciiCaseInsensitive asciiCaseInsensitive;
564
565 template <class T>
566 size_t qfind(const Range<T>& haystack,
567              const Range<T>& needle) {
568   return qfind(haystack, needle, asciiCaseSensitive);
569 }
570
571 template <class T>
572 size_t qfind(const Range<T>& haystack,
573              const typename Range<T>::value_type& needle) {
574   return qfind(haystack, makeRange(&needle, &needle + 1));
575 }
576
577 }  // !namespace folly
578
579 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);
580
581 #endif // FOLLY_RANGE_H_