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>
31 #include <glog/logging.h>
35 #include <type_traits>
37 // libc++ doesn't provide this header, nor does msvc
38 #ifdef FOLLY_HAVE_BITS_CXXCONFIG_H
39 // This file appears in two locations: inside fbcode and in the
40 // libstdc++ source code (when embedding fbstring as std::string).
41 // To aid in this schizophrenic use, two macros are defined in
43 // _LIBSTDCXX_FBSTRING - Set inside libstdc++. This is useful to
44 // gate use inside fbcode v. libstdc++
45 #include <bits/c++config.h>
48 #include <folly/CpuId.h>
49 #include <folly/Traits.h>
50 #include <folly/Likely.h>
51 #include <folly/detail/RangeCommon.h>
52 #include <folly/detail/RangeSse42.h>
54 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
55 #pragma GCC diagnostic push
56 #pragma GCC diagnostic ignored "-Wshadow"
60 template <class T> class Range;
63 * Finds the first occurrence of needle in haystack. The algorithm is on
64 * average faster than O(haystack.size() * needle.size()) but not as fast
65 * as Boyer-Moore. On the upside, it does not do any upfront
66 * preprocessing and does not allocate memory.
68 template <class T, class Comp = std::equal_to<typename Range<T>::value_type>>
69 inline size_t qfind(const Range<T> & haystack,
70 const Range<T> & needle,
74 * Finds the first occurrence of needle in haystack. The result is the
75 * offset reported to the beginning of haystack, or string::npos if
76 * needle wasn't found.
79 size_t qfind(const Range<T> & haystack,
80 const typename Range<T>::value_type& needle);
83 * Finds the last occurrence of needle in haystack. The result is the
84 * offset reported to the beginning of haystack, or string::npos if
85 * needle wasn't found.
88 size_t rfind(const Range<T> & haystack,
89 const typename Range<T>::value_type& needle);
93 * Finds the first occurrence of any element of needle in
94 * haystack. The algorithm is O(haystack.size() * needle.size()).
97 inline size_t qfind_first_of(const Range<T> & haystack,
98 const Range<T> & needle);
101 * Small internal helper - returns the value just before an iterator.
106 * For random-access iterators, the value before is simply i[-1].
108 template <class Iter>
109 typename std::enable_if<
110 std::is_same<typename std::iterator_traits<Iter>::iterator_category,
111 std::random_access_iterator_tag>::value,
112 typename std::iterator_traits<Iter>::reference>::type
113 value_before(Iter i) {
118 * For all other iterators, we need to use the decrement operator.
120 template <class Iter>
121 typename std::enable_if<
122 !std::is_same<typename std::iterator_traits<Iter>::iterator_category,
123 std::random_access_iterator_tag>::value,
124 typename std::iterator_traits<Iter>::reference>::type
125 value_before(Iter i) {
130 * Use IsCharPointer<T>::type to enable const char* or char*.
131 * Use IsCharPointer<T>::const_type to enable only const char*.
133 template <class T> struct IsCharPointer {};
136 struct IsCharPointer<char*> {
141 struct IsCharPointer<const char*> {
142 typedef int const_type;
146 } // namespace detail
149 * Range abstraction keeping a pair of iterators. We couldn't use
150 * boost's similar range abstraction because we need an API identical
151 * with the former StringPiece class, which is used by a lot of other
152 * code. This abstraction does fulfill the needs of boost's
153 * range-oriented algorithms though.
155 * (Keep memory lifetime in mind when using this class, since it
156 * doesn't manage the data it refers to - just like an iterator
159 template <class Iter>
160 class Range : private boost::totally_ordered<Range<Iter> > {
162 typedef std::size_t size_type;
163 typedef Iter iterator;
164 typedef Iter const_iterator;
165 typedef typename std::remove_reference<
166 typename std::iterator_traits<Iter>::reference>::type
168 typedef typename std::iterator_traits<Iter>::reference reference;
171 * For MutableStringPiece and MutableByteRange we define StringPiece
172 * and ByteRange as const_range_type (for everything else its just
173 * identity). We do that to enable operations such as find with
174 * args which are const.
176 typedef typename std::conditional<
177 std::is_same<Iter, char*>::value
178 || std::is_same<Iter, unsigned char*>::value,
179 Range<const value_type*>,
180 Range<Iter>>::type const_range_type;
182 typedef std::char_traits<typename std::remove_const<value_type>::type>
185 static const size_type npos;
187 // Works for all iterators
188 constexpr Range() : b_(), e_() {
191 constexpr Range(const Range&) = default;
192 constexpr Range(Range&&) = default;
195 // Works for all iterators
196 constexpr Range(Iter start, Iter end) : b_(start), e_(end) {
199 // Works only for random-access iterators
200 constexpr Range(Iter start, size_t size)
201 : b_(start), e_(start + size) { }
203 template <class T = Iter, typename detail::IsCharPointer<T>::type = 0>
204 constexpr /* implicit */ Range(Iter str)
205 : b_(str), e_(str + constexpr_strlen(str)) {}
207 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
208 /* implicit */ Range(const std::string& str)
209 : b_(str.data()), e_(b_ + str.size()) {}
211 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
212 Range(const std::string& str, std::string::size_type startFrom) {
213 if (UNLIKELY(startFrom > str.size())) {
214 throw std::out_of_range("index out of range");
216 b_ = str.data() + startFrom;
217 e_ = str.data() + str.size();
220 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
221 Range(const std::string& str,
222 std::string::size_type startFrom,
223 std::string::size_type size) {
224 if (UNLIKELY(startFrom > str.size())) {
225 throw std::out_of_range("index out of range");
227 b_ = str.data() + startFrom;
228 if (str.size() - startFrom < size) {
229 e_ = str.data() + str.size();
235 Range(const Range& other,
237 size_type length = npos)
238 : Range(other.subpiece(first, length))
241 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
242 /* implicit */ Range(const fbstring& str)
243 : b_(str.data()), e_(b_ + str.size()) { }
245 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
246 Range(const fbstring& str, fbstring::size_type startFrom) {
247 if (UNLIKELY(startFrom > str.size())) {
248 throw std::out_of_range("index out of range");
250 b_ = str.data() + startFrom;
251 e_ = str.data() + str.size();
254 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
255 Range(const fbstring& str, fbstring::size_type startFrom,
256 fbstring::size_type size) {
257 if (UNLIKELY(startFrom > str.size())) {
258 throw std::out_of_range("index out of range");
260 b_ = str.data() + startFrom;
261 if (str.size() - startFrom < size) {
262 e_ = str.data() + str.size();
268 // Allow implicit conversion from Range<const char*> (aka StringPiece) to
269 // Range<const unsigned char*> (aka ByteRange), as they're both frequently
270 // used to represent ranges of bytes. Allow explicit conversion in the other
272 template <class OtherIter, typename std::enable_if<
273 (std::is_same<Iter, const unsigned char*>::value &&
274 (std::is_same<OtherIter, const char*>::value ||
275 std::is_same<OtherIter, char*>::value)), int>::type = 0>
276 /* implicit */ Range(const Range<OtherIter>& other)
277 : b_(reinterpret_cast<const unsigned char*>(other.begin())),
278 e_(reinterpret_cast<const unsigned char*>(other.end())) {
281 template <class OtherIter, typename std::enable_if<
282 (std::is_same<Iter, unsigned char*>::value &&
283 std::is_same<OtherIter, char*>::value), int>::type = 0>
284 /* implicit */ Range(const Range<OtherIter>& other)
285 : b_(reinterpret_cast<unsigned char*>(other.begin())),
286 e_(reinterpret_cast<unsigned char*>(other.end())) {
289 template <class OtherIter, typename std::enable_if<
290 (std::is_same<Iter, const char*>::value &&
291 (std::is_same<OtherIter, const unsigned char*>::value ||
292 std::is_same<OtherIter, unsigned char*>::value)), int>::type = 0>
293 explicit Range(const Range<OtherIter>& other)
294 : b_(reinterpret_cast<const char*>(other.begin())),
295 e_(reinterpret_cast<const char*>(other.end())) {
298 template <class OtherIter, typename std::enable_if<
299 (std::is_same<Iter, char*>::value &&
300 std::is_same<OtherIter, unsigned char*>::value), int>::type = 0>
301 explicit Range(const Range<OtherIter>& other)
302 : b_(reinterpret_cast<char*>(other.begin())),
303 e_(reinterpret_cast<char*>(other.end())) {
306 // Allow implicit conversion from Range<From> to Range<To> if From is
307 // implicitly convertible to To.
308 template <class OtherIter, typename std::enable_if<
309 (!std::is_same<Iter, OtherIter>::value &&
310 std::is_convertible<OtherIter, Iter>::value), int>::type = 0>
311 constexpr /* implicit */ Range(const Range<OtherIter>& other)
316 // Allow explicit conversion from Range<From> to Range<To> if From is
317 // explicitly convertible to To.
318 template <class OtherIter, typename std::enable_if<
319 (!std::is_same<Iter, OtherIter>::value &&
320 !std::is_convertible<OtherIter, Iter>::value &&
321 std::is_constructible<Iter, const OtherIter&>::value), int>::type = 0>
322 constexpr explicit Range(const Range<OtherIter>& other)
327 Range& operator=(const Range& rhs) & = default;
328 Range& operator=(Range&& rhs) & = default;
335 void assign(Iter start, Iter end) {
340 void reset(Iter start, size_type size) {
345 // Works only for Range<const char*>
346 void reset(const std::string& str) {
347 reset(str.data(), str.size());
350 size_type size() const {
354 size_type walk_size() const {
356 return std::distance(b_, e_);
358 bool empty() const { return b_ == e_; }
359 Iter data() const { return b_; }
360 Iter start() const { return b_; }
361 Iter begin() const { return b_; }
362 Iter end() const { return e_; }
363 Iter cbegin() const { return b_; }
364 Iter cend() const { return e_; }
365 value_type& front() {
371 return detail::value_before(e_);
373 const value_type& front() const {
377 const value_type& back() const {
379 return detail::value_before(e_);
381 // Works only for Range<const char*> and Range<char*>
382 std::string str() const { return std::string(b_, size()); }
383 std::string toString() const { return str(); }
384 // Works only for Range<const char*> and Range<char*>
385 fbstring fbstr() const { return fbstring(b_, size()); }
386 fbstring toFbstring() const { return fbstr(); }
388 const_range_type castToConst() const {
389 return const_range_type(*this);
392 // Works only for Range<const char*> and Range<char*>
393 int compare(const const_range_type& o) const {
394 const size_type tsize = this->size();
395 const size_type osize = o.size();
396 const size_type msize = std::min(tsize, osize);
397 int r = traits_type::compare(data(), o.data(), msize);
398 if (r == 0 && tsize != osize) {
399 // We check the signed bit of the subtraction and bit shift it
400 // to produce either 0 or 2. The subtraction yields the
401 // comparison values of either -1 or 1.
402 r = (static_cast<int>(
403 (osize - tsize) >> (CHAR_BIT * sizeof(size_t) - 1)) << 1) - 1;
408 value_type& operator[](size_t i) {
409 DCHECK_GT(size(), i);
413 const value_type& operator[](size_t i) const {
414 DCHECK_GT(size(), i);
418 value_type& at(size_t i) {
419 if (i >= size()) throw std::out_of_range("index out of range");
423 const value_type& at(size_t i) const {
424 if (i >= size()) throw std::out_of_range("index out of range");
428 // Do NOT use this function, which was left behind for backwards
429 // compatibility. Use SpookyHashV2 instead -- it is faster, and produces
430 // a 64-bit hash, which means dramatically fewer collisions in large maps.
431 // (The above advice does not apply if you are targeting a 32-bit system.)
433 // Works only for Range<const char*> and Range<char*>
434 uint32_t hash() const {
435 // Taken from fbi/nstring.h:
436 // Quick and dirty bernstein hash...fine for short ascii strings
437 uint32_t hash = 5381;
438 for (size_t ix = 0; ix < size(); ix++) {
439 hash = ((hash << 5) + hash) + b_[ix];
444 void advance(size_type n) {
445 if (UNLIKELY(n > size())) {
446 throw std::out_of_range("index out of range");
451 void subtract(size_type n) {
452 if (UNLIKELY(n > size())) {
453 throw std::out_of_range("index out of range");
468 Range subpiece(size_type first, size_type length = npos) const {
469 if (UNLIKELY(first > size())) {
470 throw std::out_of_range("index out of range");
473 return Range(b_ + first, std::min(length, size() - first));
476 // string work-alike functions
477 size_type find(const_range_type str) const {
478 return qfind(castToConst(), str);
481 size_type find(const_range_type str, size_t pos) const {
482 if (pos > size()) return std::string::npos;
483 size_t ret = qfind(castToConst().subpiece(pos), str);
484 return ret == npos ? ret : ret + pos;
487 size_type find(Iter s, size_t pos, size_t n) const {
488 if (pos > size()) return std::string::npos;
489 auto forFinding = castToConst();
491 pos ? forFinding.subpiece(pos) : forFinding, const_range_type(s, n));
492 return ret == npos ? ret : ret + pos;
495 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
496 size_type find(const Iter s) const {
497 return qfind(castToConst(), const_range_type(s));
500 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
501 size_type find(const Iter s, size_t pos) const {
502 if (pos > size()) return std::string::npos;
503 size_type ret = qfind(castToConst().subpiece(pos), const_range_type(s));
504 return ret == npos ? ret : ret + pos;
507 size_type find(value_type c) const {
508 return qfind(castToConst(), c);
511 size_type rfind(value_type c) const {
512 return folly::rfind(castToConst(), c);
515 size_type find(value_type c, size_t pos) const {
516 if (pos > size()) return std::string::npos;
517 size_type ret = qfind(castToConst().subpiece(pos), c);
518 return ret == npos ? ret : ret + pos;
521 size_type find_first_of(const_range_type needles) const {
522 return qfind_first_of(castToConst(), needles);
525 size_type find_first_of(const_range_type needles, size_t pos) const {
526 if (pos > size()) return std::string::npos;
527 size_type ret = qfind_first_of(castToConst().subpiece(pos), needles);
528 return ret == npos ? ret : ret + pos;
531 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
532 size_type find_first_of(Iter needles) const {
533 return find_first_of(const_range_type(needles));
536 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
537 size_type find_first_of(Iter needles, size_t pos) const {
538 return find_first_of(const_range_type(needles), pos);
541 size_type find_first_of(Iter needles, size_t pos, size_t n) const {
542 return find_first_of(const_range_type(needles, n), pos);
545 size_type find_first_of(value_type c) const {
549 size_type find_first_of(value_type c, size_t pos) const {
554 * Determine whether the range contains the given subrange or item.
556 * Note: Call find() directly if the index is needed.
558 bool contains(const const_range_type& other) const {
559 return find(other) != std::string::npos;
562 bool contains(const value_type& other) const {
563 return find(other) != std::string::npos;
566 void swap(Range& rhs) {
567 std::swap(b_, rhs.b_);
568 std::swap(e_, rhs.e_);
572 * Does this Range start with another range?
574 bool startsWith(const const_range_type& other) const {
575 return size() >= other.size()
576 && castToConst().subpiece(0, other.size()) == other;
578 bool startsWith(value_type c) const {
579 return !empty() && front() == c;
583 * Does this Range end with another range?
585 bool endsWith(const const_range_type& other) const {
586 return size() >= other.size()
587 && castToConst().subpiece(size() - other.size()) == other;
589 bool endsWith(value_type c) const {
590 return !empty() && back() == c;
594 * Remove the given prefix and return true if the range starts with the given
595 * prefix; return false otherwise.
597 bool removePrefix(const const_range_type& prefix) {
598 return startsWith(prefix) && (b_ += prefix.size(), true);
600 bool removePrefix(value_type prefix) {
601 return startsWith(prefix) && (++b_, true);
605 * Remove the given suffix and return true if the range ends with the given
606 * suffix; return false otherwise.
608 bool removeSuffix(const const_range_type& suffix) {
609 return endsWith(suffix) && (e_ -= suffix.size(), true);
611 bool removeSuffix(value_type suffix) {
612 return endsWith(suffix) && (--e_, true);
616 * Replaces the content of the range, starting at position 'pos', with
617 * contents of 'replacement'. Entire 'replacement' must fit into the
618 * range. Returns false if 'replacements' does not fit. Example use:
620 * char in[] = "buffer";
621 * auto msp = MutablesStringPiece(input);
622 * EXPECT_TRUE(msp.replaceAt(2, "tt"));
623 * EXPECT_EQ(msp, "butter");
625 * // not enough space
626 * EXPECT_FALSE(msp.replace(msp.size() - 1, "rr"));
627 * EXPECT_EQ(msp, "butter"); // unchanged
629 bool replaceAt(size_t pos, const_range_type replacement) {
630 if (size() < pos + replacement.size()) {
634 std::copy(replacement.begin(), replacement.end(), begin() + pos);
640 * Replaces all occurences of 'source' with 'dest'. Returns number
641 * of replacements made. Source and dest have to have the same
642 * length. Throws if the lengths are different. If 'source' is a
643 * pattern that is overlapping with itself, we perform sequential
644 * replacement: "aaaaaaa".replaceAll("aa", "ba") --> "bababaa"
648 * char in[] = "buffer";
649 * auto msp = MutablesStringPiece(input);
650 * EXPECT_EQ(msp.replaceAll("ff","tt"), 1);
651 * EXPECT_EQ(msp, "butter");
653 size_t replaceAll(const_range_type source, const_range_type dest) {
654 if (source.size() != dest.size()) {
655 throw std::invalid_argument(
656 "replacement must have the same size as source");
664 size_t num_replaced = 0;
665 size_type found = std::string::npos;
666 while ((found = find(source, pos)) != std::string::npos) {
667 replaceAt(found, dest);
668 pos += source.size();
676 * Splits this `Range` `[b, e)` in the position `i` dictated by the next
677 * occurence of `delimiter`.
679 * Returns a new `Range` `[b, i)` and adjusts this range to start right after
680 * the delimiter's position. This range will be empty if the delimiter is not
681 * found. If called on an empty `Range`, both this and the returned `Range`
686 * folly::StringPiece s("sample string for split_next");
687 * auto p = s.split_step(' ');
689 * // prints "string for split_next"
697 * void tokenize(StringPiece s, char delimiter) {
698 * while (!s.empty()) {
699 * cout << s.split_step(delimiter);
703 * @author: Marcelo Juchem <marcelo@fb.com>
705 Range split_step(value_type delimiter) {
706 auto i = std::find(b_, e_, delimiter);
709 b_ = i == e_ ? e_ : std::next(i);
714 Range split_step(Range delimiter) {
715 auto i = find(delimiter);
716 Range result(b_, i == std::string::npos ? size() : i);
718 b_ = result.end() == e_ ? e_ : std::next(result.end(), delimiter.size());
724 * Convenience method that calls `split_step()` and passes the result to a
725 * functor, returning whatever the functor does. Any additional arguments
726 * `args` passed to this function are perfectly forwarded to the functor.
728 * Say you have a functor with this signature:
730 * Foo fn(Range r) { }
732 * `split_step()`'s return type will be `Foo`. It works just like:
734 * auto result = fn(myRange.split_step(' '));
736 * A functor returning `void` is also supported.
740 * void do_some_parsing(folly::StringPiece s) {
741 * auto version = s.split_step(' ', [&](folly::StringPiece x) {
743 * throw std::invalid_argument("empty string");
745 * return std::strtoull(x.begin(), x.end(), 16);
752 * void parse(folly::StringPiece s) {
753 * s.split_step(' ', parse_field, bar, 10);
754 * s.split_step('\t', parse_field, baz, 20);
756 * auto const kludge = [](folly::StringPiece x, int &out, int def) {
760 * parse_field(x, out, def);
764 * s.split_step('\t', kludge, gaz);
765 * s.split_step(' ', kludge, foo);
774 * static parse_field(folly::StringPiece s, int &out, int def) {
776 * out = folly::to<int>(s);
777 * } catch (std::exception const &) {
783 * @author: Marcelo Juchem <marcelo@fb.com>
785 template <typename TProcess, typename... Args>
786 auto split_step(value_type delimiter, TProcess &&process, Args &&...args)
787 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
788 { return process(split_step(delimiter), std::forward<Args>(args)...); }
790 template <typename TProcess, typename... Args>
791 auto split_step(Range delimiter, TProcess &&process, Args &&...args)
792 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
793 { return process(split_step(delimiter), std::forward<Args>(args)...); }
799 template <class Iter>
800 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
803 void swap(Range<T>& lhs, Range<T>& rhs) {
808 * Create a range from two iterators, with type deduction.
810 template <class Iter>
811 Range<Iter> range(Iter first, Iter last) {
812 return Range<Iter>(first, last);
816 * Creates a range to reference the contents of a contiguous-storage container.
818 // Use pointers for types with '.data()' member
819 template <class Collection,
820 class T = typename std::remove_pointer<
821 decltype(std::declval<Collection>().data())>::type>
822 Range<T*> range(Collection&& v) {
823 return Range<T*>(v.data(), v.data() + v.size());
826 template <class T, size_t n>
827 Range<T*> range(T (&array)[n]) {
828 return Range<T*>(array, array + n);
831 typedef Range<const char*> StringPiece;
832 typedef Range<char*> MutableStringPiece;
833 typedef Range<const unsigned char*> ByteRange;
834 typedef Range<unsigned char*> MutableByteRange;
836 inline std::ostream& operator<<(std::ostream& os,
837 const StringPiece piece) {
838 os.write(piece.start(), piece.size());
842 inline std::ostream& operator<<(std::ostream& os,
843 const MutableStringPiece piece) {
844 os.write(piece.start(), piece.size());
849 * Templated comparison operators
853 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
854 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
858 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
859 return lhs.compare(rhs) < 0;
863 * Specializations of comparison operators for StringPiece
868 template <class A, class B>
869 struct ComparableAsStringPiece {
872 (std::is_convertible<A, StringPiece>::value
873 && std::is_same<B, StringPiece>::value)
875 (std::is_convertible<B, StringPiece>::value
876 && std::is_same<A, StringPiece>::value)
880 } // namespace detail
883 * operator== through conversion for Range<const char*>
885 template <class T, class U>
887 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
888 operator==(const T& lhs, const U& rhs) {
889 return StringPiece(lhs) == StringPiece(rhs);
893 * operator< through conversion for Range<const char*>
895 template <class T, class U>
897 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
898 operator<(const T& lhs, const U& rhs) {
899 return StringPiece(lhs) < StringPiece(rhs);
903 * operator> through conversion for Range<const char*>
905 template <class T, class U>
907 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
908 operator>(const T& lhs, const U& rhs) {
909 return StringPiece(lhs) > StringPiece(rhs);
913 * operator< through conversion for Range<const char*>
915 template <class T, class U>
917 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
918 operator<=(const T& lhs, const U& rhs) {
919 return StringPiece(lhs) <= StringPiece(rhs);
923 * operator> through conversion for Range<const char*>
925 template <class T, class U>
927 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
928 operator>=(const T& lhs, const U& rhs) {
929 return StringPiece(lhs) >= StringPiece(rhs);
932 // Do NOT use this, use SpookyHashV2 instead, see commment on hash() above.
933 struct StringPieceHash {
934 std::size_t operator()(const StringPiece str) const {
935 return static_cast<std::size_t>(str.hash());
940 * Finds substrings faster than brute force by borrowing from Boyer-Moore
942 template <class T, class Comp>
943 size_t qfind(const Range<T>& haystack,
944 const Range<T>& needle,
946 // Don't use std::search, use a Boyer-Moore-like trick by comparing
947 // the last characters first
948 auto const nsize = needle.size();
949 if (haystack.size() < nsize) {
950 return std::string::npos;
952 if (!nsize) return 0;
953 auto const nsize_1 = nsize - 1;
954 auto const lastNeedle = needle[nsize_1];
956 // Boyer-Moore skip value for the last char in the needle. Zero is
957 // not a valid value; skip will be computed the first time it's
959 std::string::size_type skip = 0;
961 auto i = haystack.begin();
962 auto iEnd = haystack.end() - nsize_1;
965 // Boyer-Moore: match the last element in the needle
966 while (!eq(i[nsize_1], lastNeedle)) {
969 return std::string::npos;
972 // Here we know that the last char matches
973 // Continue in pedestrian mode
974 for (size_t j = 0; ; ) {
976 if (!eq(i[j], needle[j])) {
977 // Not found, we can skip
978 // Compute the skip value lazily
981 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
988 // Check if done searching
991 return i - haystack.begin();
995 return std::string::npos;
1000 inline size_t qfind_first_byte_of(const StringPiece haystack,
1001 const StringPiece needles) {
1002 static auto const qfind_first_byte_of_fn =
1003 folly::CpuId().sse42() ? qfind_first_byte_of_sse42
1004 : qfind_first_byte_of_nosse;
1005 return qfind_first_byte_of_fn(haystack, needles);
1008 } // namespace detail
1010 template <class T, class Comp>
1011 size_t qfind_first_of(const Range<T> & haystack,
1012 const Range<T> & needles,
1014 auto ret = std::find_first_of(haystack.begin(), haystack.end(),
1015 needles.begin(), needles.end(),
1017 return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
1020 struct AsciiCaseSensitive {
1021 bool operator()(char lhs, char rhs) const {
1027 * Check if two ascii characters are case insensitive equal.
1028 * The difference between the lower/upper case characters are the 6-th bit.
1029 * We also check they are alpha chars, in case of xor = 32.
1031 struct AsciiCaseInsensitive {
1032 bool operator()(char lhs, char rhs) const {
1034 if (k == 0) return true;
1035 if (k != 32) return false;
1037 return (k >= 'a' && k <= 'z');
1042 size_t qfind(const Range<T>& haystack,
1043 const typename Range<T>::value_type& needle) {
1044 auto pos = std::find(haystack.begin(), haystack.end(), needle);
1045 return pos == haystack.end() ? std::string::npos : pos - haystack.data();
1049 size_t rfind(const Range<T>& haystack,
1050 const typename Range<T>::value_type& needle) {
1051 for (auto i = haystack.size(); i-- > 0; ) {
1052 if (haystack[i] == needle) {
1056 return std::string::npos;
1059 // specialization for StringPiece
1061 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
1062 auto pos = static_cast<const char*>(
1063 ::memchr(haystack.data(), needle, haystack.size()));
1064 return pos == nullptr ? std::string::npos : pos - haystack.data();
1067 #if FOLLY_HAVE_MEMRCHR
1069 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
1070 auto pos = static_cast<const char*>(
1071 ::memrchr(haystack.data(), needle, haystack.size()));
1072 return pos == nullptr ? std::string::npos : pos - haystack.data();
1076 // specialization for ByteRange
1078 inline size_t qfind(const Range<const unsigned char*>& haystack,
1079 const unsigned char& needle) {
1080 auto pos = static_cast<const unsigned char*>(
1081 ::memchr(haystack.data(), needle, haystack.size()));
1082 return pos == nullptr ? std::string::npos : pos - haystack.data();
1085 #if FOLLY_HAVE_MEMRCHR
1087 inline size_t rfind(const Range<const unsigned char*>& haystack,
1088 const unsigned char& needle) {
1089 auto pos = static_cast<const unsigned char*>(
1090 ::memrchr(haystack.data(), needle, haystack.size()));
1091 return pos == nullptr ? std::string::npos : pos - haystack.data();
1096 size_t qfind_first_of(const Range<T>& haystack,
1097 const Range<T>& needles) {
1098 return qfind_first_of(haystack, needles, AsciiCaseSensitive());
1101 // specialization for StringPiece
1103 inline size_t qfind_first_of(const Range<const char*>& haystack,
1104 const Range<const char*>& needles) {
1105 return detail::qfind_first_byte_of(haystack, needles);
1108 // specialization for ByteRange
1110 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
1111 const Range<const unsigned char*>& needles) {
1112 return detail::qfind_first_byte_of(StringPiece(haystack),
1113 StringPiece(needles));
1116 template<class Key, class Enable>
1120 struct hasher<folly::Range<T*>,
1121 typename std::enable_if<std::is_pod<T>::value, void>::type> {
1122 size_t operator()(folly::Range<T*> r) const {
1123 return hash::SpookyHashV2::Hash64(r.begin(), r.size() * sizeof(T), 0);
1127 } // !namespace folly
1129 #pragma GCC diagnostic pop
1131 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);
1133 #endif // FOLLY_RANGE_H_