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<value_type> traits_type;
128 static const size_type npos;
130 // Works for all iterators
131 Range() : b_(), e_() {
135 // Works for all iterators
136 Range(Iter start, Iter end) : b_(start), e_(end) {
139 // Works only for random-access iterators
140 Range(Iter start, size_t size)
141 : b_(start), e_(start + size) { }
143 // Works only for Range<const char*>
144 /* implicit */ Range(Iter str)
145 : b_(str), e_(b_ + strlen(str)) {}
146 // Works only for Range<const char*>
147 /* implicit */ Range(const std::string& str)
148 : b_(str.data()), e_(b_ + str.size()) {}
149 // Works only for Range<const char*>
150 Range(const std::string& str, std::string::size_type startFrom) {
151 if (UNLIKELY(startFrom > str.size())) {
152 throw std::out_of_range("index out of range");
154 b_ = str.data() + startFrom;
155 e_ = str.data() + str.size();
157 // Works only for Range<const char*>
158 Range(const std::string& str,
159 std::string::size_type startFrom,
160 std::string::size_type size) {
161 if (UNLIKELY(startFrom > str.size())) {
162 throw std::out_of_range("index out of range");
164 b_ = str.data() + startFrom;
165 if (str.size() - startFrom < size) {
166 e_ = str.data() + str.size();
171 Range(const Range<Iter>& str,
174 if (UNLIKELY(startFrom > str.size())) {
175 throw std::out_of_range("index out of range");
177 b_ = str.b_ + startFrom;
178 if (str.size() - startFrom < size) {
184 // Works only for Range<const char*>
185 /* implicit */ Range(const fbstring& str)
186 : b_(str.data()), e_(b_ + str.size()) { }
187 // Works only for Range<const char*>
188 Range(const fbstring& str, fbstring::size_type startFrom) {
189 if (UNLIKELY(startFrom > str.size())) {
190 throw std::out_of_range("index out of range");
192 b_ = str.data() + startFrom;
193 e_ = str.data() + str.size();
195 // Works only for Range<const char*>
196 Range(const fbstring& str, fbstring::size_type startFrom,
197 fbstring::size_type size) {
198 if (UNLIKELY(startFrom > str.size())) {
199 throw std::out_of_range("index out of range");
201 b_ = str.data() + startFrom;
202 if (str.size() - startFrom < size) {
203 e_ = str.data() + str.size();
209 // Allow implicit conversion from Range<const char*> (aka StringPiece) to
210 // Range<const unsigned char*> (aka ByteRange), as they're both frequently
211 // used to represent ranges of bytes. Allow explicit conversion in the other
213 template <class OtherIter, typename std::enable_if<
214 (std::is_same<Iter, const unsigned char*>::value &&
215 std::is_same<OtherIter, const char*>::value), int>::type = 0>
216 /* implicit */ Range(const Range<OtherIter>& other)
217 : b_(reinterpret_cast<const unsigned char*>(other.begin())),
218 e_(reinterpret_cast<const unsigned char*>(other.end())) {
221 template <class OtherIter, typename std::enable_if<
222 (std::is_same<Iter, const char*>::value &&
223 std::is_same<OtherIter, const unsigned char*>::value), int>::type = 0>
224 explicit Range(const Range<OtherIter>& other)
225 : b_(reinterpret_cast<const char*>(other.begin())),
226 e_(reinterpret_cast<const char*>(other.end())) {
234 void assign(Iter start, Iter end) {
239 void reset(Iter start, size_type size) {
244 // Works only for Range<const char*>
245 void reset(const std::string& str) {
246 reset(str.data(), str.size());
249 size_type size() const {
253 size_type walk_size() const {
255 return std::distance(b_, e_);
257 bool empty() const { return b_ == e_; }
258 Iter data() const { return b_; }
259 Iter start() const { return b_; }
260 Iter begin() const { return b_; }
261 Iter end() const { return e_; }
262 Iter cbegin() const { return b_; }
263 Iter cend() const { return e_; }
264 value_type& front() {
270 return detail::value_before(e_);
272 const value_type& front() const {
276 const value_type& back() const {
278 return detail::value_before(e_);
280 // Works only for Range<const char*>
281 std::string str() const { return std::string(b_, size()); }
282 std::string toString() const { return str(); }
283 // Works only for Range<const char*>
284 fbstring fbstr() const { return fbstring(b_, size()); }
285 fbstring toFbstring() const { return fbstr(); }
287 // Works only for Range<const char*>
288 int compare(const Range& o) const {
289 const size_type tsize = this->size();
290 const size_type osize = o.size();
291 const size_type msize = std::min(tsize, osize);
292 int r = traits_type::compare(data(), o.data(), msize);
293 if (r == 0) r = tsize - osize;
297 value_type& operator[](size_t i) {
302 const value_type& operator[](size_t i) const {
307 value_type& at(size_t i) {
308 if (i >= size()) throw std::out_of_range("index out of range");
312 const value_type& at(size_t i) const {
313 if (i >= size()) throw std::out_of_range("index out of range");
317 // Works only for Range<const char*>
318 uint32_t hash() const {
319 // Taken from fbi/nstring.h:
320 // Quick and dirty bernstein hash...fine for short ascii strings
321 uint32_t hash = 5381;
322 for (size_t ix = 0; ix < size(); ix++) {
323 hash = ((hash << 5) + hash) + b_[ix];
328 void advance(size_type n) {
329 if (UNLIKELY(n > size())) {
330 throw std::out_of_range("index out of range");
335 void subtract(size_type n) {
336 if (UNLIKELY(n > size())) {
337 throw std::out_of_range("index out of range");
352 Range subpiece(size_type first,
353 size_type length = std::string::npos) const {
354 if (UNLIKELY(first > size())) {
355 throw std::out_of_range("index out of range");
357 return Range(b_ + first,
358 std::min<std::string::size_type>(length, size() - first));
361 // string work-alike functions
362 size_type find(Range str) const {
363 return qfind(*this, str);
366 size_type find(Range str, size_t pos) const {
367 if (pos > size()) return std::string::npos;
368 size_t ret = qfind(subpiece(pos), str);
369 return ret == npos ? ret : ret + pos;
372 size_type find(Iter s, size_t pos, size_t n) const {
373 if (pos > size()) return std::string::npos;
374 size_t ret = qfind(pos ? subpiece(pos) : *this, Range(s, n));
375 return ret == npos ? ret : ret + pos;
378 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
379 size_type find(const Iter s) const {
380 return qfind(*this, Range(s));
383 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
384 size_type find(const Iter s, size_t pos) const {
385 if (pos > size()) return std::string::npos;
386 size_type ret = qfind(subpiece(pos), Range(s));
387 return ret == npos ? ret : ret + pos;
390 size_type find(value_type c) const {
391 return qfind(*this, c);
394 size_type find(value_type c, size_t pos) const {
395 if (pos > size()) return std::string::npos;
396 size_type ret = qfind(subpiece(pos), c);
397 return ret == npos ? ret : ret + pos;
400 size_type find_first_of(Range needles) const {
401 return qfind_first_of(*this, needles);
404 size_type find_first_of(Range needles, size_t pos) const {
405 if (pos > size()) return std::string::npos;
406 size_type ret = qfind_first_of(subpiece(pos), needles);
407 return ret == npos ? ret : ret + pos;
410 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
411 size_type find_first_of(Iter needles) const {
412 return find_first_of(Range(needles));
415 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
416 size_type find_first_of(Iter needles, size_t pos) const {
417 return find_first_of(Range(needles), pos);
420 size_type find_first_of(Iter needles, size_t pos, size_t n) const {
421 return find_first_of(Range(needles, n), pos);
424 size_type find_first_of(value_type c) const {
428 size_type find_first_of(value_type c, size_t pos) const {
432 void swap(Range& rhs) {
433 std::swap(b_, rhs.b_);
434 std::swap(e_, rhs.e_);
441 template <class Iter>
442 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
445 void swap(Range<T>& lhs, Range<T>& rhs) {
450 * Create a range from two iterators, with type deduction.
452 template <class Iter>
453 Range<Iter> makeRange(Iter first, Iter last) {
454 return Range<Iter>(first, last);
457 typedef Range<const char*> StringPiece;
458 typedef Range<const unsigned char*> ByteRange;
460 std::ostream& operator<<(std::ostream& os, const StringPiece& piece);
463 * Templated comparison operators
467 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
468 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
472 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
473 return lhs.compare(rhs) < 0;
477 * Specializations of comparison operators for StringPiece
482 template <class A, class B>
483 struct ComparableAsStringPiece {
486 (std::is_convertible<A, StringPiece>::value
487 && std::is_same<B, StringPiece>::value)
489 (std::is_convertible<B, StringPiece>::value
490 && std::is_same<A, StringPiece>::value)
494 } // namespace detail
497 * operator== through conversion for Range<const char*>
499 template <class T, class U>
501 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
502 operator==(const T& lhs, const U& rhs) {
503 return StringPiece(lhs) == StringPiece(rhs);
507 * operator< through conversion for Range<const char*>
509 template <class T, class U>
511 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
512 operator<(const T& lhs, const U& rhs) {
513 return StringPiece(lhs) < StringPiece(rhs);
517 * operator> through conversion for Range<const char*>
519 template <class T, class U>
521 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
522 operator>(const T& lhs, const U& rhs) {
523 return StringPiece(lhs) > StringPiece(rhs);
527 * operator< through conversion for Range<const char*>
529 template <class T, class U>
531 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
532 operator<=(const T& lhs, const U& rhs) {
533 return StringPiece(lhs) <= StringPiece(rhs);
537 * operator> through conversion for Range<const char*>
539 template <class T, class U>
541 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
542 operator>=(const T& lhs, const U& rhs) {
543 return StringPiece(lhs) >= StringPiece(rhs);
546 struct StringPieceHash {
547 std::size_t operator()(const StringPiece& str) const {
548 return static_cast<std::size_t>(str.hash());
553 * Finds substrings faster than brute force by borrowing from Boyer-Moore
555 template <class T, class Comp>
556 size_t qfind(const Range<T>& haystack,
557 const Range<T>& needle,
559 // Don't use std::search, use a Boyer-Moore-like trick by comparing
560 // the last characters first
561 auto const nsize = needle.size();
562 if (haystack.size() < nsize) {
563 return std::string::npos;
565 if (!nsize) return 0;
566 auto const nsize_1 = nsize - 1;
567 auto const lastNeedle = needle[nsize_1];
569 // Boyer-Moore skip value for the last char in the needle. Zero is
570 // not a valid value; skip will be computed the first time it's
572 std::string::size_type skip = 0;
574 auto i = haystack.begin();
575 auto iEnd = haystack.end() - nsize_1;
578 // Boyer-Moore: match the last element in the needle
579 while (!eq(i[nsize_1], lastNeedle)) {
582 return std::string::npos;
585 // Here we know that the last char matches
586 // Continue in pedestrian mode
587 for (size_t j = 0; ; ) {
589 if (!eq(i[j], needle[j])) {
590 // Not found, we can skip
591 // Compute the skip value lazily
594 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
601 // Check if done searching
604 return i - haystack.begin();
608 return std::string::npos;
613 size_t qfind_first_byte_of_nosse(const StringPiece& haystack,
614 const StringPiece& needles);
616 #if FOLLY_HAVE_EMMINTRIN_H
617 size_t qfind_first_byte_of_sse42(const StringPiece& haystack,
618 const StringPiece& needles);
620 inline size_t qfind_first_byte_of(const StringPiece& haystack,
621 const StringPiece& needles) {
622 static auto const qfind_first_byte_of_fn =
623 folly::CpuId().sse42() ? qfind_first_byte_of_sse42
624 : qfind_first_byte_of_nosse;
625 return qfind_first_byte_of_fn(haystack, needles);
629 inline size_t qfind_first_byte_of(const StringPiece& haystack,
630 const StringPiece& needles) {
631 return qfind_first_byte_of_nosse(haystack, needles);
633 #endif // FOLLY_HAVE_EMMINTRIN_H
635 } // namespace detail
637 template <class T, class Comp>
638 size_t qfind_first_of(const Range<T> & haystack,
639 const Range<T> & needles,
641 auto ret = std::find_first_of(haystack.begin(), haystack.end(),
642 needles.begin(), needles.end(),
644 return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
647 struct AsciiCaseSensitive {
648 bool operator()(char lhs, char rhs) const {
653 struct AsciiCaseInsensitive {
654 bool operator()(char lhs, char rhs) const {
655 return toupper(lhs) == toupper(rhs);
659 extern const AsciiCaseSensitive asciiCaseSensitive;
660 extern const AsciiCaseInsensitive asciiCaseInsensitive;
663 size_t qfind(const Range<T>& haystack,
664 const Range<T>& needle) {
665 return qfind(haystack, needle, asciiCaseSensitive);
669 size_t qfind(const Range<T>& haystack,
670 const typename Range<T>::value_type& needle) {
671 auto pos = std::find(haystack.begin(), haystack.end(), needle);
672 return pos == haystack.end() ? std::string::npos : pos - haystack.data();
675 // specialization for StringPiece
677 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
678 auto pos = static_cast<const char*>(
679 ::memchr(haystack.data(), needle, haystack.size()));
680 return pos == nullptr ? std::string::npos : pos - haystack.data();
683 // specialization for ByteRange
685 inline size_t qfind(const Range<const unsigned char*>& haystack,
686 const unsigned char& needle) {
687 auto pos = static_cast<const unsigned char*>(
688 ::memchr(haystack.data(), needle, haystack.size()));
689 return pos == nullptr ? std::string::npos : pos - haystack.data();
693 size_t qfind_first_of(const Range<T>& haystack,
694 const Range<T>& needles) {
695 return qfind_first_of(haystack, needles, asciiCaseSensitive);
698 // specialization for StringPiece
700 inline size_t qfind_first_of(const Range<const char*>& haystack,
701 const Range<const char*>& needles) {
702 return detail::qfind_first_byte_of(haystack, needles);
705 // specialization for ByteRange
707 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
708 const Range<const unsigned char*>& needles) {
709 return detail::qfind_first_byte_of(StringPiece(haystack),
710 StringPiece(needles));
712 } // !namespace folly
714 #pragma GCC diagnostic pop
716 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);
718 #endif // FOLLY_RANGE_H_