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 #if FOLLY_HAVE_CONSTEXPR_STRLEN
155 // Works only for Range<const char*>
156 /* implicit */ constexpr Range(Iter str)
157 : b_(str), e_(str + strlen(str)) {}
159 // Works only for Range<const char*>
160 /* implicit */ Range(Iter str)
161 : b_(str), e_(str + strlen(str)) {}
163 // Works only for Range<const char*>
164 /* implicit */ Range(const std::string& str)
165 : b_(str.data()), e_(b_ + str.size()) {}
166 // Works only for Range<const char*>
167 Range(const std::string& str, std::string::size_type startFrom) {
168 if (UNLIKELY(startFrom > str.size())) {
169 throw std::out_of_range("index out of range");
171 b_ = str.data() + startFrom;
172 e_ = str.data() + str.size();
174 // Works only for Range<const char*>
175 Range(const std::string& str,
176 std::string::size_type startFrom,
177 std::string::size_type size) {
178 if (UNLIKELY(startFrom > str.size())) {
179 throw std::out_of_range("index out of range");
181 b_ = str.data() + startFrom;
182 if (str.size() - startFrom < size) {
183 e_ = str.data() + str.size();
188 Range(const Range<Iter>& str,
191 if (UNLIKELY(startFrom > str.size())) {
192 throw std::out_of_range("index out of range");
194 b_ = str.b_ + startFrom;
195 if (str.size() - startFrom < size) {
201 // Works only for Range<const char*>
202 /* implicit */ Range(const fbstring& str)
203 : b_(str.data()), e_(b_ + str.size()) { }
204 // Works only for Range<const char*>
205 Range(const fbstring& str, fbstring::size_type startFrom) {
206 if (UNLIKELY(startFrom > str.size())) {
207 throw std::out_of_range("index out of range");
209 b_ = str.data() + startFrom;
210 e_ = str.data() + str.size();
212 // Works only for Range<const char*>
213 Range(const fbstring& str, fbstring::size_type startFrom,
214 fbstring::size_type size) {
215 if (UNLIKELY(startFrom > str.size())) {
216 throw std::out_of_range("index out of range");
218 b_ = str.data() + startFrom;
219 if (str.size() - startFrom < size) {
220 e_ = str.data() + str.size();
226 // Allow implicit conversion from Range<const char*> (aka StringPiece) to
227 // Range<const unsigned char*> (aka ByteRange), as they're both frequently
228 // used to represent ranges of bytes. Allow explicit conversion in the other
230 template <class OtherIter, typename std::enable_if<
231 (std::is_same<Iter, const unsigned char*>::value &&
232 std::is_same<OtherIter, const char*>::value), int>::type = 0>
233 /* implicit */ Range(const Range<OtherIter>& other)
234 : b_(reinterpret_cast<const unsigned char*>(other.begin())),
235 e_(reinterpret_cast<const unsigned char*>(other.end())) {
238 template <class OtherIter, typename std::enable_if<
239 (std::is_same<Iter, const char*>::value &&
240 std::is_same<OtherIter, const unsigned char*>::value), int>::type = 0>
241 explicit Range(const Range<OtherIter>& other)
242 : b_(reinterpret_cast<const char*>(other.begin())),
243 e_(reinterpret_cast<const char*>(other.end())) {
251 void assign(Iter start, Iter end) {
256 void reset(Iter start, size_type size) {
261 // Works only for Range<const char*>
262 void reset(const std::string& str) {
263 reset(str.data(), str.size());
266 size_type size() const {
270 size_type walk_size() const {
272 return std::distance(b_, e_);
274 bool empty() const { return b_ == e_; }
275 Iter data() const { return b_; }
276 Iter start() const { return b_; }
277 Iter begin() const { return b_; }
278 Iter end() const { return e_; }
279 Iter cbegin() const { return b_; }
280 Iter cend() const { return e_; }
281 value_type& front() {
287 return detail::value_before(e_);
289 const value_type& front() const {
293 const value_type& back() const {
295 return detail::value_before(e_);
297 // Works only for Range<const char*>
298 std::string str() const { return std::string(b_, size()); }
299 std::string toString() const { return str(); }
300 // Works only for Range<const char*>
301 fbstring fbstr() const { return fbstring(b_, size()); }
302 fbstring toFbstring() const { return fbstr(); }
304 // Works only for Range<const char*>
305 int compare(const Range& o) const {
306 const size_type tsize = this->size();
307 const size_type osize = o.size();
308 const size_type msize = std::min(tsize, osize);
309 int r = traits_type::compare(data(), o.data(), msize);
310 if (r == 0) r = tsize - osize;
314 value_type& operator[](size_t i) {
319 const value_type& operator[](size_t i) const {
324 value_type& at(size_t i) {
325 if (i >= size()) throw std::out_of_range("index out of range");
329 const value_type& at(size_t i) const {
330 if (i >= size()) throw std::out_of_range("index out of range");
334 // Works only for Range<const char*>
335 uint32_t hash() const {
336 // Taken from fbi/nstring.h:
337 // Quick and dirty bernstein hash...fine for short ascii strings
338 uint32_t hash = 5381;
339 for (size_t ix = 0; ix < size(); ix++) {
340 hash = ((hash << 5) + hash) + b_[ix];
345 void advance(size_type n) {
346 if (UNLIKELY(n > size())) {
347 throw std::out_of_range("index out of range");
352 void subtract(size_type n) {
353 if (UNLIKELY(n > size())) {
354 throw std::out_of_range("index out of range");
369 Range subpiece(size_type first,
370 size_type length = std::string::npos) const {
371 if (UNLIKELY(first > size())) {
372 throw std::out_of_range("index out of range");
374 return Range(b_ + first,
375 std::min<std::string::size_type>(length, size() - first));
378 // string work-alike functions
379 size_type find(Range str) const {
380 return qfind(*this, str);
383 size_type find(Range str, size_t pos) const {
384 if (pos > size()) return std::string::npos;
385 size_t ret = qfind(subpiece(pos), str);
386 return ret == npos ? ret : ret + pos;
389 size_type find(Iter s, size_t pos, size_t n) const {
390 if (pos > size()) return std::string::npos;
391 size_t ret = qfind(pos ? subpiece(pos) : *this, Range(s, n));
392 return ret == npos ? ret : ret + pos;
395 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
396 size_type find(const Iter s) const {
397 return qfind(*this, Range(s));
400 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
401 size_type find(const Iter s, size_t pos) const {
402 if (pos > size()) return std::string::npos;
403 size_type ret = qfind(subpiece(pos), Range(s));
404 return ret == npos ? ret : ret + pos;
407 size_type find(value_type c) const {
408 return qfind(*this, c);
411 size_type rfind(value_type c) const {
412 return folly::rfind(*this, c);
415 size_type find(value_type c, size_t pos) const {
416 if (pos > size()) return std::string::npos;
417 size_type ret = qfind(subpiece(pos), c);
418 return ret == npos ? ret : ret + pos;
421 size_type find_first_of(Range needles) const {
422 return qfind_first_of(*this, needles);
425 size_type find_first_of(Range needles, size_t pos) const {
426 if (pos > size()) return std::string::npos;
427 size_type ret = qfind_first_of(subpiece(pos), needles);
428 return ret == npos ? ret : ret + pos;
431 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
432 size_type find_first_of(Iter needles) const {
433 return find_first_of(Range(needles));
436 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
437 size_type find_first_of(Iter needles, size_t pos) const {
438 return find_first_of(Range(needles), pos);
441 size_type find_first_of(Iter needles, size_t pos, size_t n) const {
442 return find_first_of(Range(needles, n), pos);
445 size_type find_first_of(value_type c) const {
449 size_type find_first_of(value_type c, size_t pos) const {
453 void swap(Range& rhs) {
454 std::swap(b_, rhs.b_);
455 std::swap(e_, rhs.e_);
459 * Does this Range start with another range?
461 bool startsWith(const Range& other) const {
462 return size() >= other.size() && subpiece(0, other.size()) == other;
464 bool startsWith(value_type c) const {
465 return !empty() && front() == c;
469 * Does this Range end with another range?
471 bool endsWith(const Range& other) const {
472 return size() >= other.size() && subpiece(size() - other.size()) == other;
474 bool endsWith(value_type c) const {
475 return !empty() && back() == c;
479 * Remove the given prefix and return true if the range starts with the given
480 * prefix; return false otherwise.
482 bool removePrefix(const Range& prefix) {
483 return startsWith(prefix) && (b_ += prefix.size(), true);
485 bool removePrefix(value_type prefix) {
486 return startsWith(prefix) && (++b_, true);
490 * Remove the given suffix and return true if the range ends with the given
491 * suffix; return false otherwise.
493 bool removeSuffix(const Range& suffix) {
494 return endsWith(suffix) && (e_ -= suffix.size(), true);
496 bool removeSuffix(value_type suffix) {
497 return endsWith(suffix) && (--e_, true);
504 template <class Iter>
505 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
508 void swap(Range<T>& lhs, Range<T>& rhs) {
513 * Create a range from two iterators, with type deduction.
515 template <class Iter>
516 Range<Iter> makeRange(Iter first, Iter last) {
517 return Range<Iter>(first, last);
520 typedef Range<const char*> StringPiece;
521 typedef Range<const unsigned char*> ByteRange;
523 std::ostream& operator<<(std::ostream& os, const StringPiece& piece);
526 * Templated comparison operators
530 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
531 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
535 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
536 return lhs.compare(rhs) < 0;
540 * Specializations of comparison operators for StringPiece
545 template <class A, class B>
546 struct ComparableAsStringPiece {
549 (std::is_convertible<A, StringPiece>::value
550 && std::is_same<B, StringPiece>::value)
552 (std::is_convertible<B, StringPiece>::value
553 && std::is_same<A, StringPiece>::value)
557 } // namespace detail
560 * operator== through conversion for Range<const char*>
562 template <class T, class U>
564 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
565 operator==(const T& lhs, const U& rhs) {
566 return StringPiece(lhs) == StringPiece(rhs);
570 * operator< through conversion for Range<const char*>
572 template <class T, class U>
574 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
575 operator<(const T& lhs, const U& rhs) {
576 return StringPiece(lhs) < StringPiece(rhs);
580 * operator> through conversion for Range<const char*>
582 template <class T, class U>
584 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
585 operator>(const T& lhs, const U& rhs) {
586 return StringPiece(lhs) > StringPiece(rhs);
590 * operator< through conversion for Range<const char*>
592 template <class T, class U>
594 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
595 operator<=(const T& lhs, const U& rhs) {
596 return StringPiece(lhs) <= StringPiece(rhs);
600 * operator> through conversion for Range<const char*>
602 template <class T, class U>
604 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
605 operator>=(const T& lhs, const U& rhs) {
606 return StringPiece(lhs) >= StringPiece(rhs);
609 struct StringPieceHash {
610 std::size_t operator()(const StringPiece& str) const {
611 return static_cast<std::size_t>(str.hash());
616 * Finds substrings faster than brute force by borrowing from Boyer-Moore
618 template <class T, class Comp>
619 size_t qfind(const Range<T>& haystack,
620 const Range<T>& needle,
622 // Don't use std::search, use a Boyer-Moore-like trick by comparing
623 // the last characters first
624 auto const nsize = needle.size();
625 if (haystack.size() < nsize) {
626 return std::string::npos;
628 if (!nsize) return 0;
629 auto const nsize_1 = nsize - 1;
630 auto const lastNeedle = needle[nsize_1];
632 // Boyer-Moore skip value for the last char in the needle. Zero is
633 // not a valid value; skip will be computed the first time it's
635 std::string::size_type skip = 0;
637 auto i = haystack.begin();
638 auto iEnd = haystack.end() - nsize_1;
641 // Boyer-Moore: match the last element in the needle
642 while (!eq(i[nsize_1], lastNeedle)) {
645 return std::string::npos;
648 // Here we know that the last char matches
649 // Continue in pedestrian mode
650 for (size_t j = 0; ; ) {
652 if (!eq(i[j], needle[j])) {
653 // Not found, we can skip
654 // Compute the skip value lazily
657 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
664 // Check if done searching
667 return i - haystack.begin();
671 return std::string::npos;
676 size_t qfind_first_byte_of_nosse(const StringPiece& haystack,
677 const StringPiece& needles);
679 #if FOLLY_HAVE_EMMINTRIN_H && __GNUC_PREREQ(4, 6)
680 size_t qfind_first_byte_of_sse42(const StringPiece& haystack,
681 const StringPiece& needles);
683 inline size_t qfind_first_byte_of(const StringPiece& haystack,
684 const StringPiece& needles) {
685 static auto const qfind_first_byte_of_fn =
686 folly::CpuId().sse42() ? qfind_first_byte_of_sse42
687 : qfind_first_byte_of_nosse;
688 return qfind_first_byte_of_fn(haystack, needles);
692 inline size_t qfind_first_byte_of(const StringPiece& haystack,
693 const StringPiece& needles) {
694 return qfind_first_byte_of_nosse(haystack, needles);
696 #endif // FOLLY_HAVE_EMMINTRIN_H
698 } // namespace detail
700 template <class T, class Comp>
701 size_t qfind_first_of(const Range<T> & haystack,
702 const Range<T> & needles,
704 auto ret = std::find_first_of(haystack.begin(), haystack.end(),
705 needles.begin(), needles.end(),
707 return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
710 struct AsciiCaseSensitive {
711 bool operator()(char lhs, char rhs) const {
716 struct AsciiCaseInsensitive {
717 bool operator()(char lhs, char rhs) const {
718 return toupper(lhs) == toupper(rhs);
722 extern const AsciiCaseSensitive asciiCaseSensitive;
723 extern const AsciiCaseInsensitive asciiCaseInsensitive;
726 size_t qfind(const Range<T>& haystack,
727 const typename Range<T>::value_type& needle) {
728 auto pos = std::find(haystack.begin(), haystack.end(), needle);
729 return pos == haystack.end() ? std::string::npos : pos - haystack.data();
733 size_t rfind(const Range<T>& haystack,
734 const typename Range<T>::value_type& needle) {
735 for (auto i = haystack.size(); i-- > 0; ) {
736 if (haystack[i] == needle) {
740 return std::string::npos;
743 // specialization for StringPiece
745 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
746 auto pos = static_cast<const char*>(
747 ::memchr(haystack.data(), needle, haystack.size()));
748 return pos == nullptr ? std::string::npos : pos - haystack.data();
751 #if FOLLY_HAVE_MEMRCHR
753 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
754 auto pos = static_cast<const char*>(
755 ::memrchr(haystack.data(), needle, haystack.size()));
756 return pos == nullptr ? std::string::npos : pos - haystack.data();
760 // specialization for ByteRange
762 inline size_t qfind(const Range<const unsigned char*>& haystack,
763 const unsigned char& needle) {
764 auto pos = static_cast<const unsigned char*>(
765 ::memchr(haystack.data(), needle, haystack.size()));
766 return pos == nullptr ? std::string::npos : pos - haystack.data();
769 #if FOLLY_HAVE_MEMRCHR
771 inline size_t rfind(const Range<const unsigned char*>& haystack,
772 const unsigned char& needle) {
773 auto pos = static_cast<const unsigned char*>(
774 ::memrchr(haystack.data(), needle, haystack.size()));
775 return pos == nullptr ? std::string::npos : pos - haystack.data();
780 size_t qfind_first_of(const Range<T>& haystack,
781 const Range<T>& needles) {
782 return qfind_first_of(haystack, needles, asciiCaseSensitive);
785 // specialization for StringPiece
787 inline size_t qfind_first_of(const Range<const char*>& haystack,
788 const Range<const char*>& needles) {
789 return detail::qfind_first_byte_of(haystack, needles);
792 // specialization for ByteRange
794 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
795 const Range<const unsigned char*>& needles) {
796 return detail::qfind_first_byte_of(StringPiece(haystack),
797 StringPiece(needles));
799 } // !namespace folly
801 #pragma GCC diagnostic pop
803 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);
805 #endif // FOLLY_RANGE_H_