2 * Copyright 2013 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/Portability.h"
24 #include "folly/FBString.h"
25 #include <glog/logging.h>
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"
38 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
39 #pragma GCC diagnostic push
40 #pragma GCC diagnostic ignored "-Wshadow"
44 template <class T> class Range;
47 * Finds the first occurrence of needle in haystack. The algorithm is on
48 * average faster than O(haystack.size() * needle.size()) but not as fast
49 * as Boyer-Moore. On the upside, it does not do any upfront
50 * preprocessing and does not allocate memory.
52 template <class T, class Comp = std::equal_to<typename Range<T>::value_type>>
53 inline size_t qfind(const Range<T> & haystack,
54 const Range<T> & needle,
58 * Finds the first occurrence of needle in haystack. The result is the
59 * offset reported to the beginning of haystack, or string::npos if
60 * needle wasn't found.
63 size_t qfind(const Range<T> & haystack,
64 const typename Range<T>::value_type& needle);
67 * Finds the last occurrence of needle in haystack. The result is the
68 * offset reported to the beginning of haystack, or string::npos if
69 * needle wasn't found.
72 size_t rfind(const Range<T> & haystack,
73 const typename Range<T>::value_type& needle);
77 * Finds the first occurrence of any element of needle in
78 * haystack. The algorithm is O(haystack.size() * needle.size()).
81 inline size_t qfind_first_of(const Range<T> & haystack,
82 const Range<T> & needle);
85 * Small internal helper - returns the value just before an iterator.
90 * For random-access iterators, the value before is simply i[-1].
93 typename std::enable_if<
94 std::is_same<typename std::iterator_traits<Iter>::iterator_category,
95 std::random_access_iterator_tag>::value,
96 typename std::iterator_traits<Iter>::reference>::type
97 value_before(Iter i) {
102 * For all other iterators, we need to use the decrement operator.
104 template <class Iter>
105 typename std::enable_if<
106 !std::is_same<typename std::iterator_traits<Iter>::iterator_category,
107 std::random_access_iterator_tag>::value,
108 typename std::iterator_traits<Iter>::reference>::type
109 value_before(Iter i) {
113 } // namespace detail
116 * Range abstraction keeping a pair of iterators. We couldn't use
117 * boost's similar range abstraction because we need an API identical
118 * with the former StringPiece class, which is used by a lot of other
119 * code. This abstraction does fulfill the needs of boost's
120 * range-oriented algorithms though.
122 * (Keep memory lifetime in mind when using this class, since it
123 * doesn't manage the data it refers to - just like an iterator
126 template <class Iter>
127 class Range : private boost::totally_ordered<Range<Iter> > {
129 typedef std::size_t size_type;
130 typedef Iter iterator;
131 typedef Iter const_iterator;
132 typedef typename std::remove_reference<
133 typename std::iterator_traits<Iter>::reference>::type
135 typedef typename std::iterator_traits<Iter>::reference reference;
136 typedef std::char_traits<typename std::remove_const<value_type>::type>
139 static const size_type npos;
141 // Works for all iterators
142 Range() : b_(), e_() {
146 // Works for all iterators
147 Range(Iter start, Iter end) : b_(start), e_(end) {
150 // Works only for random-access iterators
151 Range(Iter start, size_t size)
152 : b_(start), e_(start + size) { }
154 // Works only for Range<const char*>
155 /* implicit */ Range(Iter str)
156 : b_(str), e_(b_ + strlen(str)) {}
157 // Works only for Range<const char*>
158 /* implicit */ Range(const std::string& str)
159 : b_(str.data()), e_(b_ + str.size()) {}
160 // Works only for Range<const char*>
161 Range(const std::string& str, std::string::size_type startFrom) {
162 if (UNLIKELY(startFrom > str.size())) {
163 throw std::out_of_range("index out of range");
165 b_ = str.data() + startFrom;
166 e_ = str.data() + str.size();
168 // Works only for Range<const char*>
169 Range(const std::string& str,
170 std::string::size_type startFrom,
171 std::string::size_type size) {
172 if (UNLIKELY(startFrom > str.size())) {
173 throw std::out_of_range("index out of range");
175 b_ = str.data() + startFrom;
176 if (str.size() - startFrom < size) {
177 e_ = str.data() + str.size();
182 Range(const Range<Iter>& str,
185 if (UNLIKELY(startFrom > str.size())) {
186 throw std::out_of_range("index out of range");
188 b_ = str.b_ + startFrom;
189 if (str.size() - startFrom < size) {
195 // Works only for Range<const char*>
196 /* implicit */ Range(const fbstring& str)
197 : b_(str.data()), e_(b_ + str.size()) { }
198 // Works only for Range<const char*>
199 Range(const fbstring& str, fbstring::size_type startFrom) {
200 if (UNLIKELY(startFrom > str.size())) {
201 throw std::out_of_range("index out of range");
203 b_ = str.data() + startFrom;
204 e_ = str.data() + str.size();
206 // Works only for Range<const char*>
207 Range(const fbstring& str, fbstring::size_type startFrom,
208 fbstring::size_type size) {
209 if (UNLIKELY(startFrom > str.size())) {
210 throw std::out_of_range("index out of range");
212 b_ = str.data() + startFrom;
213 if (str.size() - startFrom < size) {
214 e_ = str.data() + str.size();
220 // Allow implicit conversion from Range<const char*> (aka StringPiece) to
221 // Range<const unsigned char*> (aka ByteRange), as they're both frequently
222 // used to represent ranges of bytes. Allow explicit conversion in the other
224 template <class OtherIter, typename std::enable_if<
225 (std::is_same<Iter, const unsigned char*>::value &&
226 std::is_same<OtherIter, const char*>::value), int>::type = 0>
227 /* implicit */ Range(const Range<OtherIter>& other)
228 : b_(reinterpret_cast<const unsigned char*>(other.begin())),
229 e_(reinterpret_cast<const unsigned char*>(other.end())) {
232 template <class OtherIter, typename std::enable_if<
233 (std::is_same<Iter, const char*>::value &&
234 std::is_same<OtherIter, const unsigned char*>::value), int>::type = 0>
235 explicit Range(const Range<OtherIter>& other)
236 : b_(reinterpret_cast<const char*>(other.begin())),
237 e_(reinterpret_cast<const char*>(other.end())) {
245 void assign(Iter start, Iter end) {
250 void reset(Iter start, size_type size) {
255 // Works only for Range<const char*>
256 void reset(const std::string& str) {
257 reset(str.data(), str.size());
260 size_type size() const {
264 size_type walk_size() const {
266 return std::distance(b_, e_);
268 bool empty() const { return b_ == e_; }
269 Iter data() const { return b_; }
270 Iter start() const { return b_; }
271 Iter begin() const { return b_; }
272 Iter end() const { return e_; }
273 Iter cbegin() const { return b_; }
274 Iter cend() const { return e_; }
275 value_type& front() {
281 return detail::value_before(e_);
283 const value_type& front() const {
287 const value_type& back() const {
289 return detail::value_before(e_);
291 // Works only for Range<const char*>
292 std::string str() const { return std::string(b_, size()); }
293 std::string toString() const { return str(); }
294 // Works only for Range<const char*>
295 fbstring fbstr() const { return fbstring(b_, size()); }
296 fbstring toFbstring() const { return fbstr(); }
298 // Works only for Range<const char*>
299 int compare(const Range& o) const {
300 const size_type tsize = this->size();
301 const size_type osize = o.size();
302 const size_type msize = std::min(tsize, osize);
303 int r = traits_type::compare(data(), o.data(), msize);
304 if (r == 0) r = tsize - osize;
308 value_type& operator[](size_t i) {
313 const value_type& operator[](size_t i) const {
318 value_type& at(size_t i) {
319 if (i >= size()) throw std::out_of_range("index out of range");
323 const value_type& at(size_t i) const {
324 if (i >= size()) throw std::out_of_range("index out of range");
328 // Works only for Range<const char*>
329 uint32_t hash() const {
330 // Taken from fbi/nstring.h:
331 // Quick and dirty bernstein hash...fine for short ascii strings
332 uint32_t hash = 5381;
333 for (size_t ix = 0; ix < size(); ix++) {
334 hash = ((hash << 5) + hash) + b_[ix];
339 void advance(size_type n) {
340 if (UNLIKELY(n > size())) {
341 throw std::out_of_range("index out of range");
346 void subtract(size_type n) {
347 if (UNLIKELY(n > size())) {
348 throw std::out_of_range("index out of range");
363 Range subpiece(size_type first,
364 size_type length = std::string::npos) const {
365 if (UNLIKELY(first > size())) {
366 throw std::out_of_range("index out of range");
368 return Range(b_ + first,
369 std::min<std::string::size_type>(length, size() - first));
372 // string work-alike functions
373 size_type find(Range str) const {
374 return qfind(*this, str);
377 size_type find(Range str, size_t pos) const {
378 if (pos > size()) return std::string::npos;
379 size_t ret = qfind(subpiece(pos), str);
380 return ret == npos ? ret : ret + pos;
383 size_type find(Iter s, size_t pos, size_t n) const {
384 if (pos > size()) return std::string::npos;
385 size_t ret = qfind(pos ? subpiece(pos) : *this, Range(s, n));
386 return ret == npos ? ret : ret + pos;
389 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
390 size_type find(const Iter s) const {
391 return qfind(*this, Range(s));
394 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
395 size_type find(const Iter s, size_t pos) const {
396 if (pos > size()) return std::string::npos;
397 size_type ret = qfind(subpiece(pos), Range(s));
398 return ret == npos ? ret : ret + pos;
401 size_type find(value_type c) const {
402 return qfind(*this, c);
405 size_type rfind(value_type c) const {
406 return folly::rfind(*this, c);
409 size_type find(value_type c, size_t pos) const {
410 if (pos > size()) return std::string::npos;
411 size_type ret = qfind(subpiece(pos), c);
412 return ret == npos ? ret : ret + pos;
415 size_type find_first_of(Range needles) const {
416 return qfind_first_of(*this, needles);
419 size_type find_first_of(Range needles, size_t pos) const {
420 if (pos > size()) return std::string::npos;
421 size_type ret = qfind_first_of(subpiece(pos), needles);
422 return ret == npos ? ret : ret + pos;
425 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
426 size_type find_first_of(Iter needles) const {
427 return find_first_of(Range(needles));
430 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
431 size_type find_first_of(Iter needles, size_t pos) const {
432 return find_first_of(Range(needles), pos);
435 size_type find_first_of(Iter needles, size_t pos, size_t n) const {
436 return find_first_of(Range(needles, n), pos);
439 size_type find_first_of(value_type c) const {
443 size_type find_first_of(value_type c, size_t pos) const {
447 void swap(Range& rhs) {
448 std::swap(b_, rhs.b_);
449 std::swap(e_, rhs.e_);
456 template <class Iter>
457 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
460 void swap(Range<T>& lhs, Range<T>& rhs) {
465 * Create a range from two iterators, with type deduction.
467 template <class Iter>
468 Range<Iter> makeRange(Iter first, Iter last) {
469 return Range<Iter>(first, last);
472 typedef Range<const char*> StringPiece;
473 typedef Range<const unsigned char*> ByteRange;
475 std::ostream& operator<<(std::ostream& os, const StringPiece& piece);
478 * Templated comparison operators
482 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
483 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
487 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
488 return lhs.compare(rhs) < 0;
492 * Specializations of comparison operators for StringPiece
497 template <class A, class B>
498 struct ComparableAsStringPiece {
501 (std::is_convertible<A, StringPiece>::value
502 && std::is_same<B, StringPiece>::value)
504 (std::is_convertible<B, StringPiece>::value
505 && std::is_same<A, StringPiece>::value)
509 } // namespace detail
512 * operator== through conversion for Range<const char*>
514 template <class T, class U>
516 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
517 operator==(const T& lhs, const U& rhs) {
518 return StringPiece(lhs) == StringPiece(rhs);
522 * operator< through conversion for Range<const char*>
524 template <class T, class U>
526 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
527 operator<(const T& lhs, const U& rhs) {
528 return StringPiece(lhs) < StringPiece(rhs);
532 * operator> through conversion for Range<const char*>
534 template <class T, class U>
536 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
537 operator>(const T& lhs, const U& rhs) {
538 return StringPiece(lhs) > StringPiece(rhs);
542 * operator< through conversion for Range<const char*>
544 template <class T, class U>
546 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
547 operator<=(const T& lhs, const U& rhs) {
548 return StringPiece(lhs) <= StringPiece(rhs);
552 * operator> through conversion for Range<const char*>
554 template <class T, class U>
556 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
557 operator>=(const T& lhs, const U& rhs) {
558 return StringPiece(lhs) >= StringPiece(rhs);
561 struct StringPieceHash {
562 std::size_t operator()(const StringPiece& str) const {
563 return static_cast<std::size_t>(str.hash());
568 * Finds substrings faster than brute force by borrowing from Boyer-Moore
570 template <class T, class Comp>
571 size_t qfind(const Range<T>& haystack,
572 const Range<T>& needle,
574 // Don't use std::search, use a Boyer-Moore-like trick by comparing
575 // the last characters first
576 auto const nsize = needle.size();
577 if (haystack.size() < nsize) {
578 return std::string::npos;
580 if (!nsize) return 0;
581 auto const nsize_1 = nsize - 1;
582 auto const lastNeedle = needle[nsize_1];
584 // Boyer-Moore skip value for the last char in the needle. Zero is
585 // not a valid value; skip will be computed the first time it's
587 std::string::size_type skip = 0;
589 auto i = haystack.begin();
590 auto iEnd = haystack.end() - nsize_1;
593 // Boyer-Moore: match the last element in the needle
594 while (!eq(i[nsize_1], lastNeedle)) {
597 return std::string::npos;
600 // Here we know that the last char matches
601 // Continue in pedestrian mode
602 for (size_t j = 0; ; ) {
604 if (!eq(i[j], needle[j])) {
605 // Not found, we can skip
606 // Compute the skip value lazily
609 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
616 // Check if done searching
619 return i - haystack.begin();
623 return std::string::npos;
628 size_t qfind_first_byte_of_nosse(const StringPiece& haystack,
629 const StringPiece& needles);
631 #if FOLLY_HAVE_EMMINTRIN_H
632 size_t qfind_first_byte_of_sse42(const StringPiece& haystack,
633 const StringPiece& needles);
635 inline size_t qfind_first_byte_of(const StringPiece& haystack,
636 const StringPiece& needles) {
637 static auto const qfind_first_byte_of_fn =
638 folly::CpuId().sse42() ? qfind_first_byte_of_sse42
639 : qfind_first_byte_of_nosse;
640 return qfind_first_byte_of_fn(haystack, needles);
644 inline size_t qfind_first_byte_of(const StringPiece& haystack,
645 const StringPiece& needles) {
646 return qfind_first_byte_of_nosse(haystack, needles);
648 #endif // FOLLY_HAVE_EMMINTRIN_H
650 } // namespace detail
652 template <class T, class Comp>
653 size_t qfind_first_of(const Range<T> & haystack,
654 const Range<T> & needles,
656 auto ret = std::find_first_of(haystack.begin(), haystack.end(),
657 needles.begin(), needles.end(),
659 return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
662 struct AsciiCaseSensitive {
663 bool operator()(char lhs, char rhs) const {
668 struct AsciiCaseInsensitive {
669 bool operator()(char lhs, char rhs) const {
670 return toupper(lhs) == toupper(rhs);
674 extern const AsciiCaseSensitive asciiCaseSensitive;
675 extern const AsciiCaseInsensitive asciiCaseInsensitive;
678 size_t qfind(const Range<T>& haystack,
679 const typename Range<T>::value_type& needle) {
680 auto pos = std::find(haystack.begin(), haystack.end(), needle);
681 return pos == haystack.end() ? std::string::npos : pos - haystack.data();
685 size_t rfind(const Range<T>& haystack,
686 const typename Range<T>::value_type& needle) {
687 for (auto i = haystack.size(); i-- > 0; ) {
688 if (haystack[i] == needle) {
692 return std::string::npos;
695 // specialization for StringPiece
697 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
698 auto pos = static_cast<const char*>(
699 ::memchr(haystack.data(), needle, haystack.size()));
700 return pos == nullptr ? std::string::npos : pos - haystack.data();
703 #if FOLLY_HAVE_MEMRCHR
705 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
706 auto pos = static_cast<const char*>(
707 ::memrchr(haystack.data(), needle, haystack.size()));
708 return pos == nullptr ? std::string::npos : pos - haystack.data();
712 // specialization for ByteRange
714 inline size_t qfind(const Range<const unsigned char*>& haystack,
715 const unsigned char& needle) {
716 auto pos = static_cast<const unsigned char*>(
717 ::memchr(haystack.data(), needle, haystack.size()));
718 return pos == nullptr ? std::string::npos : pos - haystack.data();
721 #if FOLLY_HAVE_MEMRCHR
723 inline size_t rfind(const Range<const unsigned char*>& haystack,
724 const unsigned char& needle) {
725 auto pos = static_cast<const unsigned char*>(
726 ::memrchr(haystack.data(), needle, haystack.size()));
727 return pos == nullptr ? std::string::npos : pos - haystack.data();
732 size_t qfind_first_of(const Range<T>& haystack,
733 const Range<T>& needles) {
734 return qfind_first_of(haystack, needles, asciiCaseSensitive);
737 // specialization for StringPiece
739 inline size_t qfind_first_of(const Range<const char*>& haystack,
740 const Range<const char*>& needles) {
741 return detail::qfind_first_byte_of(haystack, needles);
744 // specialization for ByteRange
746 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
747 const Range<const unsigned char*>& needles) {
748 return detail::qfind_first_byte_of(StringPiece(haystack),
749 StringPiece(needles));
751 } // !namespace folly
753 #pragma GCC diagnostic pop
755 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);
757 #endif // FOLLY_RANGE_H_