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.
53 inline size_t qfind(const Range<T> & haystack,
54 const Range<T> & needle);
57 * Finds the first occurrence of needle in haystack. The result is the
58 * offset reported to the beginning of haystack, or string::npos if
59 * needle wasn't found.
62 size_t qfind(const Range<T> & haystack,
63 const typename Range<T>::value_type& needle);
66 * Finds the last occurrence of needle in haystack. The result is the
67 * offset reported to the beginning of haystack, or string::npos if
68 * needle wasn't found.
71 size_t rfind(const Range<T> & haystack,
72 const typename Range<T>::value_type& needle);
76 * Finds the first occurrence of any element of needle in
77 * haystack. The algorithm is O(haystack.size() * needle.size()).
80 inline size_t qfind_first_of(const Range<T> & haystack,
81 const Range<T> & needle);
84 * Small internal helper - returns the value just before an iterator.
89 * For random-access iterators, the value before is simply i[-1].
92 typename std::enable_if<
93 std::is_same<typename std::iterator_traits<Iter>::iterator_category,
94 std::random_access_iterator_tag>::value,
95 typename std::iterator_traits<Iter>::reference>::type
96 value_before(Iter i) {
101 * For all other iterators, we need to use the decrement operator.
103 template <class Iter>
104 typename std::enable_if<
105 !std::is_same<typename std::iterator_traits<Iter>::iterator_category,
106 std::random_access_iterator_tag>::value,
107 typename std::iterator_traits<Iter>::reference>::type
108 value_before(Iter i) {
112 } // namespace detail
115 * Range abstraction keeping a pair of iterators. We couldn't use
116 * boost's similar range abstraction because we need an API identical
117 * with the former StringPiece class, which is used by a lot of other
118 * code. This abstraction does fulfill the needs of boost's
119 * range-oriented algorithms though.
121 * (Keep memory lifetime in mind when using this class, since it
122 * doesn't manage the data it refers to - just like an iterator
125 template <class Iter>
126 class Range : private boost::totally_ordered<Range<Iter> > {
128 typedef std::size_t size_type;
129 typedef Iter iterator;
130 typedef Iter const_iterator;
131 typedef typename std::remove_reference<
132 typename std::iterator_traits<Iter>::reference>::type
134 typedef typename std::iterator_traits<Iter>::reference reference;
135 typedef std::char_traits<typename std::remove_const<value_type>::type>
138 static const size_type npos;
140 // Works for all iterators
141 Range() : b_(), e_() {
145 // Works for all iterators
146 Range(Iter start, Iter end) : b_(start), e_(end) {
149 // Works only for random-access iterators
150 Range(Iter start, size_t size)
151 : b_(start), e_(start + size) { }
153 // Works only for Range<const char*>
154 /* implicit */ Range(Iter str)
155 : b_(str), e_(b_ + strlen(str)) {}
156 // Works only for Range<const char*>
157 /* implicit */ Range(const std::string& str)
158 : b_(str.data()), e_(b_ + str.size()) {}
159 // Works only for Range<const char*>
160 Range(const std::string& str, std::string::size_type startFrom) {
161 if (UNLIKELY(startFrom > str.size())) {
162 throw std::out_of_range("index out of range");
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 if (UNLIKELY(startFrom > str.size())) {
172 throw std::out_of_range("index out of range");
174 b_ = str.data() + startFrom;
175 if (str.size() - startFrom < size) {
176 e_ = str.data() + str.size();
181 Range(const Range<Iter>& str,
184 if (UNLIKELY(startFrom > str.size())) {
185 throw std::out_of_range("index out of range");
187 b_ = str.b_ + startFrom;
188 if (str.size() - startFrom < size) {
194 // Works only for Range<const char*>
195 /* implicit */ Range(const fbstring& str)
196 : b_(str.data()), e_(b_ + str.size()) { }
197 // Works only for Range<const char*>
198 Range(const fbstring& str, fbstring::size_type startFrom) {
199 if (UNLIKELY(startFrom > str.size())) {
200 throw std::out_of_range("index out of range");
202 b_ = str.data() + startFrom;
203 e_ = str.data() + str.size();
205 // Works only for Range<const char*>
206 Range(const fbstring& str, fbstring::size_type startFrom,
207 fbstring::size_type size) {
208 if (UNLIKELY(startFrom > str.size())) {
209 throw std::out_of_range("index out of range");
211 b_ = str.data() + startFrom;
212 if (str.size() - startFrom < size) {
213 e_ = str.data() + str.size();
219 // Allow implicit conversion from Range<const char*> (aka StringPiece) to
220 // Range<const unsigned char*> (aka ByteRange), as they're both frequently
221 // used to represent ranges of bytes. Allow explicit conversion in the other
223 template <class OtherIter, typename std::enable_if<
224 (std::is_same<Iter, const unsigned char*>::value &&
225 std::is_same<OtherIter, const char*>::value), int>::type = 0>
226 /* implicit */ Range(const Range<OtherIter>& other)
227 : b_(reinterpret_cast<const unsigned char*>(other.begin())),
228 e_(reinterpret_cast<const unsigned char*>(other.end())) {
231 template <class OtherIter, typename std::enable_if<
232 (std::is_same<Iter, const char*>::value &&
233 std::is_same<OtherIter, const unsigned char*>::value), int>::type = 0>
234 explicit Range(const Range<OtherIter>& other)
235 : b_(reinterpret_cast<const char*>(other.begin())),
236 e_(reinterpret_cast<const char*>(other.end())) {
244 void assign(Iter start, Iter end) {
249 void reset(Iter start, size_type size) {
254 // Works only for Range<const char*>
255 void reset(const std::string& str) {
256 reset(str.data(), str.size());
259 size_type size() const {
263 size_type walk_size() const {
265 return std::distance(b_, e_);
267 bool empty() const { return b_ == e_; }
268 Iter data() const { return b_; }
269 Iter start() const { return b_; }
270 Iter begin() const { return b_; }
271 Iter end() const { return e_; }
272 Iter cbegin() const { return b_; }
273 Iter cend() const { return e_; }
274 value_type& front() {
280 return detail::value_before(e_);
282 const value_type& front() const {
286 const value_type& back() const {
288 return detail::value_before(e_);
290 // Works only for Range<const char*>
291 std::string str() const { return std::string(b_, size()); }
292 std::string toString() const { return str(); }
293 // Works only for Range<const char*>
294 fbstring fbstr() const { return fbstring(b_, size()); }
295 fbstring toFbstring() const { return fbstr(); }
297 // Works only for Range<const char*>
298 int compare(const Range& o) const {
299 const size_type tsize = this->size();
300 const size_type osize = o.size();
301 const size_type msize = std::min(tsize, osize);
302 int r = traits_type::compare(data(), o.data(), msize);
303 if (r == 0) r = tsize - osize;
307 value_type& operator[](size_t i) {
312 const value_type& operator[](size_t i) const {
317 value_type& at(size_t i) {
318 if (i >= size()) throw std::out_of_range("index out of range");
322 const value_type& at(size_t i) const {
323 if (i >= size()) throw std::out_of_range("index out of range");
327 // Works only for Range<const char*>
328 uint32_t hash() const {
329 // Taken from fbi/nstring.h:
330 // Quick and dirty bernstein hash...fine for short ascii strings
331 uint32_t hash = 5381;
332 for (size_t ix = 0; ix < size(); ix++) {
333 hash = ((hash << 5) + hash) + b_[ix];
338 void advance(size_type n) {
339 if (UNLIKELY(n > size())) {
340 throw std::out_of_range("index out of range");
345 void subtract(size_type n) {
346 if (UNLIKELY(n > size())) {
347 throw std::out_of_range("index out of range");
362 Range subpiece(size_type first,
363 size_type length = std::string::npos) const {
364 if (UNLIKELY(first > size())) {
365 throw std::out_of_range("index out of range");
367 return Range(b_ + first,
368 std::min<std::string::size_type>(length, size() - first));
371 // string work-alike functions
372 size_type find(Range str) const {
373 return qfind(*this, str);
376 size_type find(Range str, size_t pos) const {
377 if (pos > size()) return std::string::npos;
378 size_t ret = qfind(subpiece(pos), str);
379 return ret == npos ? ret : ret + pos;
382 size_type find(Iter s, size_t pos, size_t n) const {
383 if (pos > size()) return std::string::npos;
384 size_t ret = qfind(pos ? subpiece(pos) : *this, Range(s, n));
385 return ret == npos ? ret : ret + pos;
388 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
389 size_type find(const Iter s) const {
390 return qfind(*this, Range(s));
393 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
394 size_type find(const Iter s, size_t pos) const {
395 if (pos > size()) return std::string::npos;
396 size_type ret = qfind(subpiece(pos), Range(s));
397 return ret == npos ? ret : ret + pos;
400 size_type find(value_type c) const {
401 return qfind(*this, c);
404 size_type rfind(value_type c) const {
405 return folly::rfind(*this, c);
408 size_type find(value_type c, size_t pos) const {
409 if (pos > size()) return std::string::npos;
410 size_type ret = qfind(subpiece(pos), c);
411 return ret == npos ? ret : ret + pos;
414 size_type find_first_of(Range needles) const {
415 return qfind_first_of(*this, needles);
418 size_type find_first_of(Range needles, size_t pos) const {
419 if (pos > size()) return std::string::npos;
420 size_type ret = qfind_first_of(subpiece(pos), needles);
421 return ret == npos ? ret : ret + pos;
424 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
425 size_type find_first_of(Iter needles) const {
426 return find_first_of(Range(needles));
429 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
430 size_type find_first_of(Iter needles, size_t pos) const {
431 return find_first_of(Range(needles), pos);
434 size_type find_first_of(Iter needles, size_t pos, size_t n) const {
435 return find_first_of(Range(needles, n), pos);
438 size_type find_first_of(value_type c) const {
442 size_type find_first_of(value_type c, size_t pos) const {
446 void swap(Range& rhs) {
447 std::swap(b_, rhs.b_);
448 std::swap(e_, rhs.e_);
455 template <class Iter>
456 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
459 void swap(Range<T>& lhs, Range<T>& rhs) {
464 * Create a range from two iterators, with type deduction.
466 template <class Iter>
467 Range<Iter> makeRange(Iter first, Iter last) {
468 return Range<Iter>(first, last);
471 typedef Range<const char*> StringPiece;
472 typedef Range<const unsigned char*> ByteRange;
474 std::ostream& operator<<(std::ostream& os, const StringPiece& piece);
477 * Templated comparison operators
481 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
482 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
486 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
487 return lhs.compare(rhs) < 0;
491 * Specializations of comparison operators for StringPiece
496 template <class A, class B>
497 struct ComparableAsStringPiece {
500 (std::is_convertible<A, StringPiece>::value
501 && std::is_same<B, StringPiece>::value)
503 (std::is_convertible<B, StringPiece>::value
504 && std::is_same<A, StringPiece>::value)
508 } // namespace detail
511 * operator== through conversion for Range<const char*>
513 template <class T, class U>
515 std::enable_if<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 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
526 operator<(const T& lhs, const U& rhs) {
527 return StringPiece(lhs) < StringPiece(rhs);
531 * operator> through conversion for Range<const char*>
533 template <class T, class U>
535 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
536 operator>(const T& lhs, const U& rhs) {
537 return StringPiece(lhs) > StringPiece(rhs);
541 * operator< through conversion for Range<const char*>
543 template <class T, class U>
545 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
546 operator<=(const T& lhs, const U& rhs) {
547 return StringPiece(lhs) <= StringPiece(rhs);
551 * operator> through conversion for Range<const char*>
553 template <class T, class U>
555 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
556 operator>=(const T& lhs, const U& rhs) {
557 return StringPiece(lhs) >= StringPiece(rhs);
560 struct StringPieceHash {
561 std::size_t operator()(const StringPiece& str) const {
562 return static_cast<std::size_t>(str.hash());
567 * Finds substrings faster than brute force by borrowing from Boyer-Moore
569 template <class T, class Comp>
570 size_t qfind(const Range<T>& haystack,
571 const Range<T>& needle,
573 // Don't use std::search, use a Boyer-Moore-like trick by comparing
574 // the last characters first
575 auto const nsize = needle.size();
576 if (haystack.size() < nsize) {
577 return std::string::npos;
579 if (!nsize) return 0;
580 auto const nsize_1 = nsize - 1;
581 auto const lastNeedle = needle[nsize_1];
583 // Boyer-Moore skip value for the last char in the needle. Zero is
584 // not a valid value; skip will be computed the first time it's
586 std::string::size_type skip = 0;
588 auto i = haystack.begin();
589 auto iEnd = haystack.end() - nsize_1;
592 // Boyer-Moore: match the last element in the needle
593 while (!eq(i[nsize_1], lastNeedle)) {
596 return std::string::npos;
599 // Here we know that the last char matches
600 // Continue in pedestrian mode
601 for (size_t j = 0; ; ) {
603 if (!eq(i[j], needle[j])) {
604 // Not found, we can skip
605 // Compute the skip value lazily
608 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
615 // Check if done searching
618 return i - haystack.begin();
622 return std::string::npos;
627 size_t qfind_first_byte_of_nosse(const StringPiece& haystack,
628 const StringPiece& needles);
630 #if FOLLY_HAVE_EMMINTRIN_H
631 size_t qfind_first_byte_of_sse42(const StringPiece& haystack,
632 const StringPiece& needles);
634 inline size_t qfind_first_byte_of(const StringPiece& haystack,
635 const StringPiece& needles) {
636 static auto const qfind_first_byte_of_fn =
637 folly::CpuId().sse42() ? qfind_first_byte_of_sse42
638 : qfind_first_byte_of_nosse;
639 return qfind_first_byte_of_fn(haystack, needles);
643 inline size_t qfind_first_byte_of(const StringPiece& haystack,
644 const StringPiece& needles) {
645 return qfind_first_byte_of_nosse(haystack, needles);
647 #endif // FOLLY_HAVE_EMMINTRIN_H
649 } // namespace detail
651 template <class T, class Comp>
652 size_t qfind_first_of(const Range<T> & haystack,
653 const Range<T> & needles,
655 auto ret = std::find_first_of(haystack.begin(), haystack.end(),
656 needles.begin(), needles.end(),
658 return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
661 struct AsciiCaseSensitive {
662 bool operator()(char lhs, char rhs) const {
667 struct AsciiCaseInsensitive {
668 bool operator()(char lhs, char rhs) const {
669 return toupper(lhs) == toupper(rhs);
673 extern const AsciiCaseSensitive asciiCaseSensitive;
674 extern const AsciiCaseInsensitive asciiCaseInsensitive;
677 size_t qfind(const Range<T>& haystack,
678 const Range<T>& needle) {
679 return qfind(haystack, needle, asciiCaseSensitive);
683 size_t qfind(const Range<T>& haystack,
684 const typename Range<T>::value_type& needle) {
685 auto pos = std::find(haystack.begin(), haystack.end(), needle);
686 return pos == haystack.end() ? std::string::npos : pos - haystack.data();
690 size_t rfind(const Range<T>& haystack,
691 const typename Range<T>::value_type& needle) {
692 for (auto i = haystack.size(); i-- > 0; ) {
693 if (haystack[i] == needle) {
697 return std::string::npos;
700 // specialization for StringPiece
702 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
703 auto pos = static_cast<const char*>(
704 ::memchr(haystack.data(), needle, haystack.size()));
705 return pos == nullptr ? std::string::npos : pos - haystack.data();
708 #ifdef _GNU_SOURCE // memrchr is a GNU extension
710 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
711 auto pos = static_cast<const char*>(
712 ::memrchr(haystack.data(), needle, haystack.size()));
713 return pos == nullptr ? std::string::npos : pos - haystack.data();
717 // specialization for ByteRange
719 inline size_t qfind(const Range<const unsigned char*>& haystack,
720 const unsigned char& needle) {
721 auto pos = static_cast<const unsigned char*>(
722 ::memchr(haystack.data(), needle, haystack.size()));
723 return pos == nullptr ? std::string::npos : pos - haystack.data();
726 #ifdef _GNU_SOURCE // memrchr is a GNU extension
728 inline size_t rfind(const Range<const unsigned char*>& haystack,
729 const unsigned char& needle) {
730 auto pos = static_cast<const unsigned char*>(
731 ::memrchr(haystack.data(), needle, haystack.size()));
732 return pos == nullptr ? std::string::npos : pos - haystack.data();
737 size_t qfind_first_of(const Range<T>& haystack,
738 const Range<T>& needles) {
739 return qfind_first_of(haystack, needles, asciiCaseSensitive);
742 // specialization for StringPiece
744 inline size_t qfind_first_of(const Range<const char*>& haystack,
745 const Range<const char*>& needles) {
746 return detail::qfind_first_byte_of(haystack, needles);
749 // specialization for ByteRange
751 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
752 const Range<const unsigned char*>& needles) {
753 return detail::qfind_first_byte_of(StringPiece(haystack),
754 StringPiece(needles));
756 } // !namespace folly
758 #pragma GCC diagnostic pop
760 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);
762 #endif // FOLLY_RANGE_H_