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.
191 template <typename std::enable_if<
192 (std::is_same<Iter, const unsigned char*>::value), int>::type = 0>
193 /* implicit */ Range(const Range<const char*>& other)
194 : b_(reinterpret_cast<const unsigned char*>(other.begin())),
195 e_(reinterpret_cast<const unsigned char*>(other.end())) {
203 void assign(Iter start, Iter end) {
208 void reset(Iter start, size_type size) {
213 // Works only for Range<const char*>
214 void reset(const std::string& str) {
215 reset(str.data(), str.size());
218 size_type size() const {
222 size_type walk_size() const {
224 return std::distance(b_, e_);
226 bool empty() const { return b_ == e_; }
227 Iter data() const { return b_; }
228 Iter start() const { return b_; }
229 Iter begin() const { return b_; }
230 Iter end() const { return e_; }
231 Iter cbegin() const { return b_; }
232 Iter cend() const { return e_; }
233 value_type& front() {
239 return detail::value_before(e_);
241 const value_type& front() const {
245 const value_type& back() const {
247 return detail::value_before(e_);
249 // Works only for Range<const char*>
250 std::string str() const { return std::string(b_, size()); }
251 std::string toString() const { return str(); }
252 // Works only for Range<const char*>
253 fbstring fbstr() const { return fbstring(b_, size()); }
254 fbstring toFbstring() const { return fbstr(); }
256 // Works only for Range<const char*>
257 int compare(const Range& o) const {
258 const size_type tsize = this->size();
259 const size_type osize = o.size();
260 const size_type msize = std::min(tsize, osize);
261 int r = traits_type::compare(data(), o.data(), msize);
262 if (r == 0) r = tsize - osize;
266 value_type& operator[](size_t i) {
271 const value_type& operator[](size_t i) const {
276 value_type& at(size_t i) {
277 if (i >= size()) throw std::out_of_range("index out of range");
281 const value_type& at(size_t i) const {
282 if (i >= size()) throw std::out_of_range("index out of range");
286 // Works only for Range<const char*>
287 uint32_t hash() const {
288 // Taken from fbi/nstring.h:
289 // Quick and dirty bernstein hash...fine for short ascii strings
290 uint32_t hash = 5381;
291 for (size_t ix = 0; ix < size(); ix++) {
292 hash = ((hash << 5) + hash) + b_[ix];
297 void advance(size_type n) {
302 void subtract(size_type n) {
317 Range subpiece(size_type first,
318 size_type length = std::string::npos) const {
319 CHECK_LE(first, size());
320 return Range(b_ + first,
321 std::min<std::string::size_type>(length, size() - first));
324 // string work-alike functions
325 size_type find(Range str) const {
326 return qfind(*this, str);
329 size_type find(Range str, size_t pos) const {
330 if (pos > size()) return std::string::npos;
331 size_t ret = qfind(subpiece(pos), str);
332 return ret == npos ? ret : ret + pos;
335 size_type find(Iter s, size_t pos, size_t n) const {
336 if (pos > size()) return std::string::npos;
337 size_t ret = qfind(pos ? subpiece(pos) : *this, Range(s, n));
338 return ret == npos ? ret : ret + pos;
341 size_type find(const Iter s) const {
342 return qfind(*this, Range(s));
345 size_type find(const Iter s, size_t pos) const {
346 if (pos > size()) return std::string::npos;
347 size_type ret = qfind(subpiece(pos), Range(s));
348 return ret == npos ? ret : ret + pos;
351 size_type find(value_type c) const {
352 return qfind(*this, c);
355 size_type find(value_type c, size_t pos) const {
356 if (pos > size()) return std::string::npos;
357 size_type ret = qfind(subpiece(pos), c);
358 return ret == npos ? ret : ret + pos;
361 void swap(Range& rhs) {
362 std::swap(b_, rhs.b_);
363 std::swap(e_, rhs.e_);
370 template <class Iter>
371 const typename Range<Iter>::size_type Range<Iter>::npos;
374 void swap(Range<T>& lhs, Range<T>& rhs) {
379 * Create a range from two iterators, with type deduction.
381 template <class Iter>
382 Range<Iter> makeRange(Iter first, Iter last) {
383 return Range<Iter>(first, last);
386 typedef Range<const char*> StringPiece;
387 typedef Range<const unsigned char*> ByteRange;
389 std::ostream& operator<<(std::ostream& os, const StringPiece& piece);
392 * Templated comparison operators
396 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
397 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
401 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
402 return lhs.compare(rhs) < 0;
406 * Specializations of comparison operators for StringPiece
411 template <class A, class B>
412 struct ComparableAsStringPiece {
415 (boost::is_convertible<A, StringPiece>::value
416 && boost::is_same<B, StringPiece>::value)
418 (boost::is_convertible<B, StringPiece>::value
419 && boost::is_same<A, StringPiece>::value)
423 } // namespace detail
426 * operator== through conversion for Range<const char*>
428 template <class T, class U>
430 boost::enable_if_c<detail::ComparableAsStringPiece<T, U>::value, bool>::type
431 operator==(const T& lhs, const U& rhs) {
432 return StringPiece(lhs) == StringPiece(rhs);
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);
475 struct StringPieceHash {
476 std::size_t operator()(const StringPiece& str) const {
477 return static_cast<std::size_t>(str.hash());
482 * Finds substrings faster than brute force by borrowing from Boyer-Moore
484 template <class T, class Comp>
485 size_t qfind(const Range<T>& haystack,
486 const Range<T>& needle,
488 // Don't use std::search, use a Boyer-Moore-like trick by comparing
489 // the last characters first
490 auto const nsize = needle.size();
491 if (haystack.size() < nsize) {
492 return std::string::npos;
494 if (!nsize) return 0;
495 auto const nsize_1 = nsize - 1;
496 auto const lastNeedle = needle[nsize_1];
498 // Boyer-Moore skip value for the last char in the needle. Zero is
499 // not a valid value; skip will be computed the first time it's
501 std::string::size_type skip = 0;
503 auto i = haystack.begin();
504 auto iEnd = haystack.end() - nsize_1;
507 // Boyer-Moore: match the last element in the needle
508 while (!eq(i[nsize_1], lastNeedle)) {
511 return std::string::npos;
514 // Here we know that the last char matches
515 // Continue in pedestrian mode
516 for (size_t j = 0; ; ) {
518 if (!eq(i[j], needle[j])) {
519 // Not found, we can skip
520 // Compute the skip value lazily
523 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
530 // Check if done searching
533 return i - haystack.begin();
537 return std::string::npos;
540 struct AsciiCaseSensitive {
541 bool operator()(char lhs, char rhs) const {
546 struct AsciiCaseInsensitive {
547 bool operator()(char lhs, char rhs) const {
548 return toupper(lhs) == toupper(rhs);
552 extern const AsciiCaseSensitive asciiCaseSensitive;
553 extern const AsciiCaseInsensitive asciiCaseInsensitive;
556 size_t qfind(const Range<T>& haystack,
557 const Range<T>& needle) {
558 return qfind(haystack, needle, asciiCaseSensitive);
562 size_t qfind(const Range<T>& haystack,
563 const typename Range<T>::value_type& needle) {
564 return qfind(haystack, makeRange(&needle, &needle + 1));
567 } // !namespace folly
569 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);
571 #endif // FOLLY_RANGE_H_