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);
67 * Finds the first occurrence of any element of needle in
68 * haystack. The algorithm is O(haystack.size() * needle.size()).
71 inline size_t qfind_first_of(const Range<T> & haystack,
72 const Range<T> & needle);
75 * Small internal helper - returns the value just before an iterator.
80 * For random-access iterators, the value before is simply i[-1].
83 typename std::enable_if<
84 std::is_same<typename std::iterator_traits<Iter>::iterator_category,
85 std::random_access_iterator_tag>::value,
86 typename std::iterator_traits<Iter>::reference>::type
87 value_before(Iter i) {
92 * For all other iterators, we need to use the decrement operator.
95 typename std::enable_if<
96 !std::is_same<typename std::iterator_traits<Iter>::iterator_category,
97 std::random_access_iterator_tag>::value,
98 typename std::iterator_traits<Iter>::reference>::type
99 value_before(Iter i) {
103 } // namespace detail
106 * Range abstraction keeping a pair of iterators. We couldn't use
107 * boost's similar range abstraction because we need an API identical
108 * with the former StringPiece class, which is used by a lot of other
109 * code. This abstraction does fulfill the needs of boost's
110 * range-oriented algorithms though.
112 * (Keep memory lifetime in mind when using this class, since it
113 * doesn't manage the data it refers to - just like an iterator
116 template <class Iter>
117 class Range : private boost::totally_ordered<Range<Iter> > {
119 typedef std::size_t size_type;
120 typedef Iter iterator;
121 typedef Iter const_iterator;
122 typedef typename std::remove_reference<
123 typename std::iterator_traits<Iter>::reference>::type
125 typedef typename std::iterator_traits<Iter>::reference reference;
126 typedef std::char_traits<typename std::remove_const<value_type>::type>
129 static const size_type npos;
131 // Works for all iterators
132 Range() : b_(), e_() {
136 // Works for all iterators
137 Range(Iter start, Iter end) : b_(start), e_(end) {
140 // Works only for random-access iterators
141 Range(Iter start, size_t size)
142 : b_(start), e_(start + size) { }
144 // Works only for Range<const char*>
145 /* implicit */ Range(Iter str)
146 : b_(str), e_(b_ + strlen(str)) {}
147 // Works only for Range<const char*>
148 /* implicit */ Range(const std::string& str)
149 : b_(str.data()), e_(b_ + str.size()) {}
150 // Works only for Range<const char*>
151 Range(const std::string& str, std::string::size_type startFrom) {
152 if (UNLIKELY(startFrom > str.size())) {
153 throw std::out_of_range("index out of range");
155 b_ = str.data() + startFrom;
156 e_ = str.data() + str.size();
158 // Works only for Range<const char*>
159 Range(const std::string& str,
160 std::string::size_type startFrom,
161 std::string::size_type size) {
162 if (UNLIKELY(startFrom > str.size())) {
163 throw std::out_of_range("index out of range");
165 b_ = str.data() + startFrom;
166 if (str.size() - startFrom < size) {
167 e_ = str.data() + str.size();
172 Range(const Range<Iter>& str,
175 if (UNLIKELY(startFrom > str.size())) {
176 throw std::out_of_range("index out of range");
178 b_ = str.b_ + startFrom;
179 if (str.size() - startFrom < size) {
185 // Works only for Range<const char*>
186 /* implicit */ Range(const fbstring& str)
187 : b_(str.data()), e_(b_ + str.size()) { }
188 // Works only for Range<const char*>
189 Range(const fbstring& str, fbstring::size_type startFrom) {
190 if (UNLIKELY(startFrom > str.size())) {
191 throw std::out_of_range("index out of range");
193 b_ = str.data() + startFrom;
194 e_ = str.data() + str.size();
196 // Works only for Range<const char*>
197 Range(const fbstring& str, fbstring::size_type startFrom,
198 fbstring::size_type size) {
199 if (UNLIKELY(startFrom > str.size())) {
200 throw std::out_of_range("index out of range");
202 b_ = str.data() + startFrom;
203 if (str.size() - startFrom < size) {
204 e_ = str.data() + str.size();
210 // Allow implicit conversion from Range<const char*> (aka StringPiece) to
211 // Range<const unsigned char*> (aka ByteRange), as they're both frequently
212 // used to represent ranges of bytes. Allow explicit conversion in the other
214 template <class OtherIter, typename std::enable_if<
215 (std::is_same<Iter, const unsigned char*>::value &&
216 std::is_same<OtherIter, const char*>::value), int>::type = 0>
217 /* implicit */ Range(const Range<OtherIter>& other)
218 : b_(reinterpret_cast<const unsigned char*>(other.begin())),
219 e_(reinterpret_cast<const unsigned char*>(other.end())) {
222 template <class OtherIter, typename std::enable_if<
223 (std::is_same<Iter, const char*>::value &&
224 std::is_same<OtherIter, const unsigned char*>::value), int>::type = 0>
225 explicit Range(const Range<OtherIter>& other)
226 : b_(reinterpret_cast<const char*>(other.begin())),
227 e_(reinterpret_cast<const char*>(other.end())) {
235 void assign(Iter start, Iter end) {
240 void reset(Iter start, size_type size) {
245 // Works only for Range<const char*>
246 void reset(const std::string& str) {
247 reset(str.data(), str.size());
250 size_type size() const {
254 size_type walk_size() const {
256 return std::distance(b_, e_);
258 bool empty() const { return b_ == e_; }
259 Iter data() const { return b_; }
260 Iter start() const { return b_; }
261 Iter begin() const { return b_; }
262 Iter end() const { return e_; }
263 Iter cbegin() const { return b_; }
264 Iter cend() const { return e_; }
265 value_type& front() {
271 return detail::value_before(e_);
273 const value_type& front() const {
277 const value_type& back() const {
279 return detail::value_before(e_);
281 // Works only for Range<const char*>
282 std::string str() const { return std::string(b_, size()); }
283 std::string toString() const { return str(); }
284 // Works only for Range<const char*>
285 fbstring fbstr() const { return fbstring(b_, size()); }
286 fbstring toFbstring() const { return fbstr(); }
288 // Works only for Range<const char*>
289 int compare(const Range& o) const {
290 const size_type tsize = this->size();
291 const size_type osize = o.size();
292 const size_type msize = std::min(tsize, osize);
293 int r = traits_type::compare(data(), o.data(), msize);
294 if (r == 0) r = tsize - osize;
298 value_type& operator[](size_t i) {
303 const value_type& operator[](size_t i) const {
308 value_type& at(size_t i) {
309 if (i >= size()) throw std::out_of_range("index out of range");
313 const value_type& at(size_t i) const {
314 if (i >= size()) throw std::out_of_range("index out of range");
318 // Works only for Range<const char*>
319 uint32_t hash() const {
320 // Taken from fbi/nstring.h:
321 // Quick and dirty bernstein hash...fine for short ascii strings
322 uint32_t hash = 5381;
323 for (size_t ix = 0; ix < size(); ix++) {
324 hash = ((hash << 5) + hash) + b_[ix];
329 void advance(size_type n) {
330 if (UNLIKELY(n > size())) {
331 throw std::out_of_range("index out of range");
336 void subtract(size_type n) {
337 if (UNLIKELY(n > size())) {
338 throw std::out_of_range("index out of range");
353 Range subpiece(size_type first,
354 size_type length = std::string::npos) const {
355 if (UNLIKELY(first > size())) {
356 throw std::out_of_range("index out of range");
358 return Range(b_ + first,
359 std::min<std::string::size_type>(length, size() - first));
362 // string work-alike functions
363 size_type find(Range str) const {
364 return qfind(*this, str);
367 size_type find(Range str, size_t pos) const {
368 if (pos > size()) return std::string::npos;
369 size_t ret = qfind(subpiece(pos), str);
370 return ret == npos ? ret : ret + pos;
373 size_type find(Iter s, size_t pos, size_t n) const {
374 if (pos > size()) return std::string::npos;
375 size_t ret = qfind(pos ? subpiece(pos) : *this, Range(s, n));
376 return ret == npos ? ret : ret + pos;
379 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
380 size_type find(const Iter s) const {
381 return qfind(*this, Range(s));
384 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
385 size_type find(const Iter s, size_t pos) const {
386 if (pos > size()) return std::string::npos;
387 size_type ret = qfind(subpiece(pos), Range(s));
388 return ret == npos ? ret : ret + pos;
391 size_type find(value_type c) const {
392 return qfind(*this, c);
395 size_type find(value_type c, size_t pos) const {
396 if (pos > size()) return std::string::npos;
397 size_type ret = qfind(subpiece(pos), c);
398 return ret == npos ? ret : ret + pos;
401 size_type find_first_of(Range needles) const {
402 return qfind_first_of(*this, needles);
405 size_type find_first_of(Range needles, size_t pos) const {
406 if (pos > size()) return std::string::npos;
407 size_type ret = qfind_first_of(subpiece(pos), needles);
408 return ret == npos ? ret : ret + pos;
411 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
412 size_type find_first_of(Iter needles) const {
413 return find_first_of(Range(needles));
416 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
417 size_type find_first_of(Iter needles, size_t pos) const {
418 return find_first_of(Range(needles), pos);
421 size_type find_first_of(Iter needles, size_t pos, size_t n) const {
422 return find_first_of(Range(needles, n), pos);
425 size_type find_first_of(value_type c) const {
429 size_type find_first_of(value_type c, size_t pos) const {
433 void swap(Range& rhs) {
434 std::swap(b_, rhs.b_);
435 std::swap(e_, rhs.e_);
442 template <class Iter>
443 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
446 void swap(Range<T>& lhs, Range<T>& rhs) {
451 * Create a range from two iterators, with type deduction.
453 template <class Iter>
454 Range<Iter> makeRange(Iter first, Iter last) {
455 return Range<Iter>(first, last);
458 typedef Range<const char*> StringPiece;
459 typedef Range<const unsigned char*> ByteRange;
461 std::ostream& operator<<(std::ostream& os, const StringPiece& piece);
464 * Templated comparison operators
468 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
469 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
473 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
474 return lhs.compare(rhs) < 0;
478 * Specializations of comparison operators for StringPiece
483 template <class A, class B>
484 struct ComparableAsStringPiece {
487 (std::is_convertible<A, StringPiece>::value
488 && std::is_same<B, StringPiece>::value)
490 (std::is_convertible<B, StringPiece>::value
491 && std::is_same<A, StringPiece>::value)
495 } // namespace detail
498 * operator== through conversion for Range<const char*>
500 template <class T, class U>
502 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
503 operator==(const T& lhs, const U& rhs) {
504 return StringPiece(lhs) == StringPiece(rhs);
508 * operator< through conversion for Range<const char*>
510 template <class T, class U>
512 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
513 operator<(const T& lhs, const U& rhs) {
514 return StringPiece(lhs) < StringPiece(rhs);
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);
547 struct StringPieceHash {
548 std::size_t operator()(const StringPiece& str) const {
549 return static_cast<std::size_t>(str.hash());
554 * Finds substrings faster than brute force by borrowing from Boyer-Moore
556 template <class T, class Comp>
557 size_t qfind(const Range<T>& haystack,
558 const Range<T>& needle,
560 // Don't use std::search, use a Boyer-Moore-like trick by comparing
561 // the last characters first
562 auto const nsize = needle.size();
563 if (haystack.size() < nsize) {
564 return std::string::npos;
566 if (!nsize) return 0;
567 auto const nsize_1 = nsize - 1;
568 auto const lastNeedle = needle[nsize_1];
570 // Boyer-Moore skip value for the last char in the needle. Zero is
571 // not a valid value; skip will be computed the first time it's
573 std::string::size_type skip = 0;
575 auto i = haystack.begin();
576 auto iEnd = haystack.end() - nsize_1;
579 // Boyer-Moore: match the last element in the needle
580 while (!eq(i[nsize_1], lastNeedle)) {
583 return std::string::npos;
586 // Here we know that the last char matches
587 // Continue in pedestrian mode
588 for (size_t j = 0; ; ) {
590 if (!eq(i[j], needle[j])) {
591 // Not found, we can skip
592 // Compute the skip value lazily
595 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
602 // Check if done searching
605 return i - haystack.begin();
609 return std::string::npos;
614 size_t qfind_first_byte_of_nosse(const StringPiece& haystack,
615 const StringPiece& needles);
617 #if FOLLY_HAVE_EMMINTRIN_H
618 size_t qfind_first_byte_of_sse42(const StringPiece& haystack,
619 const StringPiece& needles);
621 inline size_t qfind_first_byte_of(const StringPiece& haystack,
622 const StringPiece& needles) {
623 static auto const qfind_first_byte_of_fn =
624 folly::CpuId().sse42() ? qfind_first_byte_of_sse42
625 : qfind_first_byte_of_nosse;
626 return qfind_first_byte_of_fn(haystack, needles);
630 inline size_t qfind_first_byte_of(const StringPiece& haystack,
631 const StringPiece& needles) {
632 return qfind_first_byte_of_nosse(haystack, needles);
634 #endif // FOLLY_HAVE_EMMINTRIN_H
636 } // namespace detail
638 template <class T, class Comp>
639 size_t qfind_first_of(const Range<T> & haystack,
640 const Range<T> & needles,
642 auto ret = std::find_first_of(haystack.begin(), haystack.end(),
643 needles.begin(), needles.end(),
645 return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
648 struct AsciiCaseSensitive {
649 bool operator()(char lhs, char rhs) const {
654 struct AsciiCaseInsensitive {
655 bool operator()(char lhs, char rhs) const {
656 return toupper(lhs) == toupper(rhs);
660 extern const AsciiCaseSensitive asciiCaseSensitive;
661 extern const AsciiCaseInsensitive asciiCaseInsensitive;
664 size_t qfind(const Range<T>& haystack,
665 const Range<T>& needle) {
666 return qfind(haystack, needle, asciiCaseSensitive);
670 size_t qfind(const Range<T>& haystack,
671 const typename Range<T>::value_type& needle) {
672 auto pos = std::find(haystack.begin(), haystack.end(), needle);
673 return pos == haystack.end() ? std::string::npos : pos - haystack.data();
676 // specialization for StringPiece
678 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
679 auto pos = static_cast<const char*>(
680 ::memchr(haystack.data(), needle, haystack.size()));
681 return pos == nullptr ? std::string::npos : pos - haystack.data();
684 // specialization for ByteRange
686 inline size_t qfind(const Range<const unsigned char*>& haystack,
687 const unsigned char& needle) {
688 auto pos = static_cast<const unsigned char*>(
689 ::memchr(haystack.data(), needle, haystack.size()));
690 return pos == nullptr ? std::string::npos : pos - haystack.data();
694 size_t qfind_first_of(const Range<T>& haystack,
695 const Range<T>& needles) {
696 return qfind_first_of(haystack, needles, asciiCaseSensitive);
699 // specialization for StringPiece
701 inline size_t qfind_first_of(const Range<const char*>& haystack,
702 const Range<const char*>& needles) {
703 return detail::qfind_first_byte_of(haystack, needles);
706 // specialization for ByteRange
708 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
709 const Range<const unsigned char*>& needles) {
710 return detail::qfind_first_byte_of(StringPiece(haystack),
711 StringPiece(needles));
713 } // !namespace folly
715 #pragma GCC diagnostic pop
717 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);
719 #endif // FOLLY_RANGE_H_