2 * Copyright 2016 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 <folly/Portability.h>
25 #include <folly/SpookyHashV2.h>
26 #include <folly/portability/Constexpr.h>
27 #include <folly/portability/String.h>
30 #include <boost/operators.hpp>
34 #include <glog/logging.h>
38 #include <type_traits>
40 // libc++ doesn't provide this header, nor does msvc
41 #ifdef FOLLY_HAVE_BITS_CXXCONFIG_H
42 // This file appears in two locations: inside fbcode and in the
43 // libstdc++ source code (when embedding fbstring as std::string).
44 // To aid in this schizophrenic use, two macros are defined in
46 // _LIBSTDCXX_FBSTRING - Set inside libstdc++. This is useful to
47 // gate use inside fbcode v. libstdc++
48 #include <bits/c++config.h>
51 #include <folly/CpuId.h>
52 #include <folly/Traits.h>
53 #include <folly/Likely.h>
54 #include <folly/detail/RangeCommon.h>
55 #include <folly/detail/RangeSse42.h>
57 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
58 #pragma GCC diagnostic push
59 #pragma GCC diagnostic ignored "-Wshadow"
63 template <class T> class Range;
66 * Finds the first occurrence of needle in haystack. The algorithm is on
67 * average faster than O(haystack.size() * needle.size()) but not as fast
68 * as Boyer-Moore. On the upside, it does not do any upfront
69 * preprocessing and does not allocate memory.
71 template <class T, class Comp = std::equal_to<typename Range<T>::value_type>>
72 inline size_t qfind(const Range<T> & haystack,
73 const Range<T> & needle,
77 * Finds the first occurrence of needle in haystack. The result is the
78 * offset reported to the beginning of haystack, or string::npos if
79 * needle wasn't found.
82 size_t qfind(const Range<T> & haystack,
83 const typename Range<T>::value_type& needle);
86 * Finds the last occurrence of needle in haystack. The result is the
87 * offset reported to the beginning of haystack, or string::npos if
88 * needle wasn't found.
91 size_t rfind(const Range<T> & haystack,
92 const typename Range<T>::value_type& needle);
96 * Finds the first occurrence of any element of needle in
97 * haystack. The algorithm is O(haystack.size() * needle.size()).
100 inline size_t qfind_first_of(const Range<T> & haystack,
101 const Range<T> & needle);
104 * Small internal helper - returns the value just before an iterator.
109 * For random-access iterators, the value before is simply i[-1].
111 template <class Iter>
112 typename std::enable_if<
113 std::is_same<typename std::iterator_traits<Iter>::iterator_category,
114 std::random_access_iterator_tag>::value,
115 typename std::iterator_traits<Iter>::reference>::type
116 value_before(Iter i) {
121 * For all other iterators, we need to use the decrement operator.
123 template <class Iter>
124 typename std::enable_if<
125 !std::is_same<typename std::iterator_traits<Iter>::iterator_category,
126 std::random_access_iterator_tag>::value,
127 typename std::iterator_traits<Iter>::reference>::type
128 value_before(Iter i) {
133 * Use IsCharPointer<T>::type to enable const char* or char*.
134 * Use IsCharPointer<T>::const_type to enable only const char*.
136 template <class T> struct IsCharPointer {};
139 struct IsCharPointer<char*> {
144 struct IsCharPointer<const char*> {
145 typedef int const_type;
149 } // namespace detail
152 * Range abstraction keeping a pair of iterators. We couldn't use
153 * boost's similar range abstraction because we need an API identical
154 * with the former StringPiece class, which is used by a lot of other
155 * code. This abstraction does fulfill the needs of boost's
156 * range-oriented algorithms though.
158 * (Keep memory lifetime in mind when using this class, since it
159 * doesn't manage the data it refers to - just like an iterator
162 template <class Iter>
163 class Range : private boost::totally_ordered<Range<Iter> > {
165 typedef std::size_t size_type;
166 typedef Iter iterator;
167 typedef Iter const_iterator;
168 typedef typename std::remove_reference<
169 typename std::iterator_traits<Iter>::reference>::type
171 typedef typename std::iterator_traits<Iter>::reference reference;
174 * For MutableStringPiece and MutableByteRange we define StringPiece
175 * and ByteRange as const_range_type (for everything else its just
176 * identity). We do that to enable operations such as find with
177 * args which are const.
179 typedef typename std::conditional<
180 std::is_same<Iter, char*>::value
181 || std::is_same<Iter, unsigned char*>::value,
182 Range<const value_type*>,
183 Range<Iter>>::type const_range_type;
185 typedef std::char_traits<typename std::remove_const<value_type>::type>
188 static const size_type npos;
190 // Works for all iterators
191 constexpr Range() : b_(), e_() {
194 constexpr Range(const Range&) = default;
195 constexpr Range(Range&&) = default;
198 // Works for all iterators
199 constexpr Range(Iter start, Iter end) : b_(start), e_(end) {
202 // Works only for random-access iterators
203 constexpr Range(Iter start, size_t size)
204 : b_(start), e_(start + size) { }
206 # if !__clang__ || __CLANG_PREREQ(3, 7) // 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 {
362 return std::distance(b_, e_);
364 bool empty() const { return b_ == e_; }
365 Iter data() const { return b_; }
366 Iter start() const { return b_; }
367 Iter begin() const { return b_; }
368 Iter end() const { return e_; }
369 Iter cbegin() const { return b_; }
370 Iter cend() const { return e_; }
371 value_type& front() {
377 return detail::value_before(e_);
379 const value_type& front() const {
383 const value_type& back() const {
385 return detail::value_before(e_);
387 // Works only for Range<const char*> and Range<char*>
388 std::string str() const { return std::string(b_, size()); }
389 std::string toString() const { return str(); }
390 // Works only for Range<const char*> and Range<char*>
391 fbstring fbstr() const { return fbstring(b_, size()); }
392 fbstring toFbstring() const { return fbstr(); }
394 const_range_type castToConst() const {
395 return const_range_type(*this);
398 // Works only for Range<const char*> and Range<char*>
399 int compare(const const_range_type& o) const {
400 const size_type tsize = this->size();
401 const size_type osize = o.size();
402 const size_type msize = std::min(tsize, osize);
403 int r = traits_type::compare(data(), o.data(), msize);
404 if (r == 0 && tsize != osize) {
405 // We check the signed bit of the subtraction and bit shift it
406 // to produce either 0 or 2. The subtraction yields the
407 // comparison values of either -1 or 1.
408 r = (static_cast<int>(
409 (osize - tsize) >> (CHAR_BIT * sizeof(size_t) - 1)) << 1) - 1;
414 value_type& operator[](size_t i) {
415 DCHECK_GT(size(), i);
419 const value_type& operator[](size_t i) const {
420 DCHECK_GT(size(), i);
424 value_type& at(size_t i) {
425 if (i >= size()) throw std::out_of_range("index out of range");
429 const value_type& at(size_t i) const {
430 if (i >= size()) throw std::out_of_range("index out of range");
434 // Do NOT use this function, which was left behind for backwards
435 // compatibility. Use SpookyHashV2 instead -- it is faster, and produces
436 // a 64-bit hash, which means dramatically fewer collisions in large maps.
437 // (The above advice does not apply if you are targeting a 32-bit system.)
439 // Works only for Range<const char*> and Range<char*>
440 uint32_t hash() const {
441 // Taken from fbi/nstring.h:
442 // Quick and dirty bernstein hash...fine for short ascii strings
443 uint32_t hash = 5381;
444 for (size_t ix = 0; ix < size(); ix++) {
445 hash = ((hash << 5) + hash) + b_[ix];
450 void advance(size_type n) {
451 if (UNLIKELY(n > size())) {
452 throw std::out_of_range("index out of range");
457 void subtract(size_type n) {
458 if (UNLIKELY(n > size())) {
459 throw std::out_of_range("index out of range");
474 Range subpiece(size_type first, size_type length = npos) const {
475 if (UNLIKELY(first > size())) {
476 throw std::out_of_range("index out of range");
479 return Range(b_ + first, std::min(length, size() - first));
482 // string work-alike functions
483 size_type find(const_range_type str) const {
484 return qfind(castToConst(), str);
487 size_type find(const_range_type str, size_t pos) const {
488 if (pos > size()) return std::string::npos;
489 size_t ret = qfind(castToConst().subpiece(pos), str);
490 return ret == npos ? ret : ret + pos;
493 size_type find(Iter s, size_t pos, size_t n) const {
494 if (pos > size()) return std::string::npos;
495 auto forFinding = castToConst();
497 pos ? forFinding.subpiece(pos) : forFinding, const_range_type(s, n));
498 return ret == npos ? ret : ret + pos;
501 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
502 size_type find(const Iter s) const {
503 return qfind(castToConst(), const_range_type(s));
506 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
507 size_type find(const Iter s, size_t pos) const {
508 if (pos > size()) return std::string::npos;
509 size_type ret = qfind(castToConst().subpiece(pos), const_range_type(s));
510 return ret == npos ? ret : ret + pos;
513 size_type find(value_type c) const {
514 return qfind(castToConst(), c);
517 size_type rfind(value_type c) const {
518 return folly::rfind(castToConst(), c);
521 size_type find(value_type c, size_t pos) const {
522 if (pos > size()) return std::string::npos;
523 size_type ret = qfind(castToConst().subpiece(pos), c);
524 return ret == npos ? ret : ret + pos;
527 size_type find_first_of(const_range_type needles) const {
528 return qfind_first_of(castToConst(), needles);
531 size_type find_first_of(const_range_type needles, size_t pos) const {
532 if (pos > size()) return std::string::npos;
533 size_type ret = qfind_first_of(castToConst().subpiece(pos), needles);
534 return ret == npos ? ret : ret + pos;
537 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
538 size_type find_first_of(Iter needles) const {
539 return find_first_of(const_range_type(needles));
542 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
543 size_type find_first_of(Iter needles, size_t pos) const {
544 return find_first_of(const_range_type(needles), pos);
547 size_type find_first_of(Iter needles, size_t pos, size_t n) const {
548 return find_first_of(const_range_type(needles, n), pos);
551 size_type find_first_of(value_type c) const {
555 size_type find_first_of(value_type c, size_t pos) const {
560 * Determine whether the range contains the given subrange or item.
562 * Note: Call find() directly if the index is needed.
564 bool contains(const const_range_type& other) const {
565 return find(other) != std::string::npos;
568 bool contains(const value_type& other) const {
569 return find(other) != std::string::npos;
572 void swap(Range& rhs) {
573 std::swap(b_, rhs.b_);
574 std::swap(e_, rhs.e_);
578 * Does this Range start with another range?
580 bool startsWith(const const_range_type& other) const {
581 return size() >= other.size()
582 && castToConst().subpiece(0, other.size()) == other;
584 bool startsWith(value_type c) const {
585 return !empty() && front() == c;
589 * Does this Range end with another range?
591 bool endsWith(const const_range_type& other) const {
592 return size() >= other.size()
593 && castToConst().subpiece(size() - other.size()) == other;
595 bool endsWith(value_type c) const {
596 return !empty() && back() == c;
600 * Remove the items in [b, e), as long as this subrange is at the beginning
601 * or end of the Range.
603 * Required for boost::algorithm::trim()
605 void erase(Iter b, Iter e) {
608 } else if (e == e_) {
611 throw std::out_of_range("index out of range");
616 * Remove the given prefix and return true if the range starts with the given
617 * prefix; return false otherwise.
619 bool removePrefix(const const_range_type& prefix) {
620 return startsWith(prefix) && (b_ += prefix.size(), true);
622 bool removePrefix(value_type prefix) {
623 return startsWith(prefix) && (++b_, true);
627 * Remove the given suffix and return true if the range ends with the given
628 * suffix; return false otherwise.
630 bool removeSuffix(const const_range_type& suffix) {
631 return endsWith(suffix) && (e_ -= suffix.size(), true);
633 bool removeSuffix(value_type suffix) {
634 return endsWith(suffix) && (--e_, true);
638 * Replaces the content of the range, starting at position 'pos', with
639 * contents of 'replacement'. Entire 'replacement' must fit into the
640 * range. Returns false if 'replacements' does not fit. Example use:
642 * char in[] = "buffer";
643 * auto msp = MutablesStringPiece(input);
644 * EXPECT_TRUE(msp.replaceAt(2, "tt"));
645 * EXPECT_EQ(msp, "butter");
647 * // not enough space
648 * EXPECT_FALSE(msp.replace(msp.size() - 1, "rr"));
649 * EXPECT_EQ(msp, "butter"); // unchanged
651 bool replaceAt(size_t pos, const_range_type replacement) {
652 if (size() < pos + replacement.size()) {
656 std::copy(replacement.begin(), replacement.end(), begin() + pos);
662 * Replaces all occurences of 'source' with 'dest'. Returns number
663 * of replacements made. Source and dest have to have the same
664 * length. Throws if the lengths are different. If 'source' is a
665 * pattern that is overlapping with itself, we perform sequential
666 * replacement: "aaaaaaa".replaceAll("aa", "ba") --> "bababaa"
670 * char in[] = "buffer";
671 * auto msp = MutablesStringPiece(input);
672 * EXPECT_EQ(msp.replaceAll("ff","tt"), 1);
673 * EXPECT_EQ(msp, "butter");
675 size_t replaceAll(const_range_type source, const_range_type dest) {
676 if (source.size() != dest.size()) {
677 throw std::invalid_argument(
678 "replacement must have the same size as source");
686 size_t num_replaced = 0;
687 size_type found = std::string::npos;
688 while ((found = find(source, pos)) != std::string::npos) {
689 replaceAt(found, dest);
690 pos += source.size();
698 * Splits this `Range` `[b, e)` in the position `i` dictated by the next
699 * occurence of `delimiter`.
701 * Returns a new `Range` `[b, i)` and adjusts this range to start right after
702 * the delimiter's position. This range will be empty if the delimiter is not
703 * found. If called on an empty `Range`, both this and the returned `Range`
708 * folly::StringPiece s("sample string for split_next");
709 * auto p = s.split_step(' ');
711 * // prints "string for split_next"
719 * void tokenize(StringPiece s, char delimiter) {
720 * while (!s.empty()) {
721 * cout << s.split_step(delimiter);
725 * @author: Marcelo Juchem <marcelo@fb.com>
727 Range split_step(value_type delimiter) {
728 auto i = std::find(b_, e_, delimiter);
731 b_ = i == e_ ? e_ : std::next(i);
736 Range split_step(Range delimiter) {
737 auto i = find(delimiter);
738 Range result(b_, i == std::string::npos ? size() : i);
740 b_ = result.end() == e_ ? e_ : std::next(result.end(), delimiter.size());
746 * Convenience method that calls `split_step()` and passes the result to a
747 * functor, returning whatever the functor does. Any additional arguments
748 * `args` passed to this function are perfectly forwarded to the functor.
750 * Say you have a functor with this signature:
752 * Foo fn(Range r) { }
754 * `split_step()`'s return type will be `Foo`. It works just like:
756 * auto result = fn(myRange.split_step(' '));
758 * A functor returning `void` is also supported.
762 * void do_some_parsing(folly::StringPiece s) {
763 * auto version = s.split_step(' ', [&](folly::StringPiece x) {
765 * throw std::invalid_argument("empty string");
767 * return std::strtoull(x.begin(), x.end(), 16);
774 * void parse(folly::StringPiece s) {
775 * s.split_step(' ', parse_field, bar, 10);
776 * s.split_step('\t', parse_field, baz, 20);
778 * auto const kludge = [](folly::StringPiece x, int &out, int def) {
782 * parse_field(x, out, def);
786 * s.split_step('\t', kludge, gaz);
787 * s.split_step(' ', kludge, foo);
796 * static parse_field(folly::StringPiece s, int &out, int def) {
798 * out = folly::to<int>(s);
799 * } catch (std::exception const &) {
805 * @author: Marcelo Juchem <marcelo@fb.com>
807 template <typename TProcess, typename... Args>
808 auto split_step(value_type delimiter, TProcess &&process, Args &&...args)
809 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
810 { return process(split_step(delimiter), std::forward<Args>(args)...); }
812 template <typename TProcess, typename... Args>
813 auto split_step(Range delimiter, TProcess &&process, Args &&...args)
814 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
815 { return process(split_step(delimiter), std::forward<Args>(args)...); }
821 template <class Iter>
822 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
825 void swap(Range<T>& lhs, Range<T>& rhs) {
830 * Create a range from two iterators, with type deduction.
832 template <class Iter>
833 Range<Iter> range(Iter first, Iter last) {
834 return Range<Iter>(first, last);
838 * Creates a range to reference the contents of a contiguous-storage container.
840 // Use pointers for types with '.data()' member
841 template <class Collection,
842 class T = typename std::remove_pointer<
843 decltype(std::declval<Collection>().data())>::type>
844 Range<T*> range(Collection&& v) {
845 return Range<T*>(v.data(), v.data() + v.size());
848 template <class T, size_t n>
849 Range<T*> range(T (&array)[n]) {
850 return Range<T*>(array, array + n);
853 typedef Range<const char*> StringPiece;
854 typedef Range<char*> MutableStringPiece;
855 typedef Range<const unsigned char*> ByteRange;
856 typedef Range<unsigned char*> MutableByteRange;
858 inline std::ostream& operator<<(std::ostream& os,
859 const StringPiece piece) {
860 os.write(piece.start(), piece.size());
864 inline std::ostream& operator<<(std::ostream& os,
865 const MutableStringPiece piece) {
866 os.write(piece.start(), piece.size());
871 * Templated comparison operators
875 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
876 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
880 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
881 return lhs.compare(rhs) < 0;
885 * Specializations of comparison operators for StringPiece
890 template <class A, class B>
891 struct ComparableAsStringPiece {
894 (std::is_convertible<A, StringPiece>::value
895 && std::is_same<B, StringPiece>::value)
897 (std::is_convertible<B, StringPiece>::value
898 && std::is_same<A, StringPiece>::value)
902 } // namespace detail
905 * operator== through conversion for Range<const char*>
907 template <class T, class U>
909 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
910 operator==(const T& lhs, const U& rhs) {
911 return StringPiece(lhs) == StringPiece(rhs);
915 * operator< through conversion for Range<const char*>
917 template <class T, class U>
919 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
920 operator<(const T& lhs, const U& rhs) {
921 return StringPiece(lhs) < StringPiece(rhs);
925 * operator> through conversion for Range<const char*>
927 template <class T, class U>
929 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
930 operator>(const T& lhs, const U& rhs) {
931 return StringPiece(lhs) > StringPiece(rhs);
935 * operator< through conversion for Range<const char*>
937 template <class T, class U>
939 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
940 operator<=(const T& lhs, const U& rhs) {
941 return StringPiece(lhs) <= StringPiece(rhs);
945 * operator> through conversion for Range<const char*>
947 template <class T, class U>
949 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
950 operator>=(const T& lhs, const U& rhs) {
951 return StringPiece(lhs) >= StringPiece(rhs);
954 // Do NOT use this, use SpookyHashV2 instead, see commment on hash() above.
955 struct StringPieceHash {
956 std::size_t operator()(const StringPiece str) const {
957 return static_cast<std::size_t>(str.hash());
962 * Finds substrings faster than brute force by borrowing from Boyer-Moore
964 template <class T, class Comp>
965 size_t qfind(const Range<T>& haystack,
966 const Range<T>& needle,
968 // Don't use std::search, use a Boyer-Moore-like trick by comparing
969 // the last characters first
970 auto const nsize = needle.size();
971 if (haystack.size() < nsize) {
972 return std::string::npos;
974 if (!nsize) return 0;
975 auto const nsize_1 = nsize - 1;
976 auto const lastNeedle = needle[nsize_1];
978 // Boyer-Moore skip value for the last char in the needle. Zero is
979 // not a valid value; skip will be computed the first time it's
981 std::string::size_type skip = 0;
983 auto i = haystack.begin();
984 auto iEnd = haystack.end() - nsize_1;
987 // Boyer-Moore: match the last element in the needle
988 while (!eq(i[nsize_1], lastNeedle)) {
991 return std::string::npos;
994 // Here we know that the last char matches
995 // Continue in pedestrian mode
996 for (size_t j = 0; ; ) {
998 if (!eq(i[j], needle[j])) {
999 // Not found, we can skip
1000 // Compute the skip value lazily
1003 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
1010 // Check if done searching
1013 return i - haystack.begin();
1017 return std::string::npos;
1022 inline size_t qfind_first_byte_of(const StringPiece haystack,
1023 const StringPiece needles) {
1024 static auto const qfind_first_byte_of_fn =
1025 folly::CpuId().sse42() ? qfind_first_byte_of_sse42
1026 : qfind_first_byte_of_nosse;
1027 return qfind_first_byte_of_fn(haystack, needles);
1030 } // namespace detail
1032 template <class T, class Comp>
1033 size_t qfind_first_of(const Range<T> & haystack,
1034 const Range<T> & needles,
1036 auto ret = std::find_first_of(haystack.begin(), haystack.end(),
1037 needles.begin(), needles.end(),
1039 return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
1042 struct AsciiCaseSensitive {
1043 bool operator()(char lhs, char rhs) const {
1049 * Check if two ascii characters are case insensitive equal.
1050 * The difference between the lower/upper case characters are the 6-th bit.
1051 * We also check they are alpha chars, in case of xor = 32.
1053 struct AsciiCaseInsensitive {
1054 bool operator()(char lhs, char rhs) const {
1056 if (k == 0) return true;
1057 if (k != 32) return false;
1059 return (k >= 'a' && k <= 'z');
1064 size_t qfind(const Range<T>& haystack,
1065 const typename Range<T>::value_type& needle) {
1066 auto pos = std::find(haystack.begin(), haystack.end(), needle);
1067 return pos == haystack.end() ? std::string::npos : pos - haystack.data();
1071 size_t rfind(const Range<T>& haystack,
1072 const typename Range<T>::value_type& needle) {
1073 for (auto i = haystack.size(); i-- > 0; ) {
1074 if (haystack[i] == needle) {
1078 return std::string::npos;
1081 // specialization for StringPiece
1083 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
1084 auto pos = static_cast<const char*>(
1085 ::memchr(haystack.data(), needle, haystack.size()));
1086 return pos == nullptr ? std::string::npos : pos - haystack.data();
1090 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
1091 auto pos = static_cast<const char*>(
1092 ::memrchr(haystack.data(), needle, haystack.size()));
1093 return pos == nullptr ? std::string::npos : pos - haystack.data();
1096 // specialization for ByteRange
1098 inline size_t qfind(const Range<const unsigned char*>& haystack,
1099 const unsigned char& needle) {
1100 auto pos = static_cast<const unsigned char*>(
1101 ::memchr(haystack.data(), needle, haystack.size()));
1102 return pos == nullptr ? std::string::npos : pos - haystack.data();
1106 inline size_t rfind(const Range<const unsigned char*>& haystack,
1107 const unsigned char& needle) {
1108 auto pos = static_cast<const unsigned char*>(
1109 ::memrchr(haystack.data(), needle, haystack.size()));
1110 return pos == nullptr ? std::string::npos : pos - haystack.data();
1114 size_t qfind_first_of(const Range<T>& haystack,
1115 const Range<T>& needles) {
1116 return qfind_first_of(haystack, needles, AsciiCaseSensitive());
1119 // specialization for StringPiece
1121 inline size_t qfind_first_of(const Range<const char*>& haystack,
1122 const Range<const char*>& needles) {
1123 return detail::qfind_first_byte_of(haystack, needles);
1126 // specialization for ByteRange
1128 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
1129 const Range<const unsigned char*>& needles) {
1130 return detail::qfind_first_byte_of(StringPiece(haystack),
1131 StringPiece(needles));
1134 template<class Key, class Enable>
1138 struct hasher<folly::Range<T*>,
1139 typename std::enable_if<std::is_pod<T>::value, void>::type> {
1140 size_t operator()(folly::Range<T*> r) const {
1141 return hash::SpookyHashV2::Hash64(r.begin(), r.size() * sizeof(T), 0);
1145 } // !namespace folly
1147 #pragma GCC diagnostic pop
1149 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);
1151 #endif // FOLLY_RANGE_H_