2 * Copyright 2012 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 // @author Mark Rabkin (mrabkin@fb.com)
18 // @author Andrei Alexandrescu (andrei.alexandrescu@fb.com)
20 #ifndef FOLLY_RANGE_H_
21 #define FOLLY_RANGE_H_
23 #include "folly/FBString.h"
24 #include <glog/logging.h>
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"
39 template <class T> class Range;
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.
48 inline size_t qfind(const Range<T> & haystack,
49 const Range<T> & needle);
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.
57 size_t qfind(const Range<T> & haystack,
58 const typename Range<T>::value_type& needle);
62 * Finds the first occurrence of any element of needle in
63 * haystack. The algorithm is O(haystack.size() * needle.size()).
66 inline size_t qfind_first_of(const Range<T> & haystack,
67 const Range<T> & needle);
70 * Small internal helper - returns the value just before an iterator.
75 * For random-access iterators, the value before is simply i[-1].
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) {
87 * For all other iterators, we need to use the decrement operator.
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) {
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.
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
111 template <class Iter>
112 class Range : private boost::totally_ordered<Range<Iter> > {
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
120 typedef typename std::iterator_traits<Iter>::reference reference;
121 typedef std::char_traits<value_type> traits_type;
123 static const size_type npos;
125 // Works for all iterators
126 Range() : b_(), e_() {
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)...";
139 static bool reachable(Iter b, Iter e, std::random_access_iterator_tag) {
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()));
151 // Works only for random-access iterators
152 Range(Iter start, size_t size)
153 : b_(start), e_(start + size) { }
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();
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;
175 Range(const Range<Iter>& str,
178 CHECK_LE(startFrom + size, str.size());
179 b_ = str.b_ + startFrom;
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();
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;
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
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())) {
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())) {
224 void assign(Iter start, Iter end) {
229 void reset(Iter start, size_type size) {
234 // Works only for Range<const char*>
235 void reset(const std::string& str) {
236 reset(str.data(), str.size());
239 size_type size() const {
243 size_type walk_size() const {
245 return std::distance(b_, e_);
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() {
260 return detail::value_before(e_);
262 const value_type& front() const {
266 const value_type& back() const {
268 return detail::value_before(e_);
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(); }
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;
287 value_type& operator[](size_t i) {
292 const value_type& operator[](size_t i) const {
297 value_type& at(size_t i) {
298 if (i >= size()) throw std::out_of_range("index out of range");
302 const value_type& at(size_t i) const {
303 if (i >= size()) throw std::out_of_range("index out of range");
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];
318 void advance(size_type n) {
323 void subtract(size_type n) {
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));
345 // string work-alike functions
346 size_type find(Range str) const {
347 return qfind(*this, str);
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;
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;
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));
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;
374 size_type find(value_type c) const {
375 return qfind(*this, c);
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;
384 size_type find_first_of(Range needles) const {
385 return qfind_first_of(*this, needles);
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;
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));
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);
404 size_type find_first_of(Iter needles, size_t pos, size_t n) const {
405 return find_first_of(Range(needles, n), pos);
408 size_type find_first_of(value_type c) const {
412 size_type find_first_of(value_type c, size_t pos) const {
416 void swap(Range& rhs) {
417 std::swap(b_, rhs.b_);
418 std::swap(e_, rhs.e_);
425 template <class Iter>
426 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
429 void swap(Range<T>& lhs, Range<T>& rhs) {
434 * Create a range from two iterators, with type deduction.
436 template <class Iter>
437 Range<Iter> makeRange(Iter first, Iter last) {
438 return Range<Iter>(first, last);
441 typedef Range<const char*> StringPiece;
442 typedef Range<const unsigned char*> ByteRange;
444 std::ostream& operator<<(std::ostream& os, const StringPiece& piece);
447 * Templated comparison operators
451 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
452 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
456 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
457 return lhs.compare(rhs) < 0;
461 * Specializations of comparison operators for StringPiece
466 template <class A, class B>
467 struct ComparableAsStringPiece {
470 (boost::is_convertible<A, StringPiece>::value
471 && boost::is_same<B, StringPiece>::value)
473 (boost::is_convertible<B, StringPiece>::value
474 && boost::is_same<A, StringPiece>::value)
478 } // namespace detail
481 * operator== through conversion for Range<const char*>
483 template <class T, class U>
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);
491 * operator< through conversion for Range<const char*>
493 template <class T, class U>
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);
501 * operator> through conversion for Range<const char*>
503 template <class T, class U>
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);
511 * operator< through conversion for Range<const char*>
513 template <class T, class U>
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);
521 * operator> through conversion for Range<const char*>
523 template <class T, class U>
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);
530 struct StringPieceHash {
531 std::size_t operator()(const StringPiece& str) const {
532 return static_cast<std::size_t>(str.hash());
537 * Finds substrings faster than brute force by borrowing from Boyer-Moore
539 template <class T, class Comp>
540 size_t qfind(const Range<T>& haystack,
541 const Range<T>& needle,
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;
549 if (!nsize) return 0;
550 auto const nsize_1 = nsize - 1;
551 auto const lastNeedle = needle[nsize_1];
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
556 std::string::size_type skip = 0;
558 auto i = haystack.begin();
559 auto iEnd = haystack.end() - nsize_1;
562 // Boyer-Moore: match the last element in the needle
563 while (!eq(i[nsize_1], lastNeedle)) {
566 return std::string::npos;
569 // Here we know that the last char matches
570 // Continue in pedestrian mode
571 for (size_t j = 0; ; ) {
573 if (!eq(i[j], needle[j])) {
574 // Not found, we can skip
575 // Compute the skip value lazily
578 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
585 // Check if done searching
588 return i - haystack.begin();
592 return std::string::npos;
595 template <class T, class Comp>
596 size_t qfind_first_of(const Range<T> & haystack,
597 const Range<T> & needle,
599 auto ret = std::find_first_of(haystack.begin(), haystack.end(),
600 needle.begin(), needle.end(),
602 return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
605 struct AsciiCaseSensitive {
606 bool operator()(char lhs, char rhs) const {
611 struct AsciiCaseInsensitive {
612 bool operator()(char lhs, char rhs) const {
613 return toupper(lhs) == toupper(rhs);
617 extern const AsciiCaseSensitive asciiCaseSensitive;
618 extern const AsciiCaseInsensitive asciiCaseInsensitive;
621 size_t qfind(const Range<T>& haystack,
622 const Range<T>& needle) {
623 return qfind(haystack, needle, asciiCaseSensitive);
627 size_t qfind(const Range<T>& haystack,
628 const typename Range<T>::value_type& needle) {
629 auto pos = std::find(haystack.begin(), haystack.end(), needle);
630 return pos == haystack.end() ? std::string::npos : pos - haystack.data();
633 // specialization for StringPiece
635 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
636 auto pos = static_cast<const char*>(
637 ::memchr(haystack.data(), needle, haystack.size()));
638 return pos == nullptr ? std::string::npos : pos - haystack.data();
641 // specialization for ByteRange
643 inline size_t qfind(const Range<const unsigned char*>& haystack,
644 const unsigned char& needle) {
645 auto pos = static_cast<const unsigned char*>(
646 ::memchr(haystack.data(), needle, haystack.size()));
647 return pos == nullptr ? std::string::npos : pos - haystack.data();
651 size_t qfind_first_of(const Range<T>& haystack,
652 const Range<T>& needle) {
653 return qfind_first_of(haystack, needle, asciiCaseSensitive);
656 } // !namespace folly
658 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);
660 #endif // FOLLY_RANGE_H_