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>
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 // Do NOT use this function, which was left behind for backwards
430 // compatibility. Use SpookyHashV2 instead -- it is faster, and produces
431 // a 64-bit hash, which means dramatically fewer collisions in large maps.
432 // (The above advice does not apply if you are targeting a 32-bit system.)
434 // Works only for Range<const char*> and Range<char*>
435 uint32_t hash() const {
436 // Taken from fbi/nstring.h:
437 // Quick and dirty bernstein hash...fine for short ascii strings
438 uint32_t hash = 5381;
439 for (size_t ix = 0; ix < size(); ix++) {
440 hash = ((hash << 5) + hash) + b_[ix];
445 void advance(size_type n) {
446 if (UNLIKELY(n > size())) {
447 throw std::out_of_range("index out of range");
452 void subtract(size_type n) {
453 if (UNLIKELY(n > size())) {
454 throw std::out_of_range("index out of range");
469 Range subpiece(size_type first, size_type length = npos) const {
470 if (UNLIKELY(first > size())) {
471 throw std::out_of_range("index out of range");
474 return Range(b_ + first, std::min(length, size() - first));
477 // string work-alike functions
478 size_type find(const_range_type str) const {
479 return qfind(castToConst(), str);
482 size_type find(const_range_type str, size_t pos) const {
483 if (pos > size()) return std::string::npos;
484 size_t ret = qfind(castToConst().subpiece(pos), str);
485 return ret == npos ? ret : ret + pos;
488 size_type find(Iter s, size_t pos, size_t n) const {
489 if (pos > size()) return std::string::npos;
490 auto forFinding = castToConst();
492 pos ? forFinding.subpiece(pos) : forFinding, const_range_type(s, n));
493 return ret == npos ? ret : ret + pos;
496 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
497 size_type find(const Iter s) const {
498 return qfind(castToConst(), const_range_type(s));
501 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
502 size_type find(const Iter s, size_t pos) const {
503 if (pos > size()) return std::string::npos;
504 size_type ret = qfind(castToConst().subpiece(pos), const_range_type(s));
505 return ret == npos ? ret : ret + pos;
508 size_type find(value_type c) const {
509 return qfind(castToConst(), c);
512 size_type rfind(value_type c) const {
513 return folly::rfind(castToConst(), c);
516 size_type find(value_type c, size_t pos) const {
517 if (pos > size()) return std::string::npos;
518 size_type ret = qfind(castToConst().subpiece(pos), c);
519 return ret == npos ? ret : ret + pos;
522 size_type find_first_of(const_range_type needles) const {
523 return qfind_first_of(castToConst(), needles);
526 size_type find_first_of(const_range_type needles, size_t pos) const {
527 if (pos > size()) return std::string::npos;
528 size_type ret = qfind_first_of(castToConst().subpiece(pos), needles);
529 return ret == npos ? ret : ret + pos;
532 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
533 size_type find_first_of(Iter needles) const {
534 return find_first_of(const_range_type(needles));
537 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
538 size_type find_first_of(Iter needles, size_t pos) const {
539 return find_first_of(const_range_type(needles), pos);
542 size_type find_first_of(Iter needles, size_t pos, size_t n) const {
543 return find_first_of(const_range_type(needles, n), pos);
546 size_type find_first_of(value_type c) const {
550 size_type find_first_of(value_type c, size_t pos) const {
555 * Determine whether the range contains the given subrange or item.
557 * Note: Call find() directly if the index is needed.
559 bool contains(const const_range_type& other) const {
560 return find(other) != std::string::npos;
563 bool contains(const value_type& other) const {
564 return find(other) != std::string::npos;
567 void swap(Range& rhs) {
568 std::swap(b_, rhs.b_);
569 std::swap(e_, rhs.e_);
573 * Does this Range start with another range?
575 bool startsWith(const const_range_type& other) const {
576 return size() >= other.size()
577 && castToConst().subpiece(0, other.size()) == other;
579 bool startsWith(value_type c) const {
580 return !empty() && front() == c;
584 * Does this Range end with another range?
586 bool endsWith(const const_range_type& other) const {
587 return size() >= other.size()
588 && castToConst().subpiece(size() - other.size()) == other;
590 bool endsWith(value_type c) const {
591 return !empty() && back() == c;
595 * Remove the given prefix and return true if the range starts with the given
596 * prefix; return false otherwise.
598 bool removePrefix(const const_range_type& prefix) {
599 return startsWith(prefix) && (b_ += prefix.size(), true);
601 bool removePrefix(value_type prefix) {
602 return startsWith(prefix) && (++b_, true);
606 * Remove the given suffix and return true if the range ends with the given
607 * suffix; return false otherwise.
609 bool removeSuffix(const const_range_type& suffix) {
610 return endsWith(suffix) && (e_ -= suffix.size(), true);
612 bool removeSuffix(value_type suffix) {
613 return endsWith(suffix) && (--e_, true);
617 * Replaces the content of the range, starting at position 'pos', with
618 * contents of 'replacement'. Entire 'replacement' must fit into the
619 * range. Returns false if 'replacements' does not fit. Example use:
621 * char in[] = "buffer";
622 * auto msp = MutablesStringPiece(input);
623 * EXPECT_TRUE(msp.replaceAt(2, "tt"));
624 * EXPECT_EQ(msp, "butter");
626 * // not enough space
627 * EXPECT_FALSE(msp.replace(msp.size() - 1, "rr"));
628 * EXPECT_EQ(msp, "butter"); // unchanged
630 bool replaceAt(size_t pos, const_range_type replacement) {
631 if (size() < pos + replacement.size()) {
635 std::copy(replacement.begin(), replacement.end(), begin() + pos);
641 * Replaces all occurences of 'source' with 'dest'. Returns number
642 * of replacements made. Source and dest have to have the same
643 * length. Throws if the lengths are different. If 'source' is a
644 * pattern that is overlapping with itself, we perform sequential
645 * replacement: "aaaaaaa".replaceAll("aa", "ba") --> "bababaa"
649 * char in[] = "buffer";
650 * auto msp = MutablesStringPiece(input);
651 * EXPECT_EQ(msp.replaceAll("ff","tt"), 1);
652 * EXPECT_EQ(msp, "butter");
654 size_t replaceAll(const_range_type source, const_range_type dest) {
655 if (source.size() != dest.size()) {
656 throw std::invalid_argument(
657 "replacement must have the same size as source");
665 size_t num_replaced = 0;
666 size_type found = std::string::npos;
667 while ((found = find(source, pos)) != std::string::npos) {
668 replaceAt(found, dest);
669 pos += source.size();
677 * Splits this `Range` `[b, e)` in the position `i` dictated by the next
678 * occurence of `delimiter`.
680 * Returns a new `Range` `[b, i)` and adjusts this range to start right after
681 * the delimiter's position. This range will be empty if the delimiter is not
682 * found. If called on an empty `Range`, both this and the returned `Range`
687 * folly::StringPiece s("sample string for split_next");
688 * auto p = s.split_step(' ');
690 * // prints "string for split_next"
698 * void tokenize(StringPiece s, char delimiter) {
699 * while (!s.empty()) {
700 * cout << s.split_step(delimiter);
704 * @author: Marcelo Juchem <marcelo@fb.com>
706 Range split_step(value_type delimiter) {
707 auto i = std::find(b_, e_, delimiter);
710 b_ = i == e_ ? e_ : std::next(i);
715 Range split_step(Range delimiter) {
716 auto i = find(delimiter);
717 Range result(b_, i == std::string::npos ? size() : i);
719 b_ = result.end() == e_ ? e_ : std::next(result.end(), delimiter.size());
725 * Convenience method that calls `split_step()` and passes the result to a
726 * functor, returning whatever the functor does. Any additional arguments
727 * `args` passed to this function are perfectly forwarded to the functor.
729 * Say you have a functor with this signature:
731 * Foo fn(Range r) { }
733 * `split_step()`'s return type will be `Foo`. It works just like:
735 * auto result = fn(myRange.split_step(' '));
737 * A functor returning `void` is also supported.
741 * void do_some_parsing(folly::StringPiece s) {
742 * auto version = s.split_step(' ', [&](folly::StringPiece x) {
744 * throw std::invalid_argument("empty string");
746 * return std::strtoull(x.begin(), x.end(), 16);
753 * void parse(folly::StringPiece s) {
754 * s.split_step(' ', parse_field, bar, 10);
755 * s.split_step('\t', parse_field, baz, 20);
757 * auto const kludge = [](folly::StringPiece x, int &out, int def) {
761 * parse_field(x, out, def);
765 * s.split_step('\t', kludge, gaz);
766 * s.split_step(' ', kludge, foo);
775 * static parse_field(folly::StringPiece s, int &out, int def) {
777 * out = folly::to<int>(s);
778 * } catch (std::exception const &) {
784 * @author: Marcelo Juchem <marcelo@fb.com>
786 template <typename TProcess, typename... Args>
787 auto split_step(value_type 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)...); }
791 template <typename TProcess, typename... Args>
792 auto split_step(Range delimiter, TProcess &&process, Args &&...args)
793 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
794 { return process(split_step(delimiter), std::forward<Args>(args)...); }
800 template <class Iter>
801 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
804 void swap(Range<T>& lhs, Range<T>& rhs) {
809 * Create a range from two iterators, with type deduction.
811 template <class Iter>
812 Range<Iter> range(Iter first, Iter last) {
813 return Range<Iter>(first, last);
817 * Creates a range to reference the contents of a contiguous-storage container.
819 // Use pointers for types with '.data()' member
820 template <class Collection,
821 class T = typename std::remove_pointer<
822 decltype(std::declval<Collection>().data())>::type>
823 Range<T*> range(Collection&& v) {
824 return Range<T*>(v.data(), v.data() + v.size());
827 template <class T, size_t n>
828 Range<T*> range(T (&array)[n]) {
829 return Range<T*>(array, array + n);
832 typedef Range<const char*> StringPiece;
833 typedef Range<char*> MutableStringPiece;
834 typedef Range<const unsigned char*> ByteRange;
835 typedef Range<unsigned char*> MutableByteRange;
837 std::ostream& operator<<(std::ostream& os, const StringPiece piece);
838 std::ostream& operator<<(std::ostream& os, const MutableStringPiece piece);
841 * Templated comparison operators
845 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
846 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
850 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
851 return lhs.compare(rhs) < 0;
855 * Specializations of comparison operators for StringPiece
860 template <class A, class B>
861 struct ComparableAsStringPiece {
864 (std::is_convertible<A, StringPiece>::value
865 && std::is_same<B, StringPiece>::value)
867 (std::is_convertible<B, StringPiece>::value
868 && std::is_same<A, StringPiece>::value)
872 } // namespace detail
875 * operator== through conversion for Range<const char*>
877 template <class T, class U>
879 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
880 operator==(const T& lhs, const U& rhs) {
881 return StringPiece(lhs) == StringPiece(rhs);
885 * operator< through conversion for Range<const char*>
887 template <class T, class U>
889 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
890 operator<(const T& lhs, const U& rhs) {
891 return StringPiece(lhs) < StringPiece(rhs);
895 * operator> through conversion for Range<const char*>
897 template <class T, class U>
899 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
900 operator>(const T& lhs, const U& rhs) {
901 return StringPiece(lhs) > StringPiece(rhs);
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);
924 // Do NOT use this, use SpookyHashV2 instead, see commment on hash() above.
925 struct StringPieceHash {
926 std::size_t operator()(const StringPiece str) const {
927 return static_cast<std::size_t>(str.hash());
932 * Finds substrings faster than brute force by borrowing from Boyer-Moore
934 template <class T, class Comp>
935 size_t qfind(const Range<T>& haystack,
936 const Range<T>& needle,
938 // Don't use std::search, use a Boyer-Moore-like trick by comparing
939 // the last characters first
940 auto const nsize = needle.size();
941 if (haystack.size() < nsize) {
942 return std::string::npos;
944 if (!nsize) return 0;
945 auto const nsize_1 = nsize - 1;
946 auto const lastNeedle = needle[nsize_1];
948 // Boyer-Moore skip value for the last char in the needle. Zero is
949 // not a valid value; skip will be computed the first time it's
951 std::string::size_type skip = 0;
953 auto i = haystack.begin();
954 auto iEnd = haystack.end() - nsize_1;
957 // Boyer-Moore: match the last element in the needle
958 while (!eq(i[nsize_1], lastNeedle)) {
961 return std::string::npos;
964 // Here we know that the last char matches
965 // Continue in pedestrian mode
966 for (size_t j = 0; ; ) {
968 if (!eq(i[j], needle[j])) {
969 // Not found, we can skip
970 // Compute the skip value lazily
973 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
980 // Check if done searching
983 return i - haystack.begin();
987 return std::string::npos;
992 size_t qfind_first_byte_of_nosse(const StringPiece haystack,
993 const StringPiece needles);
995 #if FOLLY_HAVE_EMMINTRIN_H && __GNUC_PREREQ(4, 6)
996 size_t qfind_first_byte_of_sse42(const StringPiece haystack,
997 const StringPiece needles);
999 inline size_t qfind_first_byte_of(const StringPiece haystack,
1000 const StringPiece needles) {
1001 static auto const qfind_first_byte_of_fn =
1002 folly::CpuId().sse42() ? qfind_first_byte_of_sse42
1003 : qfind_first_byte_of_nosse;
1004 return qfind_first_byte_of_fn(haystack, needles);
1008 inline size_t qfind_first_byte_of(const StringPiece haystack,
1009 const StringPiece needles) {
1010 return qfind_first_byte_of_nosse(haystack, needles);
1012 #endif // FOLLY_HAVE_EMMINTRIN_H
1014 } // namespace detail
1016 template <class T, class Comp>
1017 size_t qfind_first_of(const Range<T> & haystack,
1018 const Range<T> & needles,
1020 auto ret = std::find_first_of(haystack.begin(), haystack.end(),
1021 needles.begin(), needles.end(),
1023 return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
1026 struct AsciiCaseSensitive {
1027 bool operator()(char lhs, char rhs) const {
1033 * Check if two ascii characters are case insensitive equal.
1034 * The difference between the lower/upper case characters are the 6-th bit.
1035 * We also check they are alpha chars, in case of xor = 32.
1037 struct AsciiCaseInsensitive {
1038 bool operator()(char lhs, char rhs) const {
1040 if (k == 0) return true;
1041 if (k != 32) return false;
1043 return (k >= 'a' && k <= 'z');
1047 extern const AsciiCaseSensitive asciiCaseSensitive;
1048 extern const AsciiCaseInsensitive asciiCaseInsensitive;
1051 size_t qfind(const Range<T>& haystack,
1052 const typename Range<T>::value_type& needle) {
1053 auto pos = std::find(haystack.begin(), haystack.end(), needle);
1054 return pos == haystack.end() ? std::string::npos : pos - haystack.data();
1058 size_t rfind(const Range<T>& haystack,
1059 const typename Range<T>::value_type& needle) {
1060 for (auto i = haystack.size(); i-- > 0; ) {
1061 if (haystack[i] == needle) {
1065 return std::string::npos;
1068 // specialization for StringPiece
1070 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
1071 auto pos = static_cast<const char*>(
1072 ::memchr(haystack.data(), needle, haystack.size()));
1073 return pos == nullptr ? std::string::npos : pos - haystack.data();
1076 #if FOLLY_HAVE_MEMRCHR
1078 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
1079 auto pos = static_cast<const char*>(
1080 ::memrchr(haystack.data(), needle, haystack.size()));
1081 return pos == nullptr ? std::string::npos : pos - haystack.data();
1085 // specialization for ByteRange
1087 inline size_t qfind(const Range<const unsigned char*>& haystack,
1088 const unsigned char& needle) {
1089 auto pos = static_cast<const unsigned char*>(
1090 ::memchr(haystack.data(), needle, haystack.size()));
1091 return pos == nullptr ? std::string::npos : pos - haystack.data();
1094 #if FOLLY_HAVE_MEMRCHR
1096 inline size_t rfind(const Range<const unsigned char*>& haystack,
1097 const unsigned char& needle) {
1098 auto pos = static_cast<const unsigned char*>(
1099 ::memrchr(haystack.data(), needle, haystack.size()));
1100 return pos == nullptr ? std::string::npos : pos - haystack.data();
1105 size_t qfind_first_of(const Range<T>& haystack,
1106 const Range<T>& needles) {
1107 return qfind_first_of(haystack, needles, asciiCaseSensitive);
1110 // specialization for StringPiece
1112 inline size_t qfind_first_of(const Range<const char*>& haystack,
1113 const Range<const char*>& needles) {
1114 return detail::qfind_first_byte_of(haystack, needles);
1117 // specialization for ByteRange
1119 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
1120 const Range<const unsigned char*>& needles) {
1121 return detail::qfind_first_byte_of(StringPiece(haystack),
1122 StringPiece(needles));
1124 } // !namespace folly
1126 #pragma GCC diagnostic pop
1128 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);
1130 #endif // FOLLY_RANGE_H_