2 * Copyright 2014 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>
26 #include <boost/operators.hpp>
29 #include <glog/logging.h>
33 #include <type_traits>
35 // libc++ doesn't provide this header, nor does msvc
36 #ifdef FOLLY_HAVE_BITS_CXXCONFIG_H
37 // This file appears in two locations: inside fbcode and in the
38 // libstdc++ source code (when embedding fbstring as std::string).
39 // To aid in this schizophrenic use, two macros are defined in
41 // _LIBSTDCXX_FBSTRING - Set inside libstdc++. This is useful to
42 // gate use inside fbcode v. libstdc++
43 #include <bits/c++config.h>
46 #include <folly/CpuId.h>
47 #include <folly/Traits.h>
48 #include <folly/Likely.h>
50 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
51 #pragma GCC diagnostic push
52 #pragma GCC diagnostic ignored "-Wshadow"
56 template <class T> class Range;
59 * Finds the first occurrence of needle in haystack. The algorithm is on
60 * average faster than O(haystack.size() * needle.size()) but not as fast
61 * as Boyer-Moore. On the upside, it does not do any upfront
62 * preprocessing and does not allocate memory.
64 template <class T, class Comp = std::equal_to<typename Range<T>::value_type>>
65 inline size_t qfind(const Range<T> & haystack,
66 const Range<T> & needle,
70 * Finds the first occurrence of needle in haystack. The result is the
71 * offset reported to the beginning of haystack, or string::npos if
72 * needle wasn't found.
75 size_t qfind(const Range<T> & haystack,
76 const typename Range<T>::value_type& needle);
79 * Finds the last occurrence of needle in haystack. The result is the
80 * offset reported to the beginning of haystack, or string::npos if
81 * needle wasn't found.
84 size_t rfind(const Range<T> & haystack,
85 const typename Range<T>::value_type& needle);
89 * Finds the first occurrence of any element of needle in
90 * haystack. The algorithm is O(haystack.size() * needle.size()).
93 inline size_t qfind_first_of(const Range<T> & haystack,
94 const Range<T> & needle);
97 * Small internal helper - returns the value just before an iterator.
102 * For random-access iterators, the value before is simply i[-1].
104 template <class Iter>
105 typename std::enable_if<
106 std::is_same<typename std::iterator_traits<Iter>::iterator_category,
107 std::random_access_iterator_tag>::value,
108 typename std::iterator_traits<Iter>::reference>::type
109 value_before(Iter i) {
114 * For all other iterators, we need to use the decrement operator.
116 template <class Iter>
117 typename std::enable_if<
118 !std::is_same<typename std::iterator_traits<Iter>::iterator_category,
119 std::random_access_iterator_tag>::value,
120 typename std::iterator_traits<Iter>::reference>::type
121 value_before(Iter i) {
126 * Use IsCharPointer<T>::type to enable const char* or char*.
127 * Use IsCharPointer<T>::const_type to enable only const char*.
129 template <class T> struct IsCharPointer {};
132 struct IsCharPointer<char*> {
137 struct IsCharPointer<const char*> {
138 typedef int const_type;
142 } // namespace detail
145 * Range abstraction keeping a pair of iterators. We couldn't use
146 * boost's similar range abstraction because we need an API identical
147 * with the former StringPiece class, which is used by a lot of other
148 * code. This abstraction does fulfill the needs of boost's
149 * range-oriented algorithms though.
151 * (Keep memory lifetime in mind when using this class, since it
152 * doesn't manage the data it refers to - just like an iterator
155 template <class Iter>
156 class Range : private boost::totally_ordered<Range<Iter> > {
158 typedef std::size_t size_type;
159 typedef Iter iterator;
160 typedef Iter const_iterator;
161 typedef typename std::remove_reference<
162 typename std::iterator_traits<Iter>::reference>::type
164 typedef typename std::iterator_traits<Iter>::reference reference;
167 * For MutableStringPiece and MutableByteRange we define StringPiece
168 * and ByteRange as const_range_type (for everything else its just
169 * identity). We do that to enable operations such as find with
170 * args which are const.
172 typedef typename std::conditional<
173 std::is_same<Iter, char*>::value
174 || std::is_same<Iter, unsigned char*>::value,
175 Range<const value_type*>,
176 Range<Iter>>::type const_range_type;
178 typedef std::char_traits<typename std::remove_const<value_type>::type>
181 static const size_type npos;
183 // Works for all iterators
184 constexpr Range() : b_(), e_() {
187 constexpr Range(const Range&) = default;
188 constexpr Range(Range&&) = default;
191 // Works for all iterators
192 constexpr Range(Iter start, Iter end) : b_(start), e_(end) {
195 // Works only for random-access iterators
196 constexpr Range(Iter start, size_t size)
197 : b_(start), e_(start + size) { }
199 #if FOLLY_HAVE_CONSTEXPR_STRLEN
200 template <class T = Iter, typename detail::IsCharPointer<T>::type = 0>
201 constexpr /* implicit */ Range(Iter str)
202 : b_(str), e_(str + strlen(str)) {}
204 template <class T = Iter, typename detail::IsCharPointer<T>::type = 0>
205 /* implicit */ Range(Iter str)
206 : b_(str), e_(str + strlen(str)) {}
208 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
209 /* implicit */ Range(const std::string& str)
210 : b_(str.data()), e_(b_ + str.size()) {}
212 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
213 Range(const std::string& str, std::string::size_type startFrom) {
214 if (UNLIKELY(startFrom > str.size())) {
215 throw std::out_of_range("index out of range");
217 b_ = str.data() + startFrom;
218 e_ = str.data() + str.size();
221 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
222 Range(const std::string& str,
223 std::string::size_type startFrom,
224 std::string::size_type size) {
225 if (UNLIKELY(startFrom > str.size())) {
226 throw std::out_of_range("index out of range");
228 b_ = str.data() + startFrom;
229 if (str.size() - startFrom < size) {
230 e_ = str.data() + str.size();
236 Range(const Range& other,
238 size_type length = npos)
239 : Range(other.subpiece(first, length))
242 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
243 /* implicit */ Range(const fbstring& str)
244 : b_(str.data()), e_(b_ + str.size()) { }
246 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
247 Range(const fbstring& str, fbstring::size_type startFrom) {
248 if (UNLIKELY(startFrom > str.size())) {
249 throw std::out_of_range("index out of range");
251 b_ = str.data() + startFrom;
252 e_ = str.data() + str.size();
255 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
256 Range(const fbstring& str, fbstring::size_type startFrom,
257 fbstring::size_type size) {
258 if (UNLIKELY(startFrom > str.size())) {
259 throw std::out_of_range("index out of range");
261 b_ = str.data() + startFrom;
262 if (str.size() - startFrom < size) {
263 e_ = str.data() + str.size();
269 // Allow implicit conversion from Range<const char*> (aka StringPiece) to
270 // Range<const unsigned char*> (aka ByteRange), as they're both frequently
271 // used to represent ranges of bytes. Allow explicit conversion in the other
273 template <class OtherIter, typename std::enable_if<
274 (std::is_same<Iter, const unsigned char*>::value &&
275 (std::is_same<OtherIter, const char*>::value ||
276 std::is_same<OtherIter, char*>::value)), int>::type = 0>
277 /* implicit */ Range(const Range<OtherIter>& other)
278 : b_(reinterpret_cast<const unsigned char*>(other.begin())),
279 e_(reinterpret_cast<const unsigned char*>(other.end())) {
282 template <class OtherIter, typename std::enable_if<
283 (std::is_same<Iter, unsigned char*>::value &&
284 std::is_same<OtherIter, char*>::value), int>::type = 0>
285 /* implicit */ Range(const Range<OtherIter>& other)
286 : b_(reinterpret_cast<unsigned char*>(other.begin())),
287 e_(reinterpret_cast<unsigned char*>(other.end())) {
290 template <class OtherIter, typename std::enable_if<
291 (std::is_same<Iter, const char*>::value &&
292 (std::is_same<OtherIter, const unsigned char*>::value ||
293 std::is_same<OtherIter, unsigned char*>::value)), int>::type = 0>
294 explicit Range(const Range<OtherIter>& other)
295 : b_(reinterpret_cast<const char*>(other.begin())),
296 e_(reinterpret_cast<const char*>(other.end())) {
299 template <class OtherIter, typename std::enable_if<
300 (std::is_same<Iter, char*>::value &&
301 std::is_same<OtherIter, unsigned char*>::value), int>::type = 0>
302 explicit Range(const Range<OtherIter>& other)
303 : b_(reinterpret_cast<char*>(other.begin())),
304 e_(reinterpret_cast<char*>(other.end())) {
307 // Allow implicit conversion from Range<From> to Range<To> if From is
308 // implicitly convertible to To.
309 template <class OtherIter, typename std::enable_if<
310 (!std::is_same<Iter, OtherIter>::value &&
311 std::is_convertible<OtherIter, Iter>::value), int>::type = 0>
312 constexpr /* implicit */ Range(const Range<OtherIter>& other)
317 // Allow explicit conversion from Range<From> to Range<To> if From is
318 // explicitly convertible to To.
319 template <class OtherIter, typename std::enable_if<
320 (!std::is_same<Iter, OtherIter>::value &&
321 !std::is_convertible<OtherIter, Iter>::value &&
322 std::is_constructible<Iter, const OtherIter&>::value), int>::type = 0>
323 constexpr explicit Range(const Range<OtherIter>& other)
328 Range& operator=(const Range& rhs) & = default;
329 Range& operator=(Range&& rhs) & = default;
336 void assign(Iter start, Iter end) {
341 void reset(Iter start, size_type size) {
346 // Works only for Range<const char*>
347 void reset(const std::string& str) {
348 reset(str.data(), str.size());
351 size_type size() const {
355 size_type walk_size() const {
357 return std::distance(b_, e_);
359 bool empty() const { return b_ == e_; }
360 Iter data() const { return b_; }
361 Iter start() const { return b_; }
362 Iter begin() const { return b_; }
363 Iter end() const { return e_; }
364 Iter cbegin() const { return b_; }
365 Iter cend() const { return e_; }
366 value_type& front() {
372 return detail::value_before(e_);
374 const value_type& front() const {
378 const value_type& back() const {
380 return detail::value_before(e_);
382 // Works only for Range<const char*> and Range<char*>
383 std::string str() const { return std::string(b_, size()); }
384 std::string toString() const { return str(); }
385 // Works only for Range<const char*> and Range<char*>
386 fbstring fbstr() const { return fbstring(b_, size()); }
387 fbstring toFbstring() const { return fbstr(); }
389 const_range_type castToConst() const {
390 return const_range_type(*this);
393 // Works only for Range<const char*> and Range<char*>
394 int compare(const const_range_type& o) const {
395 const size_type tsize = this->size();
396 const size_type osize = o.size();
397 const size_type msize = std::min(tsize, osize);
398 int r = traits_type::compare(data(), o.data(), msize);
399 if (r == 0 && tsize != osize) {
400 // We check the signed bit of the subtraction and bit shift it
401 // to produce either 0 or 2. The subtraction yields the
402 // comparison values of either -1 or 1.
403 r = (static_cast<int>(
404 (osize - tsize) >> (CHAR_BIT * sizeof(size_t) - 1)) << 1) - 1;
409 value_type& operator[](size_t i) {
410 DCHECK_GT(size(), i);
414 const value_type& operator[](size_t i) const {
415 DCHECK_GT(size(), i);
419 value_type& at(size_t i) {
420 if (i >= size()) throw std::out_of_range("index out of range");
424 const value_type& at(size_t i) const {
425 if (i >= size()) throw std::out_of_range("index out of range");
429 // Works only for Range<const char*> and Range<char*>
430 uint32_t hash() const {
431 // Taken from fbi/nstring.h:
432 // Quick and dirty bernstein hash...fine for short ascii strings
433 uint32_t hash = 5381;
434 for (size_t ix = 0; ix < size(); ix++) {
435 hash = ((hash << 5) + hash) + b_[ix];
440 void advance(size_type n) {
441 if (UNLIKELY(n > size())) {
442 throw std::out_of_range("index out of range");
447 void subtract(size_type n) {
448 if (UNLIKELY(n > size())) {
449 throw std::out_of_range("index out of range");
464 Range subpiece(size_type first, size_type length = npos) const {
465 if (UNLIKELY(first > size())) {
466 throw std::out_of_range("index out of range");
469 return Range(b_ + first, std::min(length, size() - first));
472 // string work-alike functions
473 size_type find(const_range_type str) const {
474 return qfind(castToConst(), str);
477 size_type find(const_range_type str, size_t pos) const {
478 if (pos > size()) return std::string::npos;
479 size_t ret = qfind(castToConst().subpiece(pos), str);
480 return ret == npos ? ret : ret + pos;
483 size_type find(Iter s, size_t pos, size_t n) const {
484 if (pos > size()) return std::string::npos;
485 auto forFinding = castToConst();
487 pos ? forFinding.subpiece(pos) : forFinding, const_range_type(s, n));
488 return ret == npos ? ret : ret + pos;
491 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
492 size_type find(const Iter s) const {
493 return qfind(castToConst(), const_range_type(s));
496 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
497 size_type find(const Iter s, size_t pos) const {
498 if (pos > size()) return std::string::npos;
499 size_type ret = qfind(castToConst().subpiece(pos), const_range_type(s));
500 return ret == npos ? ret : ret + pos;
503 size_type find(value_type c) const {
504 return qfind(castToConst(), c);
507 size_type rfind(value_type c) const {
508 return folly::rfind(castToConst(), c);
511 size_type find(value_type c, size_t pos) const {
512 if (pos > size()) return std::string::npos;
513 size_type ret = qfind(castToConst().subpiece(pos), c);
514 return ret == npos ? ret : ret + pos;
517 size_type find_first_of(const_range_type needles) const {
518 return qfind_first_of(castToConst(), needles);
521 size_type find_first_of(const_range_type needles, size_t pos) const {
522 if (pos > size()) return std::string::npos;
523 size_type ret = qfind_first_of(castToConst().subpiece(pos), needles);
524 return ret == npos ? ret : ret + pos;
527 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
528 size_type find_first_of(Iter needles) const {
529 return find_first_of(const_range_type(needles));
532 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
533 size_type find_first_of(Iter needles, size_t pos) const {
534 return find_first_of(const_range_type(needles), pos);
537 size_type find_first_of(Iter needles, size_t pos, size_t n) const {
538 return find_first_of(const_range_type(needles, n), pos);
541 size_type find_first_of(value_type c) const {
545 size_type find_first_of(value_type c, size_t pos) const {
550 * Determine whether the range contains the given subrange or item.
552 * Note: Call find() directly if the index is needed.
554 bool contains(const const_range_type& other) const {
555 return find(other) != std::string::npos;
558 bool contains(const value_type& other) const {
559 return find(other) != std::string::npos;
562 void swap(Range& rhs) {
563 std::swap(b_, rhs.b_);
564 std::swap(e_, rhs.e_);
568 * Does this Range start with another range?
570 bool startsWith(const const_range_type& other) const {
571 return size() >= other.size()
572 && castToConst().subpiece(0, other.size()) == other;
574 bool startsWith(value_type c) const {
575 return !empty() && front() == c;
579 * Does this Range end with another range?
581 bool endsWith(const const_range_type& other) const {
582 return size() >= other.size()
583 && castToConst().subpiece(size() - other.size()) == other;
585 bool endsWith(value_type c) const {
586 return !empty() && back() == c;
590 * Remove the given prefix and return true if the range starts with the given
591 * prefix; return false otherwise.
593 bool removePrefix(const const_range_type& prefix) {
594 return startsWith(prefix) && (b_ += prefix.size(), true);
596 bool removePrefix(value_type prefix) {
597 return startsWith(prefix) && (++b_, true);
601 * Remove the given suffix and return true if the range ends with the given
602 * suffix; return false otherwise.
604 bool removeSuffix(const const_range_type& suffix) {
605 return endsWith(suffix) && (e_ -= suffix.size(), true);
607 bool removeSuffix(value_type suffix) {
608 return endsWith(suffix) && (--e_, true);
612 * Replaces the content of the range, starting at position 'pos', with
613 * contents of 'replacement'. Entire 'replacement' must fit into the
614 * range. Returns false if 'replacements' does not fit. Example use:
616 * char in[] = "buffer";
617 * auto msp = MutablesStringPiece(input);
618 * EXPECT_TRUE(msp.replaceAt(2, "tt"));
619 * EXPECT_EQ(msp, "butter");
621 * // not enough space
622 * EXPECT_FALSE(msp.replace(msp.size() - 1, "rr"));
623 * EXPECT_EQ(msp, "butter"); // unchanged
625 bool replaceAt(size_t pos, const_range_type replacement) {
626 if (size() < pos + replacement.size()) {
630 std::copy(replacement.begin(), replacement.end(), begin() + pos);
636 * Replaces all occurences of 'source' with 'dest'. Returns number
637 * of replacements made. Source and dest have to have the same
638 * length. Throws if the lengths are different. If 'source' is a
639 * pattern that is overlapping with itself, we perform sequential
640 * replacement: "aaaaaaa".replaceAll("aa", "ba") --> "bababaa"
644 * char in[] = "buffer";
645 * auto msp = MutablesStringPiece(input);
646 * EXPECT_EQ(msp.replaceAll("ff","tt"), 1);
647 * EXPECT_EQ(msp, "butter");
649 size_t replaceAll(const_range_type source, const_range_type dest) {
650 if (source.size() != dest.size()) {
651 throw std::invalid_argument(
652 "replacement must have the same size as source");
660 size_t num_replaced = 0;
661 size_type found = std::string::npos;
662 while ((found = find(source, pos)) != std::string::npos) {
663 replaceAt(found, dest);
664 pos += source.size();
672 * Splits this `Range` `[b, e)` in the position `i` dictated by the next
673 * occurence of `delimiter`.
675 * Returns a new `Range` `[b, i)` and adjusts this range to start right after
676 * the delimiter's position. This range will be empty if the delimiter is not
677 * found. If called on an empty `Range`, both this and the returned `Range`
682 * folly::StringPiece s("sample string for split_next");
683 * auto p = s.split_step(' ');
685 * // prints "string for split_next"
693 * void tokenize(StringPiece s, char delimiter) {
694 * while (!s.empty()) {
695 * cout << s.split_step(delimiter);
699 * @author: Marcelo Juchem <marcelo@fb.com>
701 Range split_step(value_type delimiter) {
702 auto i = std::find(b_, e_, delimiter);
705 b_ = i == e_ ? e_ : std::next(i);
710 Range split_step(Range delimiter) {
711 auto i = find(delimiter);
712 Range result(b_, i == std::string::npos ? size() : i);
714 b_ = result.end() == e_ ? e_ : std::next(result.end(), delimiter.size());
720 * Convenience method that calls `split_step()` and passes the result to a
721 * functor, returning whatever the functor does. Any additional arguments
722 * `args` passed to this function are perfectly forwarded to the functor.
724 * Say you have a functor with this signature:
726 * Foo fn(Range r) { }
728 * `split_step()`'s return type will be `Foo`. It works just like:
730 * auto result = fn(myRange.split_step(' '));
732 * A functor returning `void` is also supported.
736 * void do_some_parsing(folly::StringPiece s) {
737 * auto version = s.split_step(' ', [&](folly::StringPiece x) {
739 * throw std::invalid_argument("empty string");
741 * return std::strtoull(x.begin(), x.end(), 16);
748 * void parse(folly::StringPiece s) {
749 * s.split_step(' ', parse_field, bar, 10);
750 * s.split_step('\t', parse_field, baz, 20);
752 * auto const kludge = [](folly::StringPiece x, int &out, int def) {
756 * parse_field(x, out, def);
760 * s.split_step('\t', kludge, gaz);
761 * s.split_step(' ', kludge, foo);
770 * static parse_field(folly::StringPiece s, int &out, int def) {
772 * out = folly::to<int>(s);
773 * } catch (std::exception const &) {
779 * @author: Marcelo Juchem <marcelo@fb.com>
781 template <typename TProcess, typename... Args>
782 auto split_step(value_type delimiter, TProcess &&process, Args &&...args)
783 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
784 { return process(split_step(delimiter), std::forward<Args>(args)...); }
786 template <typename TProcess, typename... Args>
787 auto split_step(Range delimiter, TProcess &&process, Args &&...args)
788 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
789 { return process(split_step(delimiter), std::forward<Args>(args)...); }
795 template <class Iter>
796 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
799 void swap(Range<T>& lhs, Range<T>& rhs) {
804 * Create a range from two iterators, with type deduction.
806 template <class Iter>
807 Range<Iter> range(Iter first, Iter last) {
808 return Range<Iter>(first, last);
812 * Creates a range to reference the contents of a contiguous-storage container.
814 // Use pointers for types with '.data()' member
815 template <class Collection,
816 class T = typename std::remove_pointer<
817 decltype(std::declval<Collection>().data())>::type>
818 Range<T*> range(Collection&& v) {
819 return Range<T*>(v.data(), v.data() + v.size());
822 template <class T, size_t n>
823 Range<T*> range(T (&array)[n]) {
824 return Range<T*>(array, array + n);
827 typedef Range<const char*> StringPiece;
828 typedef Range<char*> MutableStringPiece;
829 typedef Range<const unsigned char*> ByteRange;
830 typedef Range<unsigned char*> MutableByteRange;
832 std::ostream& operator<<(std::ostream& os, const StringPiece piece);
833 std::ostream& operator<<(std::ostream& os, const MutableStringPiece piece);
836 * Templated comparison operators
840 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
841 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
845 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
846 return lhs.compare(rhs) < 0;
850 * Specializations of comparison operators for StringPiece
855 template <class A, class B>
856 struct ComparableAsStringPiece {
859 (std::is_convertible<A, StringPiece>::value
860 && std::is_same<B, StringPiece>::value)
862 (std::is_convertible<B, StringPiece>::value
863 && std::is_same<A, StringPiece>::value)
867 } // namespace detail
870 * operator== through conversion for Range<const char*>
872 template <class T, class U>
874 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
875 operator==(const T& lhs, const U& rhs) {
876 return StringPiece(lhs) == StringPiece(rhs);
880 * operator< through conversion for Range<const char*>
882 template <class T, class U>
884 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
885 operator<(const T& lhs, const U& rhs) {
886 return StringPiece(lhs) < StringPiece(rhs);
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);
919 struct StringPieceHash {
920 std::size_t operator()(const StringPiece str) const {
921 return static_cast<std::size_t>(str.hash());
926 * Finds substrings faster than brute force by borrowing from Boyer-Moore
928 template <class T, class Comp>
929 size_t qfind(const Range<T>& haystack,
930 const Range<T>& needle,
932 // Don't use std::search, use a Boyer-Moore-like trick by comparing
933 // the last characters first
934 auto const nsize = needle.size();
935 if (haystack.size() < nsize) {
936 return std::string::npos;
938 if (!nsize) return 0;
939 auto const nsize_1 = nsize - 1;
940 auto const lastNeedle = needle[nsize_1];
942 // Boyer-Moore skip value for the last char in the needle. Zero is
943 // not a valid value; skip will be computed the first time it's
945 std::string::size_type skip = 0;
947 auto i = haystack.begin();
948 auto iEnd = haystack.end() - nsize_1;
951 // Boyer-Moore: match the last element in the needle
952 while (!eq(i[nsize_1], lastNeedle)) {
955 return std::string::npos;
958 // Here we know that the last char matches
959 // Continue in pedestrian mode
960 for (size_t j = 0; ; ) {
962 if (!eq(i[j], needle[j])) {
963 // Not found, we can skip
964 // Compute the skip value lazily
967 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
974 // Check if done searching
977 return i - haystack.begin();
981 return std::string::npos;
986 size_t qfind_first_byte_of_nosse(const StringPiece haystack,
987 const StringPiece needles);
989 #if FOLLY_HAVE_EMMINTRIN_H && __GNUC_PREREQ(4, 6)
990 size_t qfind_first_byte_of_sse42(const StringPiece haystack,
991 const StringPiece needles);
993 inline size_t qfind_first_byte_of(const StringPiece haystack,
994 const StringPiece needles) {
995 static auto const qfind_first_byte_of_fn =
996 folly::CpuId().sse42() ? qfind_first_byte_of_sse42
997 : qfind_first_byte_of_nosse;
998 return qfind_first_byte_of_fn(haystack, needles);
1002 inline size_t qfind_first_byte_of(const StringPiece haystack,
1003 const StringPiece needles) {
1004 return qfind_first_byte_of_nosse(haystack, needles);
1006 #endif // FOLLY_HAVE_EMMINTRIN_H
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');
1041 extern const AsciiCaseSensitive asciiCaseSensitive;
1042 extern const AsciiCaseInsensitive asciiCaseInsensitive;
1045 size_t qfind(const Range<T>& haystack,
1046 const typename Range<T>::value_type& needle) {
1047 auto pos = std::find(haystack.begin(), haystack.end(), needle);
1048 return pos == haystack.end() ? std::string::npos : pos - haystack.data();
1052 size_t rfind(const Range<T>& haystack,
1053 const typename Range<T>::value_type& needle) {
1054 for (auto i = haystack.size(); i-- > 0; ) {
1055 if (haystack[i] == needle) {
1059 return std::string::npos;
1062 // specialization for StringPiece
1064 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
1065 auto pos = static_cast<const char*>(
1066 ::memchr(haystack.data(), needle, haystack.size()));
1067 return pos == nullptr ? std::string::npos : pos - haystack.data();
1070 #if FOLLY_HAVE_MEMRCHR
1072 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
1073 auto pos = static_cast<const char*>(
1074 ::memrchr(haystack.data(), needle, haystack.size()));
1075 return pos == nullptr ? std::string::npos : pos - haystack.data();
1079 // specialization for ByteRange
1081 inline size_t qfind(const Range<const unsigned char*>& haystack,
1082 const unsigned char& needle) {
1083 auto pos = static_cast<const unsigned char*>(
1084 ::memchr(haystack.data(), needle, haystack.size()));
1085 return pos == nullptr ? std::string::npos : pos - haystack.data();
1088 #if FOLLY_HAVE_MEMRCHR
1090 inline size_t rfind(const Range<const unsigned char*>& haystack,
1091 const unsigned char& needle) {
1092 auto pos = static_cast<const unsigned char*>(
1093 ::memrchr(haystack.data(), needle, haystack.size()));
1094 return pos == nullptr ? std::string::npos : pos - haystack.data();
1099 size_t qfind_first_of(const Range<T>& haystack,
1100 const Range<T>& needles) {
1101 return qfind_first_of(haystack, needles, asciiCaseSensitive);
1104 // specialization for StringPiece
1106 inline size_t qfind_first_of(const Range<const char*>& haystack,
1107 const Range<const char*>& needles) {
1108 return detail::qfind_first_byte_of(haystack, needles);
1111 // specialization for ByteRange
1113 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
1114 const Range<const unsigned char*>& needles) {
1115 return detail::qfind_first_byte_of(StringPiece(haystack),
1116 StringPiece(needles));
1118 } // !namespace folly
1120 #pragma GCC diagnostic pop
1122 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);
1124 #endif // FOLLY_RANGE_H_