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"
40 template <class T> class Range;
43 * Finds the first occurrence of needle in haystack. The algorithm is on
44 * average faster than O(haystack.size() * needle.size()) but not as fast
45 * as Boyer-Moore. On the upside, it does not do any upfront
46 * preprocessing and does not allocate memory.
49 inline size_t qfind(const Range<T> & haystack,
50 const Range<T> & needle);
53 * Finds the first occurrence of needle in haystack. The result is the
54 * offset reported to the beginning of haystack, or string::npos if
55 * needle wasn't found.
58 size_t qfind(const Range<T> & haystack,
59 const typename Range<T>::value_type& needle);
63 * Finds the first occurrence of any element of needle in
64 * haystack. The algorithm is O(haystack.size() * needle.size()).
67 inline size_t qfind_first_of(const Range<T> & haystack,
68 const Range<T> & needle);
71 * Small internal helper - returns the value just before an iterator.
76 * For random-access iterators, the value before is simply i[-1].
79 typename std::enable_if<
80 std::is_same<typename std::iterator_traits<Iter>::iterator_category,
81 std::random_access_iterator_tag>::value,
82 typename std::iterator_traits<Iter>::reference>::type
83 value_before(Iter i) {
88 * For all other iterators, we need to use the decrement operator.
91 typename std::enable_if<
92 !std::is_same<typename std::iterator_traits<Iter>::iterator_category,
93 std::random_access_iterator_tag>::value,
94 typename std::iterator_traits<Iter>::reference>::type
95 value_before(Iter i) {
102 * Range abstraction keeping a pair of iterators. We couldn't use
103 * boost's similar range abstraction because we need an API identical
104 * with the former StringPiece class, which is used by a lot of other
105 * code. This abstraction does fulfill the needs of boost's
106 * range-oriented algorithms though.
108 * (Keep memory lifetime in mind when using this class, since it
109 * doesn't manage the data it refers to - just like an iterator
112 template <class Iter>
113 class Range : private boost::totally_ordered<Range<Iter> > {
115 typedef std::size_t size_type;
116 typedef Iter iterator;
117 typedef Iter const_iterator;
118 typedef typename std::remove_reference<
119 typename std::iterator_traits<Iter>::reference>::type
121 typedef typename std::iterator_traits<Iter>::reference reference;
122 typedef std::char_traits<value_type> traits_type;
124 static const size_type npos;
126 // Works for all iterators
127 Range() : b_(), e_() {
131 // Works for all iterators
132 Range(Iter start, Iter end) : b_(start), e_(end) {
135 // Works only for random-access iterators
136 Range(Iter start, size_t size)
137 : b_(start), e_(start + size) { }
139 // Works only for Range<const char*>
140 /* implicit */ Range(Iter str)
141 : b_(str), e_(b_ + strlen(str)) {}
142 // Works only for Range<const char*>
143 /* implicit */ Range(const std::string& str)
144 : b_(str.data()), e_(b_ + str.size()) {}
145 // Works only for Range<const char*>
146 Range(const std::string& str, std::string::size_type startFrom) {
147 if (UNLIKELY(startFrom > str.size())) {
148 throw std::out_of_range("index out of range");
150 b_ = str.data() + startFrom;
151 e_ = str.data() + str.size();
153 // Works only for Range<const char*>
154 Range(const std::string& str,
155 std::string::size_type startFrom,
156 std::string::size_type size) {
157 if (UNLIKELY(startFrom > str.size())) {
158 throw std::out_of_range("index out of range");
160 b_ = str.data() + startFrom;
161 if (str.size() - startFrom < size) {
162 e_ = str.data() + str.size();
167 Range(const Range<Iter>& str,
170 if (UNLIKELY(startFrom > str.size())) {
171 throw std::out_of_range("index out of range");
173 b_ = str.b_ + startFrom;
174 if (str.size() - startFrom < size) {
180 // Works only for Range<const char*>
181 /* implicit */ Range(const fbstring& str)
182 : b_(str.data()), e_(b_ + str.size()) { }
183 // Works only for Range<const char*>
184 Range(const fbstring& str, fbstring::size_type startFrom) {
185 if (UNLIKELY(startFrom > str.size())) {
186 throw std::out_of_range("index out of range");
188 b_ = str.data() + startFrom;
189 e_ = str.data() + str.size();
191 // Works only for Range<const char*>
192 Range(const fbstring& str, fbstring::size_type startFrom,
193 fbstring::size_type size) {
194 if (UNLIKELY(startFrom > str.size())) {
195 throw std::out_of_range("index out of range");
197 b_ = str.data() + startFrom;
198 if (str.size() - startFrom < size) {
199 e_ = str.data() + str.size();
205 // Allow implicit conversion from Range<const char*> (aka StringPiece) to
206 // Range<const unsigned char*> (aka ByteRange), as they're both frequently
207 // used to represent ranges of bytes. Allow explicit conversion in the other
209 template <class OtherIter, typename std::enable_if<
210 (std::is_same<Iter, const unsigned char*>::value &&
211 std::is_same<OtherIter, const char*>::value), int>::type = 0>
212 /* implicit */ Range(const Range<OtherIter>& other)
213 : b_(reinterpret_cast<const unsigned char*>(other.begin())),
214 e_(reinterpret_cast<const unsigned char*>(other.end())) {
217 template <class OtherIter, typename std::enable_if<
218 (std::is_same<Iter, const char*>::value &&
219 std::is_same<OtherIter, const unsigned char*>::value), int>::type = 0>
220 explicit Range(const Range<OtherIter>& other)
221 : b_(reinterpret_cast<const char*>(other.begin())),
222 e_(reinterpret_cast<const char*>(other.end())) {
230 void assign(Iter start, Iter end) {
235 void reset(Iter start, size_type size) {
240 // Works only for Range<const char*>
241 void reset(const std::string& str) {
242 reset(str.data(), str.size());
245 size_type size() const {
249 size_type walk_size() const {
251 return std::distance(b_, e_);
253 bool empty() const { return b_ == e_; }
254 Iter data() const { return b_; }
255 Iter start() const { return b_; }
256 Iter begin() const { return b_; }
257 Iter end() const { return e_; }
258 Iter cbegin() const { return b_; }
259 Iter cend() const { return e_; }
260 value_type& front() {
266 return detail::value_before(e_);
268 const value_type& front() const {
272 const value_type& back() const {
274 return detail::value_before(e_);
276 // Works only for Range<const char*>
277 std::string str() const { return std::string(b_, size()); }
278 std::string toString() const { return str(); }
279 // Works only for Range<const char*>
280 fbstring fbstr() const { return fbstring(b_, size()); }
281 fbstring toFbstring() const { return fbstr(); }
283 // Works only for Range<const char*>
284 int compare(const Range& o) const {
285 const size_type tsize = this->size();
286 const size_type osize = o.size();
287 const size_type msize = std::min(tsize, osize);
288 int r = traits_type::compare(data(), o.data(), msize);
289 if (r == 0) r = tsize - osize;
293 value_type& operator[](size_t i) {
298 const value_type& operator[](size_t i) const {
303 value_type& at(size_t i) {
304 if (i >= size()) throw std::out_of_range("index out of range");
308 const value_type& at(size_t i) const {
309 if (i >= size()) throw std::out_of_range("index out of range");
313 // Works only for Range<const char*>
314 uint32_t hash() const {
315 // Taken from fbi/nstring.h:
316 // Quick and dirty bernstein hash...fine for short ascii strings
317 uint32_t hash = 5381;
318 for (size_t ix = 0; ix < size(); ix++) {
319 hash = ((hash << 5) + hash) + b_[ix];
324 void advance(size_type n) {
325 if (UNLIKELY(n > size())) {
326 throw std::out_of_range("index out of range");
331 void subtract(size_type n) {
332 if (UNLIKELY(n > size())) {
333 throw std::out_of_range("index out of range");
348 Range subpiece(size_type first,
349 size_type length = std::string::npos) const {
350 if (UNLIKELY(first > size())) {
351 throw std::out_of_range("index out of range");
353 return Range(b_ + first,
354 std::min<std::string::size_type>(length, size() - first));
357 // string work-alike functions
358 size_type find(Range str) const {
359 return qfind(*this, str);
362 size_type find(Range str, size_t pos) const {
363 if (pos > size()) return std::string::npos;
364 size_t ret = qfind(subpiece(pos), str);
365 return ret == npos ? ret : ret + pos;
368 size_type find(Iter s, size_t pos, size_t n) const {
369 if (pos > size()) return std::string::npos;
370 size_t ret = qfind(pos ? subpiece(pos) : *this, Range(s, n));
371 return ret == npos ? ret : ret + pos;
374 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
375 size_type find(const Iter s) const {
376 return qfind(*this, Range(s));
379 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
380 size_type find(const Iter s, size_t pos) const {
381 if (pos > size()) return std::string::npos;
382 size_type ret = qfind(subpiece(pos), Range(s));
383 return ret == npos ? ret : ret + pos;
386 size_type find(value_type c) const {
387 return qfind(*this, c);
390 size_type find(value_type c, size_t pos) const {
391 if (pos > size()) return std::string::npos;
392 size_type ret = qfind(subpiece(pos), c);
393 return ret == npos ? ret : ret + pos;
396 size_type find_first_of(Range needles) const {
397 return qfind_first_of(*this, needles);
400 size_type find_first_of(Range needles, size_t pos) const {
401 if (pos > size()) return std::string::npos;
402 size_type ret = qfind_first_of(subpiece(pos), needles);
403 return ret == npos ? ret : ret + pos;
406 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
407 size_type find_first_of(Iter needles) const {
408 return find_first_of(Range(needles));
411 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
412 size_type find_first_of(Iter needles, size_t pos) const {
413 return find_first_of(Range(needles), pos);
416 size_type find_first_of(Iter needles, size_t pos, size_t n) const {
417 return find_first_of(Range(needles, n), pos);
420 size_type find_first_of(value_type c) const {
424 size_type find_first_of(value_type c, size_t pos) const {
428 void swap(Range& rhs) {
429 std::swap(b_, rhs.b_);
430 std::swap(e_, rhs.e_);
437 template <class Iter>
438 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
441 void swap(Range<T>& lhs, Range<T>& rhs) {
446 * Create a range from two iterators, with type deduction.
448 template <class Iter>
449 Range<Iter> makeRange(Iter first, Iter last) {
450 return Range<Iter>(first, last);
453 typedef Range<const char*> StringPiece;
454 typedef Range<const unsigned char*> ByteRange;
456 std::ostream& operator<<(std::ostream& os, const StringPiece& piece);
459 * Templated comparison operators
463 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
464 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
468 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
469 return lhs.compare(rhs) < 0;
473 * Specializations of comparison operators for StringPiece
478 template <class A, class B>
479 struct ComparableAsStringPiece {
482 (std::is_convertible<A, StringPiece>::value
483 && std::is_same<B, StringPiece>::value)
485 (std::is_convertible<B, StringPiece>::value
486 && std::is_same<A, StringPiece>::value)
490 } // namespace detail
493 * operator== through conversion for Range<const char*>
495 template <class T, class U>
497 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
498 operator==(const T& lhs, const U& rhs) {
499 return StringPiece(lhs) == StringPiece(rhs);
503 * operator< through conversion for Range<const char*>
505 template <class T, class U>
507 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
508 operator<(const T& lhs, const U& rhs) {
509 return StringPiece(lhs) < StringPiece(rhs);
513 * operator> through conversion for Range<const char*>
515 template <class T, class U>
517 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
518 operator>(const T& lhs, const U& rhs) {
519 return StringPiece(lhs) > StringPiece(rhs);
523 * operator< through conversion for Range<const char*>
525 template <class T, class U>
527 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
528 operator<=(const T& lhs, const U& rhs) {
529 return StringPiece(lhs) <= StringPiece(rhs);
533 * operator> through conversion for Range<const char*>
535 template <class T, class U>
537 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
538 operator>=(const T& lhs, const U& rhs) {
539 return StringPiece(lhs) >= StringPiece(rhs);
542 struct StringPieceHash {
543 std::size_t operator()(const StringPiece& str) const {
544 return static_cast<std::size_t>(str.hash());
549 * Finds substrings faster than brute force by borrowing from Boyer-Moore
551 template <class T, class Comp>
552 size_t qfind(const Range<T>& haystack,
553 const Range<T>& needle,
555 // Don't use std::search, use a Boyer-Moore-like trick by comparing
556 // the last characters first
557 auto const nsize = needle.size();
558 if (haystack.size() < nsize) {
559 return std::string::npos;
561 if (!nsize) return 0;
562 auto const nsize_1 = nsize - 1;
563 auto const lastNeedle = needle[nsize_1];
565 // Boyer-Moore skip value for the last char in the needle. Zero is
566 // not a valid value; skip will be computed the first time it's
568 std::string::size_type skip = 0;
570 auto i = haystack.begin();
571 auto iEnd = haystack.end() - nsize_1;
574 // Boyer-Moore: match the last element in the needle
575 while (!eq(i[nsize_1], lastNeedle)) {
578 return std::string::npos;
581 // Here we know that the last char matches
582 // Continue in pedestrian mode
583 for (size_t j = 0; ; ) {
585 if (!eq(i[j], needle[j])) {
586 // Not found, we can skip
587 // Compute the skip value lazily
590 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
597 // Check if done searching
600 return i - haystack.begin();
604 return std::string::npos;
609 size_t qfind_first_byte_of_nosse(const StringPiece& haystack,
610 const StringPiece& needles);
612 #if FOLLY_HAVE_EMMINTRIN_H
613 size_t qfind_first_byte_of_sse42(const StringPiece& haystack,
614 const StringPiece& needles);
616 inline size_t qfind_first_byte_of(const StringPiece& haystack,
617 const StringPiece& needles) {
618 static auto const qfind_first_byte_of_fn =
619 folly::CpuId().sse42() ? qfind_first_byte_of_sse42
620 : qfind_first_byte_of_nosse;
621 return qfind_first_byte_of_fn(haystack, needles);
625 inline size_t qfind_first_byte_of(const StringPiece& haystack,
626 const StringPiece& needles) {
627 return qfind_first_byte_of_nosse(haystack, needles);
629 #endif // FOLLY_HAVE_EMMINTRIN_H
631 } // namespace detail
633 template <class T, class Comp>
634 size_t qfind_first_of(const Range<T> & haystack,
635 const Range<T> & needles,
637 auto ret = std::find_first_of(haystack.begin(), haystack.end(),
638 needles.begin(), needles.end(),
640 return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
643 struct AsciiCaseSensitive {
644 bool operator()(char lhs, char rhs) const {
649 struct AsciiCaseInsensitive {
650 bool operator()(char lhs, char rhs) const {
651 return toupper(lhs) == toupper(rhs);
655 extern const AsciiCaseSensitive asciiCaseSensitive;
656 extern const AsciiCaseInsensitive asciiCaseInsensitive;
659 size_t qfind(const Range<T>& haystack,
660 const Range<T>& needle) {
661 return qfind(haystack, needle, asciiCaseSensitive);
665 size_t qfind(const Range<T>& haystack,
666 const typename Range<T>::value_type& needle) {
667 auto pos = std::find(haystack.begin(), haystack.end(), needle);
668 return pos == haystack.end() ? std::string::npos : pos - haystack.data();
671 // specialization for StringPiece
673 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
674 auto pos = static_cast<const char*>(
675 ::memchr(haystack.data(), needle, haystack.size()));
676 return pos == nullptr ? std::string::npos : pos - haystack.data();
679 // specialization for ByteRange
681 inline size_t qfind(const Range<const unsigned char*>& haystack,
682 const unsigned char& needle) {
683 auto pos = static_cast<const unsigned char*>(
684 ::memchr(haystack.data(), needle, haystack.size()));
685 return pos == nullptr ? std::string::npos : pos - haystack.data();
689 size_t qfind_first_of(const Range<T>& haystack,
690 const Range<T>& needles) {
691 return qfind_first_of(haystack, needles, asciiCaseSensitive);
694 // specialization for StringPiece
696 inline size_t qfind_first_of(const Range<const char*>& haystack,
697 const Range<const char*>& needles) {
698 return detail::qfind_first_byte_of(haystack, needles);
701 // specialization for ByteRange
703 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
704 const Range<const unsigned char*>& needles) {
705 return detail::qfind_first_byte_of(StringPiece(haystack),
706 StringPiece(needles));
708 } // !namespace folly
710 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);
712 #endif // FOLLY_RANGE_H_