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_);
462 template <class Iter>
463 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
466 void swap(Range<T>& lhs, Range<T>& rhs) {
471 * Create a range from two iterators, with type deduction.
473 template <class Iter>
474 Range<Iter> makeRange(Iter first, Iter last) {
475 return Range<Iter>(first, last);
478 typedef Range<const char*> StringPiece;
479 typedef Range<const unsigned char*> ByteRange;
481 std::ostream& operator<<(std::ostream& os, const StringPiece& piece);
484 * Templated comparison operators
488 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
489 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
493 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
494 return lhs.compare(rhs) < 0;
498 * Specializations of comparison operators for StringPiece
503 template <class A, class B>
504 struct ComparableAsStringPiece {
507 (std::is_convertible<A, StringPiece>::value
508 && std::is_same<B, StringPiece>::value)
510 (std::is_convertible<B, StringPiece>::value
511 && std::is_same<A, StringPiece>::value)
515 } // namespace detail
518 * operator== through conversion for Range<const char*>
520 template <class T, class U>
522 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
523 operator==(const T& lhs, const U& rhs) {
524 return StringPiece(lhs) == StringPiece(rhs);
528 * operator< through conversion for Range<const char*>
530 template <class T, class U>
532 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
533 operator<(const T& lhs, const U& rhs) {
534 return StringPiece(lhs) < StringPiece(rhs);
538 * operator> through conversion for Range<const char*>
540 template <class T, class U>
542 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
543 operator>(const T& lhs, const U& rhs) {
544 return StringPiece(lhs) > StringPiece(rhs);
548 * operator< through conversion for Range<const char*>
550 template <class T, class U>
552 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
553 operator<=(const T& lhs, const U& rhs) {
554 return StringPiece(lhs) <= StringPiece(rhs);
558 * operator> through conversion for Range<const char*>
560 template <class T, class U>
562 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
563 operator>=(const T& lhs, const U& rhs) {
564 return StringPiece(lhs) >= StringPiece(rhs);
567 struct StringPieceHash {
568 std::size_t operator()(const StringPiece& str) const {
569 return static_cast<std::size_t>(str.hash());
574 * Finds substrings faster than brute force by borrowing from Boyer-Moore
576 template <class T, class Comp>
577 size_t qfind(const Range<T>& haystack,
578 const Range<T>& needle,
580 // Don't use std::search, use a Boyer-Moore-like trick by comparing
581 // the last characters first
582 auto const nsize = needle.size();
583 if (haystack.size() < nsize) {
584 return std::string::npos;
586 if (!nsize) return 0;
587 auto const nsize_1 = nsize - 1;
588 auto const lastNeedle = needle[nsize_1];
590 // Boyer-Moore skip value for the last char in the needle. Zero is
591 // not a valid value; skip will be computed the first time it's
593 std::string::size_type skip = 0;
595 auto i = haystack.begin();
596 auto iEnd = haystack.end() - nsize_1;
599 // Boyer-Moore: match the last element in the needle
600 while (!eq(i[nsize_1], lastNeedle)) {
603 return std::string::npos;
606 // Here we know that the last char matches
607 // Continue in pedestrian mode
608 for (size_t j = 0; ; ) {
610 if (!eq(i[j], needle[j])) {
611 // Not found, we can skip
612 // Compute the skip value lazily
615 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
622 // Check if done searching
625 return i - haystack.begin();
629 return std::string::npos;
634 size_t qfind_first_byte_of_nosse(const StringPiece& haystack,
635 const StringPiece& needles);
637 #if FOLLY_HAVE_EMMINTRIN_H && __GNUC_PREREQ(4, 6)
638 size_t qfind_first_byte_of_sse42(const StringPiece& haystack,
639 const StringPiece& needles);
641 inline size_t qfind_first_byte_of(const StringPiece& haystack,
642 const StringPiece& needles) {
643 static auto const qfind_first_byte_of_fn =
644 folly::CpuId().sse42() ? qfind_first_byte_of_sse42
645 : qfind_first_byte_of_nosse;
646 return qfind_first_byte_of_fn(haystack, needles);
650 inline size_t qfind_first_byte_of(const StringPiece& haystack,
651 const StringPiece& needles) {
652 return qfind_first_byte_of_nosse(haystack, needles);
654 #endif // FOLLY_HAVE_EMMINTRIN_H
656 } // namespace detail
658 template <class T, class Comp>
659 size_t qfind_first_of(const Range<T> & haystack,
660 const Range<T> & needles,
662 auto ret = std::find_first_of(haystack.begin(), haystack.end(),
663 needles.begin(), needles.end(),
665 return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
668 struct AsciiCaseSensitive {
669 bool operator()(char lhs, char rhs) const {
674 struct AsciiCaseInsensitive {
675 bool operator()(char lhs, char rhs) const {
676 return toupper(lhs) == toupper(rhs);
680 extern const AsciiCaseSensitive asciiCaseSensitive;
681 extern const AsciiCaseInsensitive asciiCaseInsensitive;
684 size_t qfind(const Range<T>& haystack,
685 const typename Range<T>::value_type& needle) {
686 auto pos = std::find(haystack.begin(), haystack.end(), needle);
687 return pos == haystack.end() ? std::string::npos : pos - haystack.data();
691 size_t rfind(const Range<T>& haystack,
692 const typename Range<T>::value_type& needle) {
693 for (auto i = haystack.size(); i-- > 0; ) {
694 if (haystack[i] == needle) {
698 return std::string::npos;
701 // specialization for StringPiece
703 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
704 auto pos = static_cast<const char*>(
705 ::memchr(haystack.data(), needle, haystack.size()));
706 return pos == nullptr ? std::string::npos : pos - haystack.data();
709 #if FOLLY_HAVE_MEMRCHR
711 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
712 auto pos = static_cast<const char*>(
713 ::memrchr(haystack.data(), needle, haystack.size()));
714 return pos == nullptr ? std::string::npos : pos - haystack.data();
718 // specialization for ByteRange
720 inline size_t qfind(const Range<const unsigned char*>& haystack,
721 const unsigned char& needle) {
722 auto pos = static_cast<const unsigned char*>(
723 ::memchr(haystack.data(), needle, haystack.size()));
724 return pos == nullptr ? std::string::npos : pos - haystack.data();
727 #if FOLLY_HAVE_MEMRCHR
729 inline size_t rfind(const Range<const unsigned char*>& haystack,
730 const unsigned char& needle) {
731 auto pos = static_cast<const unsigned char*>(
732 ::memrchr(haystack.data(), needle, haystack.size()));
733 return pos == nullptr ? std::string::npos : pos - haystack.data();
738 size_t qfind_first_of(const Range<T>& haystack,
739 const Range<T>& needles) {
740 return qfind_first_of(haystack, needles, asciiCaseSensitive);
743 // specialization for StringPiece
745 inline size_t qfind_first_of(const Range<const char*>& haystack,
746 const Range<const char*>& needles) {
747 return detail::qfind_first_byte_of(haystack, needles);
750 // specialization for ByteRange
752 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
753 const Range<const unsigned char*>& needles) {
754 return detail::qfind_first_byte_of(StringPiece(haystack),
755 StringPiece(needles));
757 } // !namespace folly
759 #pragma GCC diagnostic pop
761 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);
763 #endif // FOLLY_RANGE_H_