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 // 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 CHECK_LE(startFrom, str.size());
148 b_ = str.data() + startFrom;
149 e_ = str.data() + str.size();
151 // Works only for Range<const char*>
152 Range(const std::string& str,
153 std::string::size_type startFrom,
154 std::string::size_type size) {
155 CHECK_LE(startFrom + size, str.size());
156 b_ = str.data() + startFrom;
159 Range(const Range<Iter>& str,
162 CHECK_LE(startFrom + size, str.size());
163 b_ = str.b_ + startFrom;
166 // Works only for Range<const char*>
167 /* implicit */ Range(const fbstring& str)
168 : b_(str.data()), e_(b_ + str.size()) { }
169 // Works only for Range<const char*>
170 Range(const fbstring& str, fbstring::size_type startFrom) {
171 CHECK_LE(startFrom, str.size());
172 b_ = str.data() + startFrom;
173 e_ = str.data() + str.size();
175 // Works only for Range<const char*>
176 Range(const fbstring& str, fbstring::size_type startFrom,
177 fbstring::size_type size) {
178 CHECK_LE(startFrom + size, str.size());
179 b_ = str.data() + startFrom;
183 // Allow implicit conversion from Range<const char*> (aka StringPiece) to
184 // Range<const unsigned char*> (aka ByteRange), as they're both frequently
185 // used to represent ranges of bytes. Allow explicit conversion in the other
187 template <class OtherIter, typename std::enable_if<
188 (std::is_same<Iter, const unsigned char*>::value &&
189 std::is_same<OtherIter, const char*>::value), int>::type = 0>
190 /* implicit */ Range(const Range<OtherIter>& other)
191 : b_(reinterpret_cast<const unsigned char*>(other.begin())),
192 e_(reinterpret_cast<const unsigned char*>(other.end())) {
195 template <class OtherIter, typename std::enable_if<
196 (std::is_same<Iter, const char*>::value &&
197 std::is_same<OtherIter, const unsigned char*>::value), int>::type = 0>
198 explicit Range(const Range<OtherIter>& other)
199 : b_(reinterpret_cast<const char*>(other.begin())),
200 e_(reinterpret_cast<const char*>(other.end())) {
208 void assign(Iter start, Iter end) {
213 void reset(Iter start, size_type size) {
218 // Works only for Range<const char*>
219 void reset(const std::string& str) {
220 reset(str.data(), str.size());
223 size_type size() const {
227 size_type walk_size() const {
229 return std::distance(b_, e_);
231 bool empty() const { return b_ == e_; }
232 Iter data() const { return b_; }
233 Iter start() const { return b_; }
234 Iter begin() const { return b_; }
235 Iter end() const { return e_; }
236 Iter cbegin() const { return b_; }
237 Iter cend() const { return e_; }
238 value_type& front() {
244 return detail::value_before(e_);
246 const value_type& front() const {
250 const value_type& back() const {
252 return detail::value_before(e_);
254 // Works only for Range<const char*>
255 std::string str() const { return std::string(b_, size()); }
256 std::string toString() const { return str(); }
257 // Works only for Range<const char*>
258 fbstring fbstr() const { return fbstring(b_, size()); }
259 fbstring toFbstring() const { return fbstr(); }
261 // Works only for Range<const char*>
262 int compare(const Range& o) const {
263 const size_type tsize = this->size();
264 const size_type osize = o.size();
265 const size_type msize = std::min(tsize, osize);
266 int r = traits_type::compare(data(), o.data(), msize);
267 if (r == 0) r = tsize - osize;
271 value_type& operator[](size_t i) {
276 const value_type& operator[](size_t i) const {
281 value_type& at(size_t i) {
282 if (i >= size()) throw std::out_of_range("index out of range");
286 const value_type& at(size_t i) const {
287 if (i >= size()) throw std::out_of_range("index out of range");
291 // Works only for Range<const char*>
292 uint32_t hash() const {
293 // Taken from fbi/nstring.h:
294 // Quick and dirty bernstein hash...fine for short ascii strings
295 uint32_t hash = 5381;
296 for (size_t ix = 0; ix < size(); ix++) {
297 hash = ((hash << 5) + hash) + b_[ix];
302 void advance(size_type n) {
307 void subtract(size_type n) {
322 Range subpiece(size_type first,
323 size_type length = std::string::npos) const {
324 CHECK_LE(first, size());
325 return Range(b_ + first,
326 std::min<std::string::size_type>(length, size() - first));
329 // string work-alike functions
330 size_type find(Range str) const {
331 return qfind(*this, str);
334 size_type find(Range str, size_t pos) const {
335 if (pos > size()) return std::string::npos;
336 size_t ret = qfind(subpiece(pos), str);
337 return ret == npos ? ret : ret + pos;
340 size_type find(Iter s, size_t pos, size_t n) const {
341 if (pos > size()) return std::string::npos;
342 size_t ret = qfind(pos ? subpiece(pos) : *this, Range(s, n));
343 return ret == npos ? ret : ret + pos;
346 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
347 size_type find(const Iter s) const {
348 return qfind(*this, Range(s));
351 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
352 size_type find(const Iter s, size_t pos) const {
353 if (pos > size()) return std::string::npos;
354 size_type ret = qfind(subpiece(pos), Range(s));
355 return ret == npos ? ret : ret + pos;
358 size_type find(value_type c) const {
359 return qfind(*this, c);
362 size_type find(value_type c, size_t pos) const {
363 if (pos > size()) return std::string::npos;
364 size_type ret = qfind(subpiece(pos), c);
365 return ret == npos ? ret : ret + pos;
368 size_type find_first_of(Range needles) const {
369 return qfind_first_of(*this, needles);
372 size_type find_first_of(Range needles, size_t pos) const {
373 if (pos > size()) return std::string::npos;
374 size_type ret = qfind_first_of(subpiece(pos), needles);
375 return ret == npos ? ret : ret + pos;
378 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
379 size_type find_first_of(Iter needles) const {
380 return find_first_of(Range(needles));
383 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
384 size_type find_first_of(Iter needles, size_t pos) const {
385 return find_first_of(Range(needles), pos);
388 size_type find_first_of(Iter needles, size_t pos, size_t n) const {
389 return find_first_of(Range(needles, n), pos);
392 size_type find_first_of(value_type c) const {
396 size_type find_first_of(value_type c, size_t pos) const {
400 void swap(Range& rhs) {
401 std::swap(b_, rhs.b_);
402 std::swap(e_, rhs.e_);
409 template <class Iter>
410 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
413 void swap(Range<T>& lhs, Range<T>& rhs) {
418 * Create a range from two iterators, with type deduction.
420 template <class Iter>
421 Range<Iter> makeRange(Iter first, Iter last) {
422 return Range<Iter>(first, last);
425 typedef Range<const char*> StringPiece;
426 typedef Range<const unsigned char*> ByteRange;
428 std::ostream& operator<<(std::ostream& os, const StringPiece& piece);
431 * Templated comparison operators
435 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
436 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
440 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
441 return lhs.compare(rhs) < 0;
445 * Specializations of comparison operators for StringPiece
450 template <class A, class B>
451 struct ComparableAsStringPiece {
454 (boost::is_convertible<A, StringPiece>::value
455 && boost::is_same<B, StringPiece>::value)
457 (boost::is_convertible<B, StringPiece>::value
458 && boost::is_same<A, StringPiece>::value)
462 } // namespace detail
465 * operator== through conversion for Range<const char*>
467 template <class T, class U>
469 boost::enable_if_c<detail::ComparableAsStringPiece<T, U>::value, bool>::type
470 operator==(const T& lhs, const U& rhs) {
471 return StringPiece(lhs) == StringPiece(rhs);
475 * operator< through conversion for Range<const char*>
477 template <class T, class U>
479 boost::enable_if_c<detail::ComparableAsStringPiece<T, U>::value, bool>::type
480 operator<(const T& lhs, const U& rhs) {
481 return StringPiece(lhs) < StringPiece(rhs);
485 * operator> through conversion for Range<const char*>
487 template <class T, class U>
489 boost::enable_if_c<detail::ComparableAsStringPiece<T, U>::value, bool>::type
490 operator>(const T& lhs, const U& rhs) {
491 return StringPiece(lhs) > StringPiece(rhs);
495 * operator< through conversion for Range<const char*>
497 template <class T, class U>
499 boost::enable_if_c<detail::ComparableAsStringPiece<T, U>::value, bool>::type
500 operator<=(const T& lhs, const U& rhs) {
501 return StringPiece(lhs) <= StringPiece(rhs);
505 * operator> through conversion for Range<const char*>
507 template <class T, class U>
509 boost::enable_if_c<detail::ComparableAsStringPiece<T, U>::value, bool>::type
510 operator>=(const T& lhs, const U& rhs) {
511 return StringPiece(lhs) >= StringPiece(rhs);
514 struct StringPieceHash {
515 std::size_t operator()(const StringPiece& str) const {
516 return static_cast<std::size_t>(str.hash());
521 * Finds substrings faster than brute force by borrowing from Boyer-Moore
523 template <class T, class Comp>
524 size_t qfind(const Range<T>& haystack,
525 const Range<T>& needle,
527 // Don't use std::search, use a Boyer-Moore-like trick by comparing
528 // the last characters first
529 auto const nsize = needle.size();
530 if (haystack.size() < nsize) {
531 return std::string::npos;
533 if (!nsize) return 0;
534 auto const nsize_1 = nsize - 1;
535 auto const lastNeedle = needle[nsize_1];
537 // Boyer-Moore skip value for the last char in the needle. Zero is
538 // not a valid value; skip will be computed the first time it's
540 std::string::size_type skip = 0;
542 auto i = haystack.begin();
543 auto iEnd = haystack.end() - nsize_1;
546 // Boyer-Moore: match the last element in the needle
547 while (!eq(i[nsize_1], lastNeedle)) {
550 return std::string::npos;
553 // Here we know that the last char matches
554 // Continue in pedestrian mode
555 for (size_t j = 0; ; ) {
557 if (!eq(i[j], needle[j])) {
558 // Not found, we can skip
559 // Compute the skip value lazily
562 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
569 // Check if done searching
572 return i - haystack.begin();
576 return std::string::npos;
581 size_t qfind_first_byte_of_sse42(const StringPiece& haystack,
582 const StringPiece& needles);
584 size_t qfind_first_byte_of_nosse(const StringPiece& haystack,
585 const StringPiece& needles);
587 inline size_t qfind_first_byte_of(const StringPiece& haystack,
588 const StringPiece& needles) {
589 static auto const qfind_first_byte_of_fn =
590 folly::CpuId().sse42() ? qfind_first_byte_of_sse42
591 : qfind_first_byte_of_nosse;
592 return qfind_first_byte_of_fn(haystack, needles);
595 } // namespace detail
597 template <class T, class Comp>
598 size_t qfind_first_of(const Range<T> & haystack,
599 const Range<T> & needles,
601 auto ret = std::find_first_of(haystack.begin(), haystack.end(),
602 needles.begin(), needles.end(),
604 return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
607 struct AsciiCaseSensitive {
608 bool operator()(char lhs, char rhs) const {
613 struct AsciiCaseInsensitive {
614 bool operator()(char lhs, char rhs) const {
615 return toupper(lhs) == toupper(rhs);
619 extern const AsciiCaseSensitive asciiCaseSensitive;
620 extern const AsciiCaseInsensitive asciiCaseInsensitive;
623 size_t qfind(const Range<T>& haystack,
624 const Range<T>& needle) {
625 return qfind(haystack, needle, asciiCaseSensitive);
629 size_t qfind(const Range<T>& haystack,
630 const typename Range<T>::value_type& needle) {
631 auto pos = std::find(haystack.begin(), haystack.end(), needle);
632 return pos == haystack.end() ? std::string::npos : pos - haystack.data();
635 // specialization for StringPiece
637 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
638 auto pos = static_cast<const char*>(
639 ::memchr(haystack.data(), needle, haystack.size()));
640 return pos == nullptr ? std::string::npos : pos - haystack.data();
643 // specialization for ByteRange
645 inline size_t qfind(const Range<const unsigned char*>& haystack,
646 const unsigned char& needle) {
647 auto pos = static_cast<const unsigned char*>(
648 ::memchr(haystack.data(), needle, haystack.size()));
649 return pos == nullptr ? std::string::npos : pos - haystack.data();
653 size_t qfind_first_of(const Range<T>& haystack,
654 const Range<T>& needles) {
655 return qfind_first_of(haystack, needles, asciiCaseSensitive);
658 // specialization for StringPiece
660 inline size_t qfind_first_of(const Range<const char*>& haystack,
661 const Range<const char*>& needles) {
662 return detail::qfind_first_byte_of(haystack, needles);
665 // specialization for ByteRange
667 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
668 const Range<const unsigned char*>& needles) {
669 return detail::qfind_first_byte_of(StringPiece(haystack),
670 StringPiece(needles));
672 } // !namespace folly
674 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);
676 #endif // FOLLY_RANGE_H_