2 * Copyright 2012 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>
28 #include <type_traits>
29 #include <boost/operators.hpp>
30 #include <boost/utility/enable_if.hpp>
31 #include <boost/type_traits.hpp>
32 #include <bits/c++config.h>
33 #include "folly/Traits.h"
37 template <class T> class Range;
40 Finds the first occurrence of needle in haystack. The algorithm is on
41 average faster than O(haystack.size() * needle.size()) but not as fast
42 as Boyer-Moore. On the upside, it does not do any upfront
43 preprocessing and does not allocate memory.
46 inline size_t qfind(const Range<T> & haystack,
47 const Range<T> & needle);
50 Finds the first occurrence of needle in haystack. The result is the
51 offset reported to the beginning of haystack, or string::npos if
55 size_t qfind(const Range<T> & haystack,
56 const typename Range<T>::value_type& needle);
59 * Small internal helper - returns the value just before an iterator.
64 * For random-access iterators, the value before is simply i[-1].
67 typename boost::enable_if_c<
68 boost::is_same<typename std::iterator_traits<Iter>::iterator_category,
69 std::random_access_iterator_tag>::value,
70 typename std::iterator_traits<Iter>::reference>::type
71 value_before(Iter i) {
76 * For all other iterators, we need to use the decrement operator.
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) {
90 * Range abstraction keeping a pair of iterators. We couldn't use
91 * boost's similar range abstraction because we need an API identical
92 * with the former StringPiece class, which is used by a lot of other
93 * code. This abstraction does fulfill the needs of boost's
94 * range-oriented algorithms though.
96 * (Keep memory lifetime in mind when using this class, since it
97 * doesn't manage the data it refers to - just like an iterator
100 template <class Iter>
101 class Range : private boost::totally_ordered<Range<Iter> > {
103 typedef std::size_t size_type;
104 typedef Iter iterator;
105 typedef Iter const_iterator;
106 typedef typename boost::remove_reference<
107 typename std::iterator_traits<Iter>::reference>::type
109 typedef typename std::iterator_traits<Iter>::reference reference;
110 typedef std::char_traits<value_type> traits_type;
112 static const size_type npos = -1;
114 // Works for all iterators
115 Range() : b_(), e_() {
119 static bool reachable(Iter b, Iter e, std::forward_iterator_tag) {
120 for (; b != e; ++b) {
121 LOG_EVERY_N(INFO, 100000) << __FILE__ ":" << __LINE__
122 << " running reachability test ("
123 << google::COUNTER << " iterations)...";
128 static bool reachable(Iter b, Iter e, std::random_access_iterator_tag) {
133 // Works for all iterators
134 Range(Iter start, Iter end)
135 : b_(start), e_(end) {
136 assert(reachable(b_, e_,
137 typename std::iterator_traits<Iter>::iterator_category()));
140 // Works only for random-access iterators
141 Range(Iter start, size_t size)
142 : b_(start), e_(start + size) { }
144 // Works only for Range<const char*>
145 /* implicit */ Range(Iter str)
146 : b_(str), e_(b_ + strlen(str)) {}
147 // Works only for Range<const char*>
148 /* implicit */ Range(const std::string& str)
149 : b_(str.data()), e_(b_ + str.size()) {}
150 // Works only for Range<const char*>
151 Range(const std::string& str, std::string::size_type startFrom) {
152 CHECK_LE(startFrom, str.size());
153 b_ = str.data() + startFrom;
154 e_ = str.data() + str.size();
156 // Works only for Range<const char*>
157 Range(const std::string& str,
158 std::string::size_type startFrom,
159 std::string::size_type size) {
160 CHECK_LE(startFrom + size, str.size());
161 b_ = str.data() + startFrom;
164 Range(const Range<Iter>& str,
167 CHECK_LE(startFrom + size, str.size());
168 b_ = str.b_ + startFrom;
171 // Works only for Range<const char*>
172 /* implicit */ Range(const fbstring& str)
173 : b_(str.data()), e_(b_ + str.size()) { }
174 // Works only for Range<const char*>
175 Range(const fbstring& str, fbstring::size_type startFrom) {
176 CHECK_LE(startFrom, str.size());
177 b_ = str.data() + startFrom;
178 e_ = str.data() + str.size();
180 // Works only for Range<const char*>
181 Range(const fbstring& str, fbstring::size_type startFrom,
182 fbstring::size_type size) {
183 CHECK_LE(startFrom + size, str.size());
184 b_ = str.data() + startFrom;
188 // Allow implicit conversion from Range<const char*> (aka StringPiece) to
189 // Range<const unsigned char*> (aka ByteRange), as they're both frequently
190 // used to represent ranges of bytes. Allow explicit conversion in the other
192 template <class OtherIter, typename std::enable_if<
193 (std::is_same<Iter, const unsigned char*>::value &&
194 std::is_same<OtherIter, const char*>::value), int>::type = 0>
195 /* implicit */ Range(const Range<OtherIter>& other)
196 : b_(reinterpret_cast<const unsigned char*>(other.begin())),
197 e_(reinterpret_cast<const unsigned char*>(other.end())) {
200 template <class OtherIter, typename std::enable_if<
201 (std::is_same<Iter, const char*>::value &&
202 std::is_same<OtherIter, const unsigned char*>::value), int>::type = 0>
203 explicit Range(const Range<OtherIter>& other)
204 : b_(reinterpret_cast<const char*>(other.begin())),
205 e_(reinterpret_cast<const char*>(other.end())) {
213 void assign(Iter start, Iter end) {
218 void reset(Iter start, size_type size) {
223 // Works only for Range<const char*>
224 void reset(const std::string& str) {
225 reset(str.data(), str.size());
228 size_type size() const {
232 size_type walk_size() const {
234 return std::distance(b_, e_);
236 bool empty() const { return b_ == e_; }
237 Iter data() const { return b_; }
238 Iter start() const { return b_; }
239 Iter begin() const { return b_; }
240 Iter end() const { return e_; }
241 Iter cbegin() const { return b_; }
242 Iter cend() const { return e_; }
243 value_type& front() {
249 return detail::value_before(e_);
251 const value_type& front() const {
255 const value_type& back() const {
257 return detail::value_before(e_);
259 // Works only for Range<const char*>
260 std::string str() const { return std::string(b_, size()); }
261 std::string toString() const { return str(); }
262 // Works only for Range<const char*>
263 fbstring fbstr() const { return fbstring(b_, size()); }
264 fbstring toFbstring() const { return fbstr(); }
266 // Works only for Range<const char*>
267 int compare(const Range& o) const {
268 const size_type tsize = this->size();
269 const size_type osize = o.size();
270 const size_type msize = std::min(tsize, osize);
271 int r = traits_type::compare(data(), o.data(), msize);
272 if (r == 0) r = tsize - osize;
276 value_type& operator[](size_t i) {
281 const value_type& operator[](size_t i) const {
286 value_type& at(size_t i) {
287 if (i >= size()) throw std::out_of_range("index out of range");
291 const value_type& at(size_t i) const {
292 if (i >= size()) throw std::out_of_range("index out of range");
296 // Works only for Range<const char*>
297 uint32_t hash() const {
298 // Taken from fbi/nstring.h:
299 // Quick and dirty bernstein hash...fine for short ascii strings
300 uint32_t hash = 5381;
301 for (size_t ix = 0; ix < size(); ix++) {
302 hash = ((hash << 5) + hash) + b_[ix];
307 void advance(size_type n) {
312 void subtract(size_type n) {
327 Range subpiece(size_type first,
328 size_type length = std::string::npos) const {
329 CHECK_LE(first, size());
330 return Range(b_ + first,
331 std::min<std::string::size_type>(length, size() - first));
334 // string work-alike functions
335 size_type find(Range str) const {
336 return qfind(*this, str);
339 size_type find(Range str, size_t pos) const {
340 if (pos > size()) return std::string::npos;
341 size_t ret = qfind(subpiece(pos), str);
342 return ret == npos ? ret : ret + pos;
345 size_type find(Iter s, size_t pos, size_t n) const {
346 if (pos > size()) return std::string::npos;
347 size_t ret = qfind(pos ? subpiece(pos) : *this, Range(s, n));
348 return ret == npos ? ret : ret + pos;
351 size_type find(const Iter s) const {
352 return qfind(*this, Range(s));
355 size_type find(const Iter s, size_t pos) const {
356 if (pos > size()) return std::string::npos;
357 size_type ret = qfind(subpiece(pos), Range(s));
358 return ret == npos ? ret : ret + pos;
361 size_type find(value_type c) const {
362 return qfind(*this, c);
365 size_type find(value_type c, size_t pos) const {
366 if (pos > size()) return std::string::npos;
367 size_type ret = qfind(subpiece(pos), c);
368 return ret == npos ? ret : ret + pos;
371 void swap(Range& rhs) {
372 std::swap(b_, rhs.b_);
373 std::swap(e_, rhs.e_);
380 template <class Iter>
381 const typename Range<Iter>::size_type Range<Iter>::npos;
384 void swap(Range<T>& lhs, Range<T>& rhs) {
389 * Create a range from two iterators, with type deduction.
391 template <class Iter>
392 Range<Iter> makeRange(Iter first, Iter last) {
393 return Range<Iter>(first, last);
396 typedef Range<const char*> StringPiece;
397 typedef Range<const unsigned char*> ByteRange;
399 std::ostream& operator<<(std::ostream& os, const StringPiece& piece);
402 * Templated comparison operators
406 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
407 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
411 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
412 return lhs.compare(rhs) < 0;
416 * Specializations of comparison operators for StringPiece
421 template <class A, class B>
422 struct ComparableAsStringPiece {
425 (boost::is_convertible<A, StringPiece>::value
426 && boost::is_same<B, StringPiece>::value)
428 (boost::is_convertible<B, StringPiece>::value
429 && boost::is_same<A, StringPiece>::value)
433 } // namespace detail
436 * operator== through conversion for Range<const char*>
438 template <class T, class U>
440 boost::enable_if_c<detail::ComparableAsStringPiece<T, U>::value, bool>::type
441 operator==(const T& lhs, const U& rhs) {
442 return StringPiece(lhs) == StringPiece(rhs);
446 * operator< through conversion for Range<const char*>
448 template <class T, class U>
450 boost::enable_if_c<detail::ComparableAsStringPiece<T, U>::value, bool>::type
451 operator<(const T& lhs, const U& rhs) {
452 return StringPiece(lhs) < StringPiece(rhs);
456 * operator> through conversion for Range<const char*>
458 template <class T, class U>
460 boost::enable_if_c<detail::ComparableAsStringPiece<T, U>::value, bool>::type
461 operator>(const T& lhs, const U& rhs) {
462 return StringPiece(lhs) > StringPiece(rhs);
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);
485 struct StringPieceHash {
486 std::size_t operator()(const StringPiece& str) const {
487 return static_cast<std::size_t>(str.hash());
492 * Finds substrings faster than brute force by borrowing from Boyer-Moore
494 template <class T, class Comp>
495 size_t qfind(const Range<T>& haystack,
496 const Range<T>& needle,
498 // Don't use std::search, use a Boyer-Moore-like trick by comparing
499 // the last characters first
500 auto const nsize = needle.size();
501 if (haystack.size() < nsize) {
502 return std::string::npos;
504 if (!nsize) return 0;
505 auto const nsize_1 = nsize - 1;
506 auto const lastNeedle = needle[nsize_1];
508 // Boyer-Moore skip value for the last char in the needle. Zero is
509 // not a valid value; skip will be computed the first time it's
511 std::string::size_type skip = 0;
513 auto i = haystack.begin();
514 auto iEnd = haystack.end() - nsize_1;
517 // Boyer-Moore: match the last element in the needle
518 while (!eq(i[nsize_1], lastNeedle)) {
521 return std::string::npos;
524 // Here we know that the last char matches
525 // Continue in pedestrian mode
526 for (size_t j = 0; ; ) {
528 if (!eq(i[j], needle[j])) {
529 // Not found, we can skip
530 // Compute the skip value lazily
533 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
540 // Check if done searching
543 return i - haystack.begin();
547 return std::string::npos;
550 struct AsciiCaseSensitive {
551 bool operator()(char lhs, char rhs) const {
556 struct AsciiCaseInsensitive {
557 bool operator()(char lhs, char rhs) const {
558 return toupper(lhs) == toupper(rhs);
562 extern const AsciiCaseSensitive asciiCaseSensitive;
563 extern const AsciiCaseInsensitive asciiCaseInsensitive;
566 size_t qfind(const Range<T>& haystack,
567 const Range<T>& needle) {
568 return qfind(haystack, needle, asciiCaseSensitive);
572 size_t qfind(const Range<T>& haystack,
573 const typename Range<T>::value_type& needle) {
574 return qfind(haystack, makeRange(&needle, &needle + 1));
577 } // !namespace folly
579 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);
581 #endif // FOLLY_RANGE_H_