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/folly-config.h"
24 #include "folly/FBString.h"
25 #include <glog/logging.h>
31 #include <type_traits>
32 #include <boost/operators.hpp>
33 #include <boost/utility/enable_if.hpp>
34 #include <boost/type_traits.hpp>
35 #include <bits/c++config.h>
36 #include "folly/CpuId.h"
37 #include "folly/Traits.h"
41 template <class T> class Range;
44 * Finds the first occurrence of needle in haystack. The algorithm is on
45 * average faster than O(haystack.size() * needle.size()) but not as fast
46 * as Boyer-Moore. On the upside, it does not do any upfront
47 * preprocessing and does not allocate memory.
50 inline size_t qfind(const Range<T> & haystack,
51 const Range<T> & needle);
54 * Finds the first occurrence of needle in haystack. The result is the
55 * offset reported to the beginning of haystack, or string::npos if
56 * needle wasn't found.
59 size_t qfind(const Range<T> & haystack,
60 const typename Range<T>::value_type& needle);
64 * Finds the first occurrence of any element of needle in
65 * haystack. The algorithm is O(haystack.size() * needle.size()).
68 inline size_t qfind_first_of(const Range<T> & haystack,
69 const Range<T> & needle);
72 * Small internal helper - returns the value just before an iterator.
77 * For random-access iterators, the value before is simply i[-1].
80 typename boost::enable_if_c<
81 boost::is_same<typename std::iterator_traits<Iter>::iterator_category,
82 std::random_access_iterator_tag>::value,
83 typename std::iterator_traits<Iter>::reference>::type
84 value_before(Iter i) {
89 * For all other iterators, we need to use the decrement operator.
92 typename boost::enable_if_c<
93 !boost::is_same<typename std::iterator_traits<Iter>::iterator_category,
94 std::random_access_iterator_tag>::value,
95 typename std::iterator_traits<Iter>::reference>::type
96 value_before(Iter i) {
100 } // namespace detail
103 * Range abstraction keeping a pair of iterators. We couldn't use
104 * boost's similar range abstraction because we need an API identical
105 * with the former StringPiece class, which is used by a lot of other
106 * code. This abstraction does fulfill the needs of boost's
107 * range-oriented algorithms though.
109 * (Keep memory lifetime in mind when using this class, since it
110 * doesn't manage the data it refers to - just like an iterator
113 template <class Iter>
114 class Range : private boost::totally_ordered<Range<Iter> > {
116 typedef std::size_t size_type;
117 typedef Iter iterator;
118 typedef Iter const_iterator;
119 typedef typename boost::remove_reference<
120 typename std::iterator_traits<Iter>::reference>::type
122 typedef typename std::iterator_traits<Iter>::reference reference;
123 typedef std::char_traits<value_type> traits_type;
125 static const size_type npos;
127 // Works for all iterators
128 Range() : b_(), e_() {
132 // Works for all iterators
133 Range(Iter start, Iter end) : b_(start), e_(end) {
136 // Works only for random-access iterators
137 Range(Iter start, size_t size)
138 : b_(start), e_(start + size) { }
140 // Works only for Range<const char*>
141 /* implicit */ Range(Iter str)
142 : b_(str), e_(b_ + strlen(str)) {}
143 // Works only for Range<const char*>
144 /* implicit */ Range(const std::string& str)
145 : b_(str.data()), e_(b_ + str.size()) {}
146 // Works only for Range<const char*>
147 Range(const std::string& str, std::string::size_type startFrom) {
148 CHECK_LE(startFrom, str.size());
149 b_ = str.data() + startFrom;
150 e_ = str.data() + str.size();
152 // Works only for Range<const char*>
153 Range(const std::string& str,
154 std::string::size_type startFrom,
155 std::string::size_type size) {
156 CHECK_LE(startFrom + size, str.size());
157 b_ = str.data() + startFrom;
160 Range(const Range<Iter>& str,
163 CHECK_LE(startFrom + size, str.size());
164 b_ = str.b_ + startFrom;
167 // Works only for Range<const char*>
168 /* implicit */ Range(const fbstring& str)
169 : b_(str.data()), e_(b_ + str.size()) { }
170 // Works only for Range<const char*>
171 Range(const fbstring& str, fbstring::size_type startFrom) {
172 CHECK_LE(startFrom, str.size());
173 b_ = str.data() + startFrom;
174 e_ = str.data() + str.size();
176 // Works only for Range<const char*>
177 Range(const fbstring& str, fbstring::size_type startFrom,
178 fbstring::size_type size) {
179 CHECK_LE(startFrom + size, str.size());
180 b_ = str.data() + startFrom;
184 // Allow implicit conversion from Range<const char*> (aka StringPiece) to
185 // Range<const unsigned char*> (aka ByteRange), as they're both frequently
186 // used to represent ranges of bytes. Allow explicit conversion in the other
188 template <class OtherIter, typename std::enable_if<
189 (std::is_same<Iter, const unsigned char*>::value &&
190 std::is_same<OtherIter, const char*>::value), int>::type = 0>
191 /* implicit */ Range(const Range<OtherIter>& other)
192 : b_(reinterpret_cast<const unsigned char*>(other.begin())),
193 e_(reinterpret_cast<const unsigned char*>(other.end())) {
196 template <class OtherIter, typename std::enable_if<
197 (std::is_same<Iter, const char*>::value &&
198 std::is_same<OtherIter, const unsigned char*>::value), int>::type = 0>
199 explicit Range(const Range<OtherIter>& other)
200 : b_(reinterpret_cast<const char*>(other.begin())),
201 e_(reinterpret_cast<const char*>(other.end())) {
209 void assign(Iter start, Iter end) {
214 void reset(Iter start, size_type size) {
219 // Works only for Range<const char*>
220 void reset(const std::string& str) {
221 reset(str.data(), str.size());
224 size_type size() const {
228 size_type walk_size() const {
230 return std::distance(b_, e_);
232 bool empty() const { return b_ == e_; }
233 Iter data() const { return b_; }
234 Iter start() const { return b_; }
235 Iter begin() const { return b_; }
236 Iter end() const { return e_; }
237 Iter cbegin() const { return b_; }
238 Iter cend() const { return e_; }
239 value_type& front() {
245 return detail::value_before(e_);
247 const value_type& front() const {
251 const value_type& back() const {
253 return detail::value_before(e_);
255 // Works only for Range<const char*>
256 std::string str() const { return std::string(b_, size()); }
257 std::string toString() const { return str(); }
258 // Works only for Range<const char*>
259 fbstring fbstr() const { return fbstring(b_, size()); }
260 fbstring toFbstring() const { return fbstr(); }
262 // Works only for Range<const char*>
263 int compare(const Range& o) const {
264 const size_type tsize = this->size();
265 const size_type osize = o.size();
266 const size_type msize = std::min(tsize, osize);
267 int r = traits_type::compare(data(), o.data(), msize);
268 if (r == 0) r = tsize - osize;
272 value_type& operator[](size_t i) {
277 const value_type& operator[](size_t i) const {
282 value_type& at(size_t i) {
283 if (i >= size()) throw std::out_of_range("index out of range");
287 const value_type& at(size_t i) const {
288 if (i >= size()) throw std::out_of_range("index out of range");
292 // Works only for Range<const char*>
293 uint32_t hash() const {
294 // Taken from fbi/nstring.h:
295 // Quick and dirty bernstein hash...fine for short ascii strings
296 uint32_t hash = 5381;
297 for (size_t ix = 0; ix < size(); ix++) {
298 hash = ((hash << 5) + hash) + b_[ix];
303 void advance(size_type n) {
308 void subtract(size_type n) {
323 Range subpiece(size_type first,
324 size_type length = std::string::npos) const {
325 CHECK_LE(first, size());
326 return Range(b_ + first,
327 std::min<std::string::size_type>(length, size() - first));
330 // string work-alike functions
331 size_type find(Range str) const {
332 return qfind(*this, str);
335 size_type find(Range str, size_t pos) const {
336 if (pos > size()) return std::string::npos;
337 size_t ret = qfind(subpiece(pos), str);
338 return ret == npos ? ret : ret + pos;
341 size_type find(Iter s, size_t pos, size_t n) const {
342 if (pos > size()) return std::string::npos;
343 size_t ret = qfind(pos ? subpiece(pos) : *this, Range(s, n));
344 return ret == npos ? ret : ret + pos;
347 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
348 size_type find(const Iter s) const {
349 return qfind(*this, Range(s));
352 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
353 size_type find(const Iter s, size_t pos) const {
354 if (pos > size()) return std::string::npos;
355 size_type ret = qfind(subpiece(pos), Range(s));
356 return ret == npos ? ret : ret + pos;
359 size_type find(value_type c) const {
360 return qfind(*this, c);
363 size_type find(value_type c, size_t pos) const {
364 if (pos > size()) return std::string::npos;
365 size_type ret = qfind(subpiece(pos), c);
366 return ret == npos ? ret : ret + pos;
369 size_type find_first_of(Range needles) const {
370 return qfind_first_of(*this, needles);
373 size_type find_first_of(Range needles, size_t pos) const {
374 if (pos > size()) return std::string::npos;
375 size_type ret = qfind_first_of(subpiece(pos), needles);
376 return ret == npos ? ret : ret + pos;
379 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
380 size_type find_first_of(Iter needles) const {
381 return find_first_of(Range(needles));
384 // Works only for Range<const (unsigned) char*> which have Range(Iter) ctor
385 size_type find_first_of(Iter needles, size_t pos) const {
386 return find_first_of(Range(needles), pos);
389 size_type find_first_of(Iter needles, size_t pos, size_t n) const {
390 return find_first_of(Range(needles, n), pos);
393 size_type find_first_of(value_type c) const {
397 size_type find_first_of(value_type c, size_t pos) const {
401 void swap(Range& rhs) {
402 std::swap(b_, rhs.b_);
403 std::swap(e_, rhs.e_);
410 template <class Iter>
411 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
414 void swap(Range<T>& lhs, Range<T>& rhs) {
419 * Create a range from two iterators, with type deduction.
421 template <class Iter>
422 Range<Iter> makeRange(Iter first, Iter last) {
423 return Range<Iter>(first, last);
426 typedef Range<const char*> StringPiece;
427 typedef Range<const unsigned char*> ByteRange;
429 std::ostream& operator<<(std::ostream& os, const StringPiece& piece);
432 * Templated comparison operators
436 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
437 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
441 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
442 return lhs.compare(rhs) < 0;
446 * Specializations of comparison operators for StringPiece
451 template <class A, class B>
452 struct ComparableAsStringPiece {
455 (boost::is_convertible<A, StringPiece>::value
456 && boost::is_same<B, StringPiece>::value)
458 (boost::is_convertible<B, StringPiece>::value
459 && boost::is_same<A, StringPiece>::value)
463 } // namespace detail
466 * operator== through conversion for Range<const char*>
468 template <class T, class U>
470 boost::enable_if_c<detail::ComparableAsStringPiece<T, U>::value, bool>::type
471 operator==(const T& lhs, const U& rhs) {
472 return StringPiece(lhs) == StringPiece(rhs);
476 * operator< through conversion for Range<const char*>
478 template <class T, class U>
480 boost::enable_if_c<detail::ComparableAsStringPiece<T, U>::value, bool>::type
481 operator<(const T& lhs, const U& rhs) {
482 return StringPiece(lhs) < StringPiece(rhs);
486 * operator> through conversion for Range<const char*>
488 template <class T, class U>
490 boost::enable_if_c<detail::ComparableAsStringPiece<T, U>::value, bool>::type
491 operator>(const T& lhs, const U& rhs) {
492 return StringPiece(lhs) > StringPiece(rhs);
496 * operator< through conversion for Range<const char*>
498 template <class T, class U>
500 boost::enable_if_c<detail::ComparableAsStringPiece<T, U>::value, bool>::type
501 operator<=(const T& lhs, const U& rhs) {
502 return StringPiece(lhs) <= StringPiece(rhs);
506 * operator> through conversion for Range<const char*>
508 template <class T, class U>
510 boost::enable_if_c<detail::ComparableAsStringPiece<T, U>::value, bool>::type
511 operator>=(const T& lhs, const U& rhs) {
512 return StringPiece(lhs) >= StringPiece(rhs);
515 struct StringPieceHash {
516 std::size_t operator()(const StringPiece& str) const {
517 return static_cast<std::size_t>(str.hash());
522 * Finds substrings faster than brute force by borrowing from Boyer-Moore
524 template <class T, class Comp>
525 size_t qfind(const Range<T>& haystack,
526 const Range<T>& needle,
528 // Don't use std::search, use a Boyer-Moore-like trick by comparing
529 // the last characters first
530 auto const nsize = needle.size();
531 if (haystack.size() < nsize) {
532 return std::string::npos;
534 if (!nsize) return 0;
535 auto const nsize_1 = nsize - 1;
536 auto const lastNeedle = needle[nsize_1];
538 // Boyer-Moore skip value for the last char in the needle. Zero is
539 // not a valid value; skip will be computed the first time it's
541 std::string::size_type skip = 0;
543 auto i = haystack.begin();
544 auto iEnd = haystack.end() - nsize_1;
547 // Boyer-Moore: match the last element in the needle
548 while (!eq(i[nsize_1], lastNeedle)) {
551 return std::string::npos;
554 // Here we know that the last char matches
555 // Continue in pedestrian mode
556 for (size_t j = 0; ; ) {
558 if (!eq(i[j], needle[j])) {
559 // Not found, we can skip
560 // Compute the skip value lazily
563 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
570 // Check if done searching
573 return i - haystack.begin();
577 return std::string::npos;
582 size_t qfind_first_byte_of_nosse(const StringPiece& haystack,
583 const StringPiece& needles);
585 #if FOLLY_HAVE_EMMINTRIN_H
586 size_t qfind_first_byte_of_sse42(const StringPiece& haystack,
587 const StringPiece& needles);
589 inline size_t qfind_first_byte_of(const StringPiece& haystack,
590 const StringPiece& needles) {
591 static auto const qfind_first_byte_of_fn =
592 folly::CpuId().sse42() ? qfind_first_byte_of_sse42
593 : qfind_first_byte_of_nosse;
594 return qfind_first_byte_of_fn(haystack, needles);
598 inline size_t qfind_first_byte_of(const StringPiece& haystack,
599 const StringPiece& needles) {
600 return qfind_first_byte_of_nosse(haystack, needles);
602 #endif // FOLLY_HAVE_EMMINTRIN_H
604 } // namespace detail
606 template <class T, class Comp>
607 size_t qfind_first_of(const Range<T> & haystack,
608 const Range<T> & needles,
610 auto ret = std::find_first_of(haystack.begin(), haystack.end(),
611 needles.begin(), needles.end(),
613 return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
616 struct AsciiCaseSensitive {
617 bool operator()(char lhs, char rhs) const {
622 struct AsciiCaseInsensitive {
623 bool operator()(char lhs, char rhs) const {
624 return toupper(lhs) == toupper(rhs);
628 extern const AsciiCaseSensitive asciiCaseSensitive;
629 extern const AsciiCaseInsensitive asciiCaseInsensitive;
632 size_t qfind(const Range<T>& haystack,
633 const Range<T>& needle) {
634 return qfind(haystack, needle, asciiCaseSensitive);
638 size_t qfind(const Range<T>& haystack,
639 const typename Range<T>::value_type& needle) {
640 auto pos = std::find(haystack.begin(), haystack.end(), needle);
641 return pos == haystack.end() ? std::string::npos : pos - haystack.data();
644 // specialization for StringPiece
646 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
647 auto pos = static_cast<const char*>(
648 ::memchr(haystack.data(), needle, haystack.size()));
649 return pos == nullptr ? std::string::npos : pos - haystack.data();
652 // specialization for ByteRange
654 inline size_t qfind(const Range<const unsigned char*>& haystack,
655 const unsigned char& needle) {
656 auto pos = static_cast<const unsigned char*>(
657 ::memchr(haystack.data(), needle, haystack.size()));
658 return pos == nullptr ? std::string::npos : pos - haystack.data();
662 size_t qfind_first_of(const Range<T>& haystack,
663 const Range<T>& needles) {
664 return qfind_first_of(haystack, needles, asciiCaseSensitive);
667 // specialization for StringPiece
669 inline size_t qfind_first_of(const Range<const char*>& haystack,
670 const Range<const char*>& needles) {
671 return detail::qfind_first_byte_of(haystack, needles);
674 // specialization for ByteRange
676 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
677 const Range<const unsigned char*>& needles) {
678 return detail::qfind_first_byte_of(StringPiece(haystack),
679 StringPiece(needles));
681 } // !namespace folly
683 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);
685 #endif // FOLLY_RANGE_H_