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/FBString.h"
24 #include <glog/logging.h>
30 #include <type_traits>
31 #include <boost/operators.hpp>
32 #include <boost/utility/enable_if.hpp>
33 #include <boost/type_traits.hpp>
34 #include <bits/c++config.h>
35 #include "folly/CpuId.h"
36 #include "folly/Traits.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 boost::enable_if_c<
80 boost::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 boost::enable_if_c<
92 !boost::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 boost::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 static bool reachable(Iter b, Iter e, std::forward_iterator_tag) {
132 for (; b != e; ++b) {
133 LOG_EVERY_N(INFO, 100000) << __FILE__ ":" << __LINE__
134 << " running reachability test ("
135 << google::COUNTER << " iterations)...";
140 static bool reachable(Iter b, Iter e, std::random_access_iterator_tag) {
145 // Works for all iterators
146 Range(Iter start, Iter end)
147 : b_(start), e_(end) {
148 assert(reachable(b_, e_,
149 typename std::iterator_traits<Iter>::iterator_category()));
152 // Works only for random-access iterators
153 Range(Iter start, size_t size)
154 : b_(start), e_(start + size) { }
156 // Works only for Range<const char*>
157 /* implicit */ Range(Iter str)
158 : b_(str), e_(b_ + strlen(str)) {}
159 // Works only for Range<const char*>
160 /* implicit */ Range(const std::string& str)
161 : b_(str.data()), e_(b_ + str.size()) {}
162 // Works only for Range<const char*>
163 Range(const std::string& str, std::string::size_type startFrom) {
164 CHECK_LE(startFrom, str.size());
165 b_ = str.data() + startFrom;
166 e_ = str.data() + str.size();
168 // Works only for Range<const char*>
169 Range(const std::string& str,
170 std::string::size_type startFrom,
171 std::string::size_type size) {
172 CHECK_LE(startFrom + size, str.size());
173 b_ = str.data() + startFrom;
176 Range(const Range<Iter>& str,
179 CHECK_LE(startFrom + size, str.size());
180 b_ = str.b_ + startFrom;
183 // Works only for Range<const char*>
184 /* implicit */ Range(const fbstring& str)
185 : b_(str.data()), e_(b_ + str.size()) { }
186 // Works only for Range<const char*>
187 Range(const fbstring& str, fbstring::size_type startFrom) {
188 CHECK_LE(startFrom, str.size());
189 b_ = str.data() + startFrom;
190 e_ = str.data() + str.size();
192 // Works only for Range<const char*>
193 Range(const fbstring& str, fbstring::size_type startFrom,
194 fbstring::size_type size) {
195 CHECK_LE(startFrom + size, str.size());
196 b_ = str.data() + startFrom;
200 // Allow implicit conversion from Range<const char*> (aka StringPiece) to
201 // Range<const unsigned char*> (aka ByteRange), as they're both frequently
202 // used to represent ranges of bytes. Allow explicit conversion in the other
204 template <class OtherIter, typename std::enable_if<
205 (std::is_same<Iter, const unsigned char*>::value &&
206 std::is_same<OtherIter, const char*>::value), int>::type = 0>
207 /* implicit */ Range(const Range<OtherIter>& other)
208 : b_(reinterpret_cast<const unsigned char*>(other.begin())),
209 e_(reinterpret_cast<const unsigned char*>(other.end())) {
212 template <class OtherIter, typename std::enable_if<
213 (std::is_same<Iter, const char*>::value &&
214 std::is_same<OtherIter, const unsigned char*>::value), int>::type = 0>
215 explicit Range(const Range<OtherIter>& other)
216 : b_(reinterpret_cast<const char*>(other.begin())),
217 e_(reinterpret_cast<const char*>(other.end())) {
225 void assign(Iter start, Iter end) {
230 void reset(Iter start, size_type size) {
235 // Works only for Range<const char*>
236 void reset(const std::string& str) {
237 reset(str.data(), str.size());
240 size_type size() const {
244 size_type walk_size() const {
246 return std::distance(b_, e_);
248 bool empty() const { return b_ == e_; }
249 Iter data() const { return b_; }
250 Iter start() const { return b_; }
251 Iter begin() const { return b_; }
252 Iter end() const { return e_; }
253 Iter cbegin() const { return b_; }
254 Iter cend() const { return e_; }
255 value_type& front() {
261 return detail::value_before(e_);
263 const value_type& front() const {
267 const value_type& back() const {
269 return detail::value_before(e_);
271 // Works only for Range<const char*>
272 std::string str() const { return std::string(b_, size()); }
273 std::string toString() const { return str(); }
274 // Works only for Range<const char*>
275 fbstring fbstr() const { return fbstring(b_, size()); }
276 fbstring toFbstring() const { return fbstr(); }
278 // Works only for Range<const char*>
279 int compare(const Range& o) const {
280 const size_type tsize = this->size();
281 const size_type osize = o.size();
282 const size_type msize = std::min(tsize, osize);
283 int r = traits_type::compare(data(), o.data(), msize);
284 if (r == 0) r = tsize - osize;
288 value_type& operator[](size_t i) {
293 const value_type& operator[](size_t i) const {
298 value_type& at(size_t i) {
299 if (i >= size()) throw std::out_of_range("index out of range");
303 const value_type& at(size_t i) const {
304 if (i >= size()) throw std::out_of_range("index out of range");
308 // Works only for Range<const char*>
309 uint32_t hash() const {
310 // Taken from fbi/nstring.h:
311 // Quick and dirty bernstein hash...fine for short ascii strings
312 uint32_t hash = 5381;
313 for (size_t ix = 0; ix < size(); ix++) {
314 hash = ((hash << 5) + hash) + b_[ix];
319 void advance(size_type n) {
324 void subtract(size_type n) {
339 Range subpiece(size_type first,
340 size_type length = std::string::npos) const {
341 CHECK_LE(first, size());
342 return Range(b_ + first,
343 std::min<std::string::size_type>(length, size() - first));
346 // string work-alike functions
347 size_type find(Range str) const {
348 return qfind(*this, str);
351 size_type find(Range str, size_t pos) const {
352 if (pos > size()) return std::string::npos;
353 size_t ret = qfind(subpiece(pos), str);
354 return ret == npos ? ret : ret + pos;
357 size_type find(Iter s, size_t pos, size_t n) const {
358 if (pos > size()) return std::string::npos;
359 size_t ret = qfind(pos ? subpiece(pos) : *this, Range(s, n));
360 return ret == npos ? ret : ret + pos;
363 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
364 size_type find(const Iter s) const {
365 return qfind(*this, Range(s));
368 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
369 size_type find(const Iter s, size_t pos) const {
370 if (pos > size()) return std::string::npos;
371 size_type ret = qfind(subpiece(pos), Range(s));
372 return ret == npos ? ret : ret + pos;
375 size_type find(value_type c) const {
376 return qfind(*this, c);
379 size_type find(value_type c, size_t pos) const {
380 if (pos > size()) return std::string::npos;
381 size_type ret = qfind(subpiece(pos), c);
382 return ret == npos ? ret : ret + pos;
385 size_type find_first_of(Range needles) const {
386 return qfind_first_of(*this, needles);
389 size_type find_first_of(Range needles, size_t pos) const {
390 if (pos > size()) return std::string::npos;
391 size_type ret = qfind_first_of(subpiece(pos), needles);
392 return ret == npos ? ret : ret + pos;
395 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
396 size_type find_first_of(Iter needles) const {
397 return find_first_of(Range(needles));
400 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
401 size_type find_first_of(Iter needles, size_t pos) const {
402 return find_first_of(Range(needles), pos);
405 size_type find_first_of(Iter needles, size_t pos, size_t n) const {
406 return find_first_of(Range(needles, n), pos);
409 size_type find_first_of(value_type c) const {
413 size_type find_first_of(value_type c, size_t pos) const {
417 void swap(Range& rhs) {
418 std::swap(b_, rhs.b_);
419 std::swap(e_, rhs.e_);
426 template <class Iter>
427 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
430 void swap(Range<T>& lhs, Range<T>& rhs) {
435 * Create a range from two iterators, with type deduction.
437 template <class Iter>
438 Range<Iter> makeRange(Iter first, Iter last) {
439 return Range<Iter>(first, last);
442 typedef Range<const char*> StringPiece;
443 typedef Range<const unsigned char*> ByteRange;
445 std::ostream& operator<<(std::ostream& os, const StringPiece& piece);
448 * Templated comparison operators
452 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
453 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
457 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
458 return lhs.compare(rhs) < 0;
462 * Specializations of comparison operators for StringPiece
467 template <class A, class B>
468 struct ComparableAsStringPiece {
471 (boost::is_convertible<A, StringPiece>::value
472 && boost::is_same<B, StringPiece>::value)
474 (boost::is_convertible<B, StringPiece>::value
475 && boost::is_same<A, StringPiece>::value)
479 } // namespace detail
482 * operator== through conversion for Range<const char*>
484 template <class T, class U>
486 boost::enable_if_c<detail::ComparableAsStringPiece<T, U>::value, bool>::type
487 operator==(const T& lhs, const U& rhs) {
488 return StringPiece(lhs) == StringPiece(rhs);
492 * operator< through conversion for Range<const char*>
494 template <class T, class U>
496 boost::enable_if_c<detail::ComparableAsStringPiece<T, U>::value, bool>::type
497 operator<(const T& lhs, const U& rhs) {
498 return StringPiece(lhs) < StringPiece(rhs);
502 * operator> through conversion for Range<const char*>
504 template <class T, class U>
506 boost::enable_if_c<detail::ComparableAsStringPiece<T, U>::value, bool>::type
507 operator>(const T& lhs, const U& rhs) {
508 return StringPiece(lhs) > StringPiece(rhs);
512 * operator< through conversion for Range<const char*>
514 template <class T, class U>
516 boost::enable_if_c<detail::ComparableAsStringPiece<T, U>::value, bool>::type
517 operator<=(const T& lhs, const U& rhs) {
518 return StringPiece(lhs) <= StringPiece(rhs);
522 * operator> through conversion for Range<const char*>
524 template <class T, class U>
526 boost::enable_if_c<detail::ComparableAsStringPiece<T, U>::value, bool>::type
527 operator>=(const T& lhs, const U& rhs) {
528 return StringPiece(lhs) >= StringPiece(rhs);
531 struct StringPieceHash {
532 std::size_t operator()(const StringPiece& str) const {
533 return static_cast<std::size_t>(str.hash());
538 * Finds substrings faster than brute force by borrowing from Boyer-Moore
540 template <class T, class Comp>
541 size_t qfind(const Range<T>& haystack,
542 const Range<T>& needle,
544 // Don't use std::search, use a Boyer-Moore-like trick by comparing
545 // the last characters first
546 auto const nsize = needle.size();
547 if (haystack.size() < nsize) {
548 return std::string::npos;
550 if (!nsize) return 0;
551 auto const nsize_1 = nsize - 1;
552 auto const lastNeedle = needle[nsize_1];
554 // Boyer-Moore skip value for the last char in the needle. Zero is
555 // not a valid value; skip will be computed the first time it's
557 std::string::size_type skip = 0;
559 auto i = haystack.begin();
560 auto iEnd = haystack.end() - nsize_1;
563 // Boyer-Moore: match the last element in the needle
564 while (!eq(i[nsize_1], lastNeedle)) {
567 return std::string::npos;
570 // Here we know that the last char matches
571 // Continue in pedestrian mode
572 for (size_t j = 0; ; ) {
574 if (!eq(i[j], needle[j])) {
575 // Not found, we can skip
576 // Compute the skip value lazily
579 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
586 // Check if done searching
589 return i - haystack.begin();
593 return std::string::npos;
598 size_t qfind_first_byte_of_sse42(const StringPiece& haystack,
599 const StringPiece& needles);
601 size_t qfind_first_byte_of_nosse(const StringPiece& haystack,
602 const StringPiece& needles);
604 inline size_t qfind_first_byte_of(const StringPiece& haystack,
605 const StringPiece& needles) {
606 static auto const qfind_first_byte_of_fn =
607 folly::CpuId().sse42() ? qfind_first_byte_of_sse42
608 : qfind_first_byte_of_nosse;
609 return qfind_first_byte_of_fn(haystack, needles);
612 } // namespace detail
614 template <class T, class Comp>
615 size_t qfind_first_of(const Range<T> & haystack,
616 const Range<T> & needles,
618 auto ret = std::find_first_of(haystack.begin(), haystack.end(),
619 needles.begin(), needles.end(),
621 return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
624 struct AsciiCaseSensitive {
625 bool operator()(char lhs, char rhs) const {
630 struct AsciiCaseInsensitive {
631 bool operator()(char lhs, char rhs) const {
632 return toupper(lhs) == toupper(rhs);
636 extern const AsciiCaseSensitive asciiCaseSensitive;
637 extern const AsciiCaseInsensitive asciiCaseInsensitive;
640 size_t qfind(const Range<T>& haystack,
641 const Range<T>& needle) {
642 return qfind(haystack, needle, asciiCaseSensitive);
646 size_t qfind(const Range<T>& haystack,
647 const typename Range<T>::value_type& needle) {
648 auto pos = std::find(haystack.begin(), haystack.end(), needle);
649 return pos == haystack.end() ? std::string::npos : pos - haystack.data();
652 // specialization for StringPiece
654 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
655 auto pos = static_cast<const char*>(
656 ::memchr(haystack.data(), needle, haystack.size()));
657 return pos == nullptr ? std::string::npos : pos - haystack.data();
660 // specialization for ByteRange
662 inline size_t qfind(const Range<const unsigned char*>& haystack,
663 const unsigned char& needle) {
664 auto pos = static_cast<const unsigned char*>(
665 ::memchr(haystack.data(), needle, haystack.size()));
666 return pos == nullptr ? std::string::npos : pos - haystack.data();
670 size_t qfind_first_of(const Range<T>& haystack,
671 const Range<T>& needles) {
672 return qfind_first_of(haystack, needles, asciiCaseSensitive);
675 // specialization for StringPiece
677 inline size_t qfind_first_of(const Range<const char*>& haystack,
678 const Range<const char*>& needles) {
679 return detail::qfind_first_byte_of(haystack, needles);
682 // specialization for ByteRange
684 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
685 const Range<const unsigned char*>& needles) {
686 return detail::qfind_first_byte_of(StringPiece(haystack),
687 StringPiece(needles));
689 } // !namespace folly
691 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);
693 #endif // FOLLY_RANGE_H_