2 * Copyright 2015 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/Portability.h>
24 #include <folly/FBString.h>
25 #include <folly/SpookyHashV2.h>
28 #include <boost/operators.hpp>
32 #include <glog/logging.h>
36 #include <type_traits>
38 // libc++ doesn't provide this header, nor does msvc
39 #ifdef FOLLY_HAVE_BITS_CXXCONFIG_H
40 // This file appears in two locations: inside fbcode and in the
41 // libstdc++ source code (when embedding fbstring as std::string).
42 // To aid in this schizophrenic use, two macros are defined in
44 // _LIBSTDCXX_FBSTRING - Set inside libstdc++. This is useful to
45 // gate use inside fbcode v. libstdc++
46 #include <bits/c++config.h>
49 #include <folly/CpuId.h>
50 #include <folly/Traits.h>
51 #include <folly/Likely.h>
52 #include <folly/detail/RangeCommon.h>
53 #include <folly/detail/RangeSse42.h>
55 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
56 #pragma GCC diagnostic push
57 #pragma GCC diagnostic ignored "-Wshadow"
61 template <class T> class Range;
64 * Finds the first occurrence of needle in haystack. The algorithm is on
65 * average faster than O(haystack.size() * needle.size()) but not as fast
66 * as Boyer-Moore. On the upside, it does not do any upfront
67 * preprocessing and does not allocate memory.
69 template <class T, class Comp = std::equal_to<typename Range<T>::value_type>>
70 inline size_t qfind(const Range<T> & haystack,
71 const Range<T> & needle,
75 * Finds the first occurrence of needle in haystack. The result is the
76 * offset reported to the beginning of haystack, or string::npos if
77 * needle wasn't found.
80 size_t qfind(const Range<T> & haystack,
81 const typename Range<T>::value_type& needle);
84 * Finds the last occurrence of needle in haystack. The result is the
85 * offset reported to the beginning of haystack, or string::npos if
86 * needle wasn't found.
89 size_t rfind(const Range<T> & haystack,
90 const typename Range<T>::value_type& needle);
94 * Finds the first occurrence of any element of needle in
95 * haystack. The algorithm is O(haystack.size() * needle.size()).
98 inline size_t qfind_first_of(const Range<T> & haystack,
99 const Range<T> & needle);
102 * Small internal helper - returns the value just before an iterator.
107 * For random-access iterators, the value before is simply i[-1].
109 template <class Iter>
110 typename std::enable_if<
111 std::is_same<typename std::iterator_traits<Iter>::iterator_category,
112 std::random_access_iterator_tag>::value,
113 typename std::iterator_traits<Iter>::reference>::type
114 value_before(Iter i) {
119 * For all other iterators, we need to use the decrement operator.
121 template <class Iter>
122 typename std::enable_if<
123 !std::is_same<typename std::iterator_traits<Iter>::iterator_category,
124 std::random_access_iterator_tag>::value,
125 typename std::iterator_traits<Iter>::reference>::type
126 value_before(Iter i) {
131 * Use IsCharPointer<T>::type to enable const char* or char*.
132 * Use IsCharPointer<T>::const_type to enable only const char*.
134 template <class T> struct IsCharPointer {};
137 struct IsCharPointer<char*> {
142 struct IsCharPointer<const char*> {
143 typedef int const_type;
147 } // namespace detail
150 * Range abstraction keeping a pair of iterators. We couldn't use
151 * boost's similar range abstraction because we need an API identical
152 * with the former StringPiece class, which is used by a lot of other
153 * code. This abstraction does fulfill the needs of boost's
154 * range-oriented algorithms though.
156 * (Keep memory lifetime in mind when using this class, since it
157 * doesn't manage the data it refers to - just like an iterator
160 template <class Iter>
161 class Range : private boost::totally_ordered<Range<Iter> > {
163 typedef std::size_t size_type;
164 typedef Iter iterator;
165 typedef Iter const_iterator;
166 typedef typename std::remove_reference<
167 typename std::iterator_traits<Iter>::reference>::type
169 typedef typename std::iterator_traits<Iter>::reference reference;
172 * For MutableStringPiece and MutableByteRange we define StringPiece
173 * and ByteRange as const_range_type (for everything else its just
174 * identity). We do that to enable operations such as find with
175 * args which are const.
177 typedef typename std::conditional<
178 std::is_same<Iter, char*>::value
179 || std::is_same<Iter, unsigned char*>::value,
180 Range<const value_type*>,
181 Range<Iter>>::type const_range_type;
183 typedef std::char_traits<typename std::remove_const<value_type>::type>
186 static const size_type npos;
188 // Works for all iterators
189 constexpr Range() : b_(), e_() {
192 constexpr Range(const Range&) = default;
193 constexpr Range(Range&&) = default;
196 // Works for all iterators
197 constexpr Range(Iter start, Iter end) : b_(start), e_(end) {
200 // Works only for random-access iterators
201 constexpr Range(Iter start, size_t size)
202 : b_(start), e_(start + size) { }
204 # if !defined(__clang__) || __clang_major__ > 3 || \
205 (__clang_major__ == 3 && __clang_minor__ > 6)
206 // Clang 3.6 crashes on this line
207 /* implicit */ Range(std::nullptr_t) = delete;
210 template <class T = Iter, typename detail::IsCharPointer<T>::type = 0>
211 constexpr /* implicit */ Range(Iter str)
212 : b_(str), e_(str + constexpr_strlen(str)) {}
214 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
215 /* implicit */ Range(const std::string& str)
216 : b_(str.data()), e_(b_ + str.size()) {}
218 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
219 Range(const std::string& str, std::string::size_type startFrom) {
220 if (UNLIKELY(startFrom > str.size())) {
221 throw std::out_of_range("index out of range");
223 b_ = str.data() + startFrom;
224 e_ = str.data() + str.size();
227 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
228 Range(const std::string& str,
229 std::string::size_type startFrom,
230 std::string::size_type size) {
231 if (UNLIKELY(startFrom > str.size())) {
232 throw std::out_of_range("index out of range");
234 b_ = str.data() + startFrom;
235 if (str.size() - startFrom < size) {
236 e_ = str.data() + str.size();
242 Range(const Range& other,
244 size_type length = npos)
245 : Range(other.subpiece(first, length))
248 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
249 /* implicit */ Range(const fbstring& str)
250 : b_(str.data()), e_(b_ + str.size()) { }
252 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
253 Range(const fbstring& str, fbstring::size_type startFrom) {
254 if (UNLIKELY(startFrom > str.size())) {
255 throw std::out_of_range("index out of range");
257 b_ = str.data() + startFrom;
258 e_ = str.data() + str.size();
261 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
262 Range(const fbstring& str, fbstring::size_type startFrom,
263 fbstring::size_type size) {
264 if (UNLIKELY(startFrom > str.size())) {
265 throw std::out_of_range("index out of range");
267 b_ = str.data() + startFrom;
268 if (str.size() - startFrom < size) {
269 e_ = str.data() + str.size();
275 // Allow implicit conversion from Range<const char*> (aka StringPiece) to
276 // Range<const unsigned char*> (aka ByteRange), as they're both frequently
277 // used to represent ranges of bytes. Allow explicit conversion in the other
279 template <class OtherIter, typename std::enable_if<
280 (std::is_same<Iter, const unsigned char*>::value &&
281 (std::is_same<OtherIter, const char*>::value ||
282 std::is_same<OtherIter, char*>::value)), int>::type = 0>
283 /* implicit */ Range(const Range<OtherIter>& other)
284 : b_(reinterpret_cast<const unsigned char*>(other.begin())),
285 e_(reinterpret_cast<const unsigned char*>(other.end())) {
288 template <class OtherIter, typename std::enable_if<
289 (std::is_same<Iter, unsigned char*>::value &&
290 std::is_same<OtherIter, char*>::value), int>::type = 0>
291 /* implicit */ Range(const Range<OtherIter>& other)
292 : b_(reinterpret_cast<unsigned char*>(other.begin())),
293 e_(reinterpret_cast<unsigned char*>(other.end())) {
296 template <class OtherIter, typename std::enable_if<
297 (std::is_same<Iter, const char*>::value &&
298 (std::is_same<OtherIter, const unsigned char*>::value ||
299 std::is_same<OtherIter, unsigned char*>::value)), int>::type = 0>
300 explicit Range(const Range<OtherIter>& other)
301 : b_(reinterpret_cast<const char*>(other.begin())),
302 e_(reinterpret_cast<const char*>(other.end())) {
305 template <class OtherIter, typename std::enable_if<
306 (std::is_same<Iter, char*>::value &&
307 std::is_same<OtherIter, unsigned char*>::value), int>::type = 0>
308 explicit Range(const Range<OtherIter>& other)
309 : b_(reinterpret_cast<char*>(other.begin())),
310 e_(reinterpret_cast<char*>(other.end())) {
313 // Allow implicit conversion from Range<From> to Range<To> if From is
314 // implicitly convertible to To.
315 template <class OtherIter, typename std::enable_if<
316 (!std::is_same<Iter, OtherIter>::value &&
317 std::is_convertible<OtherIter, Iter>::value), int>::type = 0>
318 constexpr /* implicit */ Range(const Range<OtherIter>& other)
323 // Allow explicit conversion from Range<From> to Range<To> if From is
324 // explicitly convertible to To.
325 template <class OtherIter, typename std::enable_if<
326 (!std::is_same<Iter, OtherIter>::value &&
327 !std::is_convertible<OtherIter, Iter>::value &&
328 std::is_constructible<Iter, const OtherIter&>::value), int>::type = 0>
329 constexpr explicit Range(const Range<OtherIter>& other)
334 Range& operator=(const Range& rhs) & = default;
335 Range& operator=(Range&& rhs) & = default;
342 void assign(Iter start, Iter end) {
347 void reset(Iter start, size_type size) {
352 // Works only for Range<const char*>
353 void reset(const std::string& str) {
354 reset(str.data(), str.size());
357 size_type size() const {
361 size_type walk_size() const {
363 return std::distance(b_, e_);
365 bool empty() const { return b_ == e_; }
366 Iter data() const { return b_; }
367 Iter start() const { return b_; }
368 Iter begin() const { return b_; }
369 Iter end() const { return e_; }
370 Iter cbegin() const { return b_; }
371 Iter cend() const { return e_; }
372 value_type& front() {
378 return detail::value_before(e_);
380 const value_type& front() const {
384 const value_type& back() const {
386 return detail::value_before(e_);
388 // Works only for Range<const char*> and Range<char*>
389 std::string str() const { return std::string(b_, size()); }
390 std::string toString() const { return str(); }
391 // Works only for Range<const char*> and Range<char*>
392 fbstring fbstr() const { return fbstring(b_, size()); }
393 fbstring toFbstring() const { return fbstr(); }
395 const_range_type castToConst() const {
396 return const_range_type(*this);
399 // Works only for Range<const char*> and Range<char*>
400 int compare(const const_range_type& o) const {
401 const size_type tsize = this->size();
402 const size_type osize = o.size();
403 const size_type msize = std::min(tsize, osize);
404 int r = traits_type::compare(data(), o.data(), msize);
405 if (r == 0 && tsize != osize) {
406 // We check the signed bit of the subtraction and bit shift it
407 // to produce either 0 or 2. The subtraction yields the
408 // comparison values of either -1 or 1.
409 r = (static_cast<int>(
410 (osize - tsize) >> (CHAR_BIT * sizeof(size_t) - 1)) << 1) - 1;
415 value_type& operator[](size_t i) {
416 DCHECK_GT(size(), i);
420 const value_type& operator[](size_t i) const {
421 DCHECK_GT(size(), i);
425 value_type& at(size_t i) {
426 if (i >= size()) throw std::out_of_range("index out of range");
430 const value_type& at(size_t i) const {
431 if (i >= size()) throw std::out_of_range("index out of range");
435 // Do NOT use this function, which was left behind for backwards
436 // compatibility. Use SpookyHashV2 instead -- it is faster, and produces
437 // a 64-bit hash, which means dramatically fewer collisions in large maps.
438 // (The above advice does not apply if you are targeting a 32-bit system.)
440 // Works only for Range<const char*> and Range<char*>
441 uint32_t hash() const {
442 // Taken from fbi/nstring.h:
443 // Quick and dirty bernstein hash...fine for short ascii strings
444 uint32_t hash = 5381;
445 for (size_t ix = 0; ix < size(); ix++) {
446 hash = ((hash << 5) + hash) + b_[ix];
451 void advance(size_type n) {
452 if (UNLIKELY(n > size())) {
453 throw std::out_of_range("index out of range");
458 void subtract(size_type n) {
459 if (UNLIKELY(n > size())) {
460 throw std::out_of_range("index out of range");
475 Range subpiece(size_type first, size_type length = npos) const {
476 if (UNLIKELY(first > size())) {
477 throw std::out_of_range("index out of range");
480 return Range(b_ + first, std::min(length, size() - first));
483 // string work-alike functions
484 size_type find(const_range_type str) const {
485 return qfind(castToConst(), str);
488 size_type find(const_range_type str, size_t pos) const {
489 if (pos > size()) return std::string::npos;
490 size_t ret = qfind(castToConst().subpiece(pos), str);
491 return ret == npos ? ret : ret + pos;
494 size_type find(Iter s, size_t pos, size_t n) const {
495 if (pos > size()) return std::string::npos;
496 auto forFinding = castToConst();
498 pos ? forFinding.subpiece(pos) : forFinding, const_range_type(s, n));
499 return ret == npos ? ret : ret + pos;
502 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
503 size_type find(const Iter s) const {
504 return qfind(castToConst(), const_range_type(s));
507 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
508 size_type find(const Iter s, size_t pos) const {
509 if (pos > size()) return std::string::npos;
510 size_type ret = qfind(castToConst().subpiece(pos), const_range_type(s));
511 return ret == npos ? ret : ret + pos;
514 size_type find(value_type c) const {
515 return qfind(castToConst(), c);
518 size_type rfind(value_type c) const {
519 return folly::rfind(castToConst(), c);
522 size_type find(value_type c, size_t pos) const {
523 if (pos > size()) return std::string::npos;
524 size_type ret = qfind(castToConst().subpiece(pos), c);
525 return ret == npos ? ret : ret + pos;
528 size_type find_first_of(const_range_type needles) const {
529 return qfind_first_of(castToConst(), needles);
532 size_type find_first_of(const_range_type needles, size_t pos) const {
533 if (pos > size()) return std::string::npos;
534 size_type ret = qfind_first_of(castToConst().subpiece(pos), needles);
535 return ret == npos ? ret : ret + pos;
538 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
539 size_type find_first_of(Iter needles) const {
540 return find_first_of(const_range_type(needles));
543 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
544 size_type find_first_of(Iter needles, size_t pos) const {
545 return find_first_of(const_range_type(needles), pos);
548 size_type find_first_of(Iter needles, size_t pos, size_t n) const {
549 return find_first_of(const_range_type(needles, n), pos);
552 size_type find_first_of(value_type c) const {
556 size_type find_first_of(value_type c, size_t pos) const {
561 * Determine whether the range contains the given subrange or item.
563 * Note: Call find() directly if the index is needed.
565 bool contains(const const_range_type& other) const {
566 return find(other) != std::string::npos;
569 bool contains(const value_type& other) const {
570 return find(other) != std::string::npos;
573 void swap(Range& rhs) {
574 std::swap(b_, rhs.b_);
575 std::swap(e_, rhs.e_);
579 * Does this Range start with another range?
581 bool startsWith(const const_range_type& other) const {
582 return size() >= other.size()
583 && castToConst().subpiece(0, other.size()) == other;
585 bool startsWith(value_type c) const {
586 return !empty() && front() == c;
590 * Does this Range end with another range?
592 bool endsWith(const const_range_type& other) const {
593 return size() >= other.size()
594 && castToConst().subpiece(size() - other.size()) == other;
596 bool endsWith(value_type c) const {
597 return !empty() && back() == c;
601 * Remove the given prefix and return true if the range starts with the given
602 * prefix; return false otherwise.
604 bool removePrefix(const const_range_type& prefix) {
605 return startsWith(prefix) && (b_ += prefix.size(), true);
607 bool removePrefix(value_type prefix) {
608 return startsWith(prefix) && (++b_, true);
612 * Remove the given suffix and return true if the range ends with the given
613 * suffix; return false otherwise.
615 bool removeSuffix(const const_range_type& suffix) {
616 return endsWith(suffix) && (e_ -= suffix.size(), true);
618 bool removeSuffix(value_type suffix) {
619 return endsWith(suffix) && (--e_, true);
623 * Replaces the content of the range, starting at position 'pos', with
624 * contents of 'replacement'. Entire 'replacement' must fit into the
625 * range. Returns false if 'replacements' does not fit. Example use:
627 * char in[] = "buffer";
628 * auto msp = MutablesStringPiece(input);
629 * EXPECT_TRUE(msp.replaceAt(2, "tt"));
630 * EXPECT_EQ(msp, "butter");
632 * // not enough space
633 * EXPECT_FALSE(msp.replace(msp.size() - 1, "rr"));
634 * EXPECT_EQ(msp, "butter"); // unchanged
636 bool replaceAt(size_t pos, const_range_type replacement) {
637 if (size() < pos + replacement.size()) {
641 std::copy(replacement.begin(), replacement.end(), begin() + pos);
647 * Replaces all occurences of 'source' with 'dest'. Returns number
648 * of replacements made. Source and dest have to have the same
649 * length. Throws if the lengths are different. If 'source' is a
650 * pattern that is overlapping with itself, we perform sequential
651 * replacement: "aaaaaaa".replaceAll("aa", "ba") --> "bababaa"
655 * char in[] = "buffer";
656 * auto msp = MutablesStringPiece(input);
657 * EXPECT_EQ(msp.replaceAll("ff","tt"), 1);
658 * EXPECT_EQ(msp, "butter");
660 size_t replaceAll(const_range_type source, const_range_type dest) {
661 if (source.size() != dest.size()) {
662 throw std::invalid_argument(
663 "replacement must have the same size as source");
671 size_t num_replaced = 0;
672 size_type found = std::string::npos;
673 while ((found = find(source, pos)) != std::string::npos) {
674 replaceAt(found, dest);
675 pos += source.size();
683 * Splits this `Range` `[b, e)` in the position `i` dictated by the next
684 * occurence of `delimiter`.
686 * Returns a new `Range` `[b, i)` and adjusts this range to start right after
687 * the delimiter's position. This range will be empty if the delimiter is not
688 * found. If called on an empty `Range`, both this and the returned `Range`
693 * folly::StringPiece s("sample string for split_next");
694 * auto p = s.split_step(' ');
696 * // prints "string for split_next"
704 * void tokenize(StringPiece s, char delimiter) {
705 * while (!s.empty()) {
706 * cout << s.split_step(delimiter);
710 * @author: Marcelo Juchem <marcelo@fb.com>
712 Range split_step(value_type delimiter) {
713 auto i = std::find(b_, e_, delimiter);
716 b_ = i == e_ ? e_ : std::next(i);
721 Range split_step(Range delimiter) {
722 auto i = find(delimiter);
723 Range result(b_, i == std::string::npos ? size() : i);
725 b_ = result.end() == e_ ? e_ : std::next(result.end(), delimiter.size());
731 * Convenience method that calls `split_step()` and passes the result to a
732 * functor, returning whatever the functor does. Any additional arguments
733 * `args` passed to this function are perfectly forwarded to the functor.
735 * Say you have a functor with this signature:
737 * Foo fn(Range r) { }
739 * `split_step()`'s return type will be `Foo`. It works just like:
741 * auto result = fn(myRange.split_step(' '));
743 * A functor returning `void` is also supported.
747 * void do_some_parsing(folly::StringPiece s) {
748 * auto version = s.split_step(' ', [&](folly::StringPiece x) {
750 * throw std::invalid_argument("empty string");
752 * return std::strtoull(x.begin(), x.end(), 16);
759 * void parse(folly::StringPiece s) {
760 * s.split_step(' ', parse_field, bar, 10);
761 * s.split_step('\t', parse_field, baz, 20);
763 * auto const kludge = [](folly::StringPiece x, int &out, int def) {
767 * parse_field(x, out, def);
771 * s.split_step('\t', kludge, gaz);
772 * s.split_step(' ', kludge, foo);
781 * static parse_field(folly::StringPiece s, int &out, int def) {
783 * out = folly::to<int>(s);
784 * } catch (std::exception const &) {
790 * @author: Marcelo Juchem <marcelo@fb.com>
792 template <typename TProcess, typename... Args>
793 auto split_step(value_type delimiter, TProcess &&process, Args &&...args)
794 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
795 { return process(split_step(delimiter), std::forward<Args>(args)...); }
797 template <typename TProcess, typename... Args>
798 auto split_step(Range delimiter, TProcess &&process, Args &&...args)
799 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
800 { return process(split_step(delimiter), std::forward<Args>(args)...); }
806 template <class Iter>
807 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
810 void swap(Range<T>& lhs, Range<T>& rhs) {
815 * Create a range from two iterators, with type deduction.
817 template <class Iter>
818 Range<Iter> range(Iter first, Iter last) {
819 return Range<Iter>(first, last);
823 * Creates a range to reference the contents of a contiguous-storage container.
825 // Use pointers for types with '.data()' member
826 template <class Collection,
827 class T = typename std::remove_pointer<
828 decltype(std::declval<Collection>().data())>::type>
829 Range<T*> range(Collection&& v) {
830 return Range<T*>(v.data(), v.data() + v.size());
833 template <class T, size_t n>
834 Range<T*> range(T (&array)[n]) {
835 return Range<T*>(array, array + n);
838 typedef Range<const char*> StringPiece;
839 typedef Range<char*> MutableStringPiece;
840 typedef Range<const unsigned char*> ByteRange;
841 typedef Range<unsigned char*> MutableByteRange;
843 inline std::ostream& operator<<(std::ostream& os,
844 const StringPiece piece) {
845 os.write(piece.start(), piece.size());
849 inline std::ostream& operator<<(std::ostream& os,
850 const MutableStringPiece piece) {
851 os.write(piece.start(), piece.size());
856 * Templated comparison operators
860 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
861 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
865 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
866 return lhs.compare(rhs) < 0;
870 * Specializations of comparison operators for StringPiece
875 template <class A, class B>
876 struct ComparableAsStringPiece {
879 (std::is_convertible<A, StringPiece>::value
880 && std::is_same<B, StringPiece>::value)
882 (std::is_convertible<B, StringPiece>::value
883 && std::is_same<A, StringPiece>::value)
887 } // namespace detail
890 * operator== through conversion for Range<const char*>
892 template <class T, class U>
894 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
895 operator==(const T& lhs, const U& rhs) {
896 return StringPiece(lhs) == StringPiece(rhs);
900 * operator< through conversion for Range<const char*>
902 template <class T, class U>
904 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
905 operator<(const T& lhs, const U& rhs) {
906 return StringPiece(lhs) < StringPiece(rhs);
910 * operator> through conversion for Range<const char*>
912 template <class T, class U>
914 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
915 operator>(const T& lhs, const U& rhs) {
916 return StringPiece(lhs) > StringPiece(rhs);
920 * operator< through conversion for Range<const char*>
922 template <class T, class U>
924 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
925 operator<=(const T& lhs, const U& rhs) {
926 return StringPiece(lhs) <= StringPiece(rhs);
930 * operator> through conversion for Range<const char*>
932 template <class T, class U>
934 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
935 operator>=(const T& lhs, const U& rhs) {
936 return StringPiece(lhs) >= StringPiece(rhs);
939 // Do NOT use this, use SpookyHashV2 instead, see commment on hash() above.
940 struct StringPieceHash {
941 std::size_t operator()(const StringPiece str) const {
942 return static_cast<std::size_t>(str.hash());
947 * Finds substrings faster than brute force by borrowing from Boyer-Moore
949 template <class T, class Comp>
950 size_t qfind(const Range<T>& haystack,
951 const Range<T>& needle,
953 // Don't use std::search, use a Boyer-Moore-like trick by comparing
954 // the last characters first
955 auto const nsize = needle.size();
956 if (haystack.size() < nsize) {
957 return std::string::npos;
959 if (!nsize) return 0;
960 auto const nsize_1 = nsize - 1;
961 auto const lastNeedle = needle[nsize_1];
963 // Boyer-Moore skip value for the last char in the needle. Zero is
964 // not a valid value; skip will be computed the first time it's
966 std::string::size_type skip = 0;
968 auto i = haystack.begin();
969 auto iEnd = haystack.end() - nsize_1;
972 // Boyer-Moore: match the last element in the needle
973 while (!eq(i[nsize_1], lastNeedle)) {
976 return std::string::npos;
979 // Here we know that the last char matches
980 // Continue in pedestrian mode
981 for (size_t j = 0; ; ) {
983 if (!eq(i[j], needle[j])) {
984 // Not found, we can skip
985 // Compute the skip value lazily
988 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
995 // Check if done searching
998 return i - haystack.begin();
1002 return std::string::npos;
1007 inline size_t qfind_first_byte_of(const StringPiece haystack,
1008 const StringPiece needles) {
1009 static auto const qfind_first_byte_of_fn =
1010 folly::CpuId().sse42() ? qfind_first_byte_of_sse42
1011 : qfind_first_byte_of_nosse;
1012 return qfind_first_byte_of_fn(haystack, needles);
1015 } // namespace detail
1017 template <class T, class Comp>
1018 size_t qfind_first_of(const Range<T> & haystack,
1019 const Range<T> & needles,
1021 auto ret = std::find_first_of(haystack.begin(), haystack.end(),
1022 needles.begin(), needles.end(),
1024 return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
1027 struct AsciiCaseSensitive {
1028 bool operator()(char lhs, char rhs) const {
1034 * Check if two ascii characters are case insensitive equal.
1035 * The difference between the lower/upper case characters are the 6-th bit.
1036 * We also check they are alpha chars, in case of xor = 32.
1038 struct AsciiCaseInsensitive {
1039 bool operator()(char lhs, char rhs) const {
1041 if (k == 0) return true;
1042 if (k != 32) return false;
1044 return (k >= 'a' && k <= 'z');
1049 size_t qfind(const Range<T>& haystack,
1050 const typename Range<T>::value_type& needle) {
1051 auto pos = std::find(haystack.begin(), haystack.end(), needle);
1052 return pos == haystack.end() ? std::string::npos : pos - haystack.data();
1056 size_t rfind(const Range<T>& haystack,
1057 const typename Range<T>::value_type& needle) {
1058 for (auto i = haystack.size(); i-- > 0; ) {
1059 if (haystack[i] == needle) {
1063 return std::string::npos;
1066 // specialization for StringPiece
1068 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
1069 auto pos = static_cast<const char*>(
1070 ::memchr(haystack.data(), needle, haystack.size()));
1071 return pos == nullptr ? std::string::npos : pos - haystack.data();
1074 #if FOLLY_HAVE_MEMRCHR
1076 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
1077 auto pos = static_cast<const char*>(
1078 ::memrchr(haystack.data(), needle, haystack.size()));
1079 return pos == nullptr ? std::string::npos : pos - haystack.data();
1083 // specialization for ByteRange
1085 inline size_t qfind(const Range<const unsigned char*>& haystack,
1086 const unsigned char& needle) {
1087 auto pos = static_cast<const unsigned char*>(
1088 ::memchr(haystack.data(), needle, haystack.size()));
1089 return pos == nullptr ? std::string::npos : pos - haystack.data();
1092 #if FOLLY_HAVE_MEMRCHR
1094 inline size_t rfind(const Range<const unsigned char*>& haystack,
1095 const unsigned char& needle) {
1096 auto pos = static_cast<const unsigned char*>(
1097 ::memrchr(haystack.data(), needle, haystack.size()));
1098 return pos == nullptr ? std::string::npos : pos - haystack.data();
1103 size_t qfind_first_of(const Range<T>& haystack,
1104 const Range<T>& needles) {
1105 return qfind_first_of(haystack, needles, AsciiCaseSensitive());
1108 // specialization for StringPiece
1110 inline size_t qfind_first_of(const Range<const char*>& haystack,
1111 const Range<const char*>& needles) {
1112 return detail::qfind_first_byte_of(haystack, needles);
1115 // specialization for ByteRange
1117 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
1118 const Range<const unsigned char*>& needles) {
1119 return detail::qfind_first_byte_of(StringPiece(haystack),
1120 StringPiece(needles));
1123 template<class Key, class Enable>
1127 struct hasher<folly::Range<T*>,
1128 typename std::enable_if<std::is_pod<T>::value, void>::type> {
1129 size_t operator()(folly::Range<T*> r) const {
1130 return hash::SpookyHashV2::Hash64(r.begin(), r.size() * sizeof(T), 0);
1134 } // !namespace folly
1136 #pragma GCC diagnostic pop
1138 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);
1140 #endif // FOLLY_RANGE_H_