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>
34 // libc++ doesn't provide this header
36 // This file appears in two locations: inside fbcode and in the
37 // libstdc++ source code (when embedding fbstring as std::string).
38 // To aid in this schizophrenic use, two macros are defined in
40 // _LIBSTDCXX_FBSTRING - Set inside libstdc++. This is useful to
41 // gate use inside fbcode v. libstdc++
42 #include <bits/c++config.h>
45 #include "folly/CpuId.h"
46 #include "folly/Traits.h"
47 #include "folly/Likely.h"
49 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
50 #pragma GCC diagnostic push
51 #pragma GCC diagnostic ignored "-Wshadow"
55 template <class T> class Range;
58 * Finds the first occurrence of needle in haystack. The algorithm is on
59 * average faster than O(haystack.size() * needle.size()) but not as fast
60 * as Boyer-Moore. On the upside, it does not do any upfront
61 * preprocessing and does not allocate memory.
63 template <class T, class Comp = std::equal_to<typename Range<T>::value_type>>
64 inline size_t qfind(const Range<T> & haystack,
65 const Range<T> & needle,
69 * Finds the first occurrence of needle in haystack. The result is the
70 * offset reported to the beginning of haystack, or string::npos if
71 * needle wasn't found.
74 size_t qfind(const Range<T> & haystack,
75 const typename Range<T>::value_type& needle);
78 * Finds the last occurrence of needle in haystack. The result is the
79 * offset reported to the beginning of haystack, or string::npos if
80 * needle wasn't found.
83 size_t rfind(const Range<T> & haystack,
84 const typename Range<T>::value_type& needle);
88 * Finds the first occurrence of any element of needle in
89 * haystack. The algorithm is O(haystack.size() * needle.size()).
92 inline size_t qfind_first_of(const Range<T> & haystack,
93 const Range<T> & needle);
96 * Small internal helper - returns the value just before an iterator.
101 * For random-access iterators, the value before is simply i[-1].
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) {
113 * For all other iterators, we need to use the decrement operator.
115 template <class Iter>
116 typename std::enable_if<
117 !std::is_same<typename std::iterator_traits<Iter>::iterator_category,
118 std::random_access_iterator_tag>::value,
119 typename std::iterator_traits<Iter>::reference>::type
120 value_before(Iter i) {
124 } // namespace detail
127 * Range abstraction keeping a pair of iterators. We couldn't use
128 * boost's similar range abstraction because we need an API identical
129 * with the former StringPiece class, which is used by a lot of other
130 * code. This abstraction does fulfill the needs of boost's
131 * range-oriented algorithms though.
133 * (Keep memory lifetime in mind when using this class, since it
134 * doesn't manage the data it refers to - just like an iterator
137 template <class Iter>
138 class Range : private boost::totally_ordered<Range<Iter> > {
140 typedef std::size_t size_type;
141 typedef Iter iterator;
142 typedef Iter const_iterator;
143 typedef typename std::remove_reference<
144 typename std::iterator_traits<Iter>::reference>::type
146 typedef typename std::iterator_traits<Iter>::reference reference;
147 typedef std::char_traits<typename std::remove_const<value_type>::type>
150 static const size_type npos;
152 // Works for all iterators
153 Range() : b_(), e_() {
157 // Works for all iterators
158 Range(Iter start, Iter end) : b_(start), e_(end) {
161 // Works only for random-access iterators
162 Range(Iter start, size_t size)
163 : b_(start), e_(start + size) { }
165 #if FOLLY_HAVE_CONSTEXPR_STRLEN
166 // Works only for Range<const char*>
167 /* implicit */ constexpr Range(Iter str)
168 : b_(str), e_(str + strlen(str)) {}
170 // Works only for Range<const char*>
171 /* implicit */ Range(Iter str)
172 : b_(str), e_(str + strlen(str)) {}
174 // Works only for Range<const char*>
175 /* implicit */ Range(const std::string& str)
176 : b_(str.data()), e_(b_ + str.size()) {}
177 // Works only for Range<const char*>
178 Range(const std::string& str, std::string::size_type startFrom) {
179 if (UNLIKELY(startFrom > str.size())) {
180 throw std::out_of_range("index out of range");
182 b_ = str.data() + startFrom;
183 e_ = str.data() + str.size();
185 // Works only for Range<const char*>
186 Range(const std::string& str,
187 std::string::size_type startFrom,
188 std::string::size_type size) {
189 if (UNLIKELY(startFrom > str.size())) {
190 throw std::out_of_range("index out of range");
192 b_ = str.data() + startFrom;
193 if (str.size() - startFrom < size) {
194 e_ = str.data() + str.size();
199 Range(const Range<Iter>& str,
202 if (UNLIKELY(startFrom > str.size())) {
203 throw std::out_of_range("index out of range");
205 b_ = str.b_ + startFrom;
206 if (str.size() - startFrom < size) {
212 // Works only for Range<const char*>
213 /* implicit */ Range(const fbstring& str)
214 : b_(str.data()), e_(b_ + str.size()) { }
215 // Works only for Range<const char*>
216 Range(const fbstring& str, fbstring::size_type startFrom) {
217 if (UNLIKELY(startFrom > str.size())) {
218 throw std::out_of_range("index out of range");
220 b_ = str.data() + startFrom;
221 e_ = str.data() + str.size();
223 // Works only for Range<const char*>
224 Range(const fbstring& str, fbstring::size_type startFrom,
225 fbstring::size_type size) {
226 if (UNLIKELY(startFrom > str.size())) {
227 throw std::out_of_range("index out of range");
229 b_ = str.data() + startFrom;
230 if (str.size() - startFrom < size) {
231 e_ = str.data() + str.size();
237 // Allow implicit conversion from Range<const char*> (aka StringPiece) to
238 // Range<const unsigned char*> (aka ByteRange), as they're both frequently
239 // used to represent ranges of bytes. Allow explicit conversion in the other
241 template <class OtherIter, typename std::enable_if<
242 (std::is_same<Iter, const unsigned char*>::value &&
243 std::is_same<OtherIter, const char*>::value), int>::type = 0>
244 /* implicit */ Range(const Range<OtherIter>& other)
245 : b_(reinterpret_cast<const unsigned char*>(other.begin())),
246 e_(reinterpret_cast<const unsigned char*>(other.end())) {
249 template <class OtherIter, typename std::enable_if<
250 (std::is_same<Iter, const char*>::value &&
251 std::is_same<OtherIter, const unsigned char*>::value), int>::type = 0>
252 explicit Range(const Range<OtherIter>& other)
253 : b_(reinterpret_cast<const char*>(other.begin())),
254 e_(reinterpret_cast<const char*>(other.end())) {
262 void assign(Iter start, Iter end) {
267 void reset(Iter start, size_type size) {
272 // Works only for Range<const char*>
273 void reset(const std::string& str) {
274 reset(str.data(), str.size());
277 size_type size() const {
281 size_type walk_size() const {
283 return std::distance(b_, e_);
285 bool empty() const { return b_ == e_; }
286 Iter data() const { return b_; }
287 Iter start() const { return b_; }
288 Iter begin() const { return b_; }
289 Iter end() const { return e_; }
290 Iter cbegin() const { return b_; }
291 Iter cend() const { return e_; }
292 value_type& front() {
298 return detail::value_before(e_);
300 const value_type& front() const {
304 const value_type& back() const {
306 return detail::value_before(e_);
308 // Works only for Range<const char*>
309 std::string str() const { return std::string(b_, size()); }
310 std::string toString() const { return str(); }
311 // Works only for Range<const char*>
312 fbstring fbstr() const { return fbstring(b_, size()); }
313 fbstring toFbstring() const { return fbstr(); }
315 // Works only for Range<const char*>
316 int compare(const Range& o) const {
317 const size_type tsize = this->size();
318 const size_type osize = o.size();
319 const size_type msize = std::min(tsize, osize);
320 int r = traits_type::compare(data(), o.data(), msize);
321 if (r == 0) r = tsize - osize;
325 value_type& operator[](size_t i) {
330 const value_type& operator[](size_t i) const {
335 value_type& at(size_t i) {
336 if (i >= size()) throw std::out_of_range("index out of range");
340 const value_type& at(size_t i) const {
341 if (i >= size()) throw std::out_of_range("index out of range");
345 // Works only for Range<const char*>
346 uint32_t hash() const {
347 // Taken from fbi/nstring.h:
348 // Quick and dirty bernstein hash...fine for short ascii strings
349 uint32_t hash = 5381;
350 for (size_t ix = 0; ix < size(); ix++) {
351 hash = ((hash << 5) + hash) + b_[ix];
356 void advance(size_type n) {
357 if (UNLIKELY(n > size())) {
358 throw std::out_of_range("index out of range");
363 void subtract(size_type n) {
364 if (UNLIKELY(n > size())) {
365 throw std::out_of_range("index out of range");
380 Range subpiece(size_type first,
381 size_type length = std::string::npos) const {
382 if (UNLIKELY(first > size())) {
383 throw std::out_of_range("index out of range");
385 return Range(b_ + first,
386 std::min<std::string::size_type>(length, size() - first));
389 // string work-alike functions
390 size_type find(Range str) const {
391 return qfind(*this, str);
394 size_type find(Range str, size_t pos) const {
395 if (pos > size()) return std::string::npos;
396 size_t ret = qfind(subpiece(pos), str);
397 return ret == npos ? ret : ret + pos;
400 size_type find(Iter s, size_t pos, size_t n) const {
401 if (pos > size()) return std::string::npos;
402 size_t ret = qfind(pos ? subpiece(pos) : *this, Range(s, n));
403 return ret == npos ? ret : ret + pos;
406 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
407 size_type find(const Iter s) const {
408 return qfind(*this, Range(s));
411 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
412 size_type find(const Iter s, size_t pos) const {
413 if (pos > size()) return std::string::npos;
414 size_type ret = qfind(subpiece(pos), Range(s));
415 return ret == npos ? ret : ret + pos;
418 size_type find(value_type c) const {
419 return qfind(*this, c);
422 size_type rfind(value_type c) const {
423 return folly::rfind(*this, c);
426 size_type find(value_type c, size_t pos) const {
427 if (pos > size()) return std::string::npos;
428 size_type ret = qfind(subpiece(pos), c);
429 return ret == npos ? ret : ret + pos;
432 size_type find_first_of(Range needles) const {
433 return qfind_first_of(*this, needles);
436 size_type find_first_of(Range needles, size_t pos) const {
437 if (pos > size()) return std::string::npos;
438 size_type ret = qfind_first_of(subpiece(pos), needles);
439 return ret == npos ? ret : ret + pos;
442 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
443 size_type find_first_of(Iter needles) const {
444 return find_first_of(Range(needles));
447 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
448 size_type find_first_of(Iter needles, size_t pos) const {
449 return find_first_of(Range(needles), pos);
452 size_type find_first_of(Iter needles, size_t pos, size_t n) const {
453 return find_first_of(Range(needles, n), pos);
456 size_type find_first_of(value_type c) const {
460 size_type find_first_of(value_type c, size_t pos) const {
464 void swap(Range& rhs) {
465 std::swap(b_, rhs.b_);
466 std::swap(e_, rhs.e_);
473 template <class Iter>
474 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
477 void swap(Range<T>& lhs, Range<T>& rhs) {
482 * Create a range from two iterators, with type deduction.
484 template <class Iter>
485 Range<Iter> makeRange(Iter first, Iter last) {
486 return Range<Iter>(first, last);
489 typedef Range<const char*> StringPiece;
490 typedef Range<const unsigned char*> ByteRange;
492 std::ostream& operator<<(std::ostream& os, const StringPiece& piece);
495 * Templated comparison operators
499 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
500 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
504 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
505 return lhs.compare(rhs) < 0;
509 * Specializations of comparison operators for StringPiece
514 template <class A, class B>
515 struct ComparableAsStringPiece {
518 (std::is_convertible<A, StringPiece>::value
519 && std::is_same<B, StringPiece>::value)
521 (std::is_convertible<B, StringPiece>::value
522 && std::is_same<A, StringPiece>::value)
526 } // namespace detail
529 * operator== through conversion for Range<const char*>
531 template <class T, class U>
533 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
534 operator==(const T& lhs, const U& rhs) {
535 return StringPiece(lhs) == StringPiece(rhs);
539 * operator< through conversion for Range<const char*>
541 template <class T, class U>
543 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
544 operator<(const T& lhs, const U& rhs) {
545 return StringPiece(lhs) < StringPiece(rhs);
549 * operator> through conversion for Range<const char*>
551 template <class T, class U>
553 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
554 operator>(const T& lhs, const U& rhs) {
555 return StringPiece(lhs) > StringPiece(rhs);
559 * operator< through conversion for Range<const char*>
561 template <class T, class U>
563 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
564 operator<=(const T& lhs, const U& rhs) {
565 return StringPiece(lhs) <= StringPiece(rhs);
569 * operator> through conversion for Range<const char*>
571 template <class T, class U>
573 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
574 operator>=(const T& lhs, const U& rhs) {
575 return StringPiece(lhs) >= StringPiece(rhs);
578 struct StringPieceHash {
579 std::size_t operator()(const StringPiece& str) const {
580 return static_cast<std::size_t>(str.hash());
585 * Finds substrings faster than brute force by borrowing from Boyer-Moore
587 template <class T, class Comp>
588 size_t qfind(const Range<T>& haystack,
589 const Range<T>& needle,
591 // Don't use std::search, use a Boyer-Moore-like trick by comparing
592 // the last characters first
593 auto const nsize = needle.size();
594 if (haystack.size() < nsize) {
595 return std::string::npos;
597 if (!nsize) return 0;
598 auto const nsize_1 = nsize - 1;
599 auto const lastNeedle = needle[nsize_1];
601 // Boyer-Moore skip value for the last char in the needle. Zero is
602 // not a valid value; skip will be computed the first time it's
604 std::string::size_type skip = 0;
606 auto i = haystack.begin();
607 auto iEnd = haystack.end() - nsize_1;
610 // Boyer-Moore: match the last element in the needle
611 while (!eq(i[nsize_1], lastNeedle)) {
614 return std::string::npos;
617 // Here we know that the last char matches
618 // Continue in pedestrian mode
619 for (size_t j = 0; ; ) {
621 if (!eq(i[j], needle[j])) {
622 // Not found, we can skip
623 // Compute the skip value lazily
626 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
633 // Check if done searching
636 return i - haystack.begin();
640 return std::string::npos;
645 size_t qfind_first_byte_of_nosse(const StringPiece& haystack,
646 const StringPiece& needles);
648 #if FOLLY_HAVE_EMMINTRIN_H && __GNUC_PREREQ(4, 6)
649 size_t qfind_first_byte_of_sse42(const StringPiece& haystack,
650 const StringPiece& needles);
652 inline size_t qfind_first_byte_of(const StringPiece& haystack,
653 const StringPiece& needles) {
654 static auto const qfind_first_byte_of_fn =
655 folly::CpuId().sse42() ? qfind_first_byte_of_sse42
656 : qfind_first_byte_of_nosse;
657 return qfind_first_byte_of_fn(haystack, needles);
661 inline size_t qfind_first_byte_of(const StringPiece& haystack,
662 const StringPiece& needles) {
663 return qfind_first_byte_of_nosse(haystack, needles);
665 #endif // FOLLY_HAVE_EMMINTRIN_H
667 } // namespace detail
669 template <class T, class Comp>
670 size_t qfind_first_of(const Range<T> & haystack,
671 const Range<T> & needles,
673 auto ret = std::find_first_of(haystack.begin(), haystack.end(),
674 needles.begin(), needles.end(),
676 return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
679 struct AsciiCaseSensitive {
680 bool operator()(char lhs, char rhs) const {
685 struct AsciiCaseInsensitive {
686 bool operator()(char lhs, char rhs) const {
687 return toupper(lhs) == toupper(rhs);
691 extern const AsciiCaseSensitive asciiCaseSensitive;
692 extern const AsciiCaseInsensitive asciiCaseInsensitive;
695 size_t qfind(const Range<T>& haystack,
696 const typename Range<T>::value_type& needle) {
697 auto pos = std::find(haystack.begin(), haystack.end(), needle);
698 return pos == haystack.end() ? std::string::npos : pos - haystack.data();
702 size_t rfind(const Range<T>& haystack,
703 const typename Range<T>::value_type& needle) {
704 for (auto i = haystack.size(); i-- > 0; ) {
705 if (haystack[i] == needle) {
709 return std::string::npos;
712 // specialization for StringPiece
714 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
715 auto pos = static_cast<const char*>(
716 ::memchr(haystack.data(), needle, haystack.size()));
717 return pos == nullptr ? std::string::npos : pos - haystack.data();
720 #if FOLLY_HAVE_MEMRCHR
722 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
723 auto pos = static_cast<const char*>(
724 ::memrchr(haystack.data(), needle, haystack.size()));
725 return pos == nullptr ? std::string::npos : pos - haystack.data();
729 // specialization for ByteRange
731 inline size_t qfind(const Range<const unsigned char*>& haystack,
732 const unsigned char& needle) {
733 auto pos = static_cast<const unsigned char*>(
734 ::memchr(haystack.data(), needle, haystack.size()));
735 return pos == nullptr ? std::string::npos : pos - haystack.data();
738 #if FOLLY_HAVE_MEMRCHR
740 inline size_t rfind(const Range<const unsigned char*>& haystack,
741 const unsigned char& needle) {
742 auto pos = static_cast<const unsigned char*>(
743 ::memrchr(haystack.data(), needle, haystack.size()));
744 return pos == nullptr ? std::string::npos : pos - haystack.data();
749 size_t qfind_first_of(const Range<T>& haystack,
750 const Range<T>& needles) {
751 return qfind_first_of(haystack, needles, asciiCaseSensitive);
754 // specialization for StringPiece
756 inline size_t qfind_first_of(const Range<const char*>& haystack,
757 const Range<const char*>& needles) {
758 return detail::qfind_first_byte_of(haystack, needles);
761 // specialization for ByteRange
763 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
764 const Range<const unsigned char*>& needles) {
765 return detail::qfind_first_byte_of(StringPiece(haystack),
766 StringPiece(needles));
768 } // !namespace folly
770 #pragma GCC diagnostic pop
772 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);
774 #endif // FOLLY_RANGE_H_