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_() {
188 // Works for all iterators
189 constexpr Range(Iter start, Iter end) : b_(start), e_(end) {
192 // Works only for random-access iterators
193 constexpr Range(Iter start, size_t size)
194 : b_(start), e_(start + size) { }
196 #if FOLLY_HAVE_CONSTEXPR_STRLEN
197 template <class T = Iter, typename detail::IsCharPointer<T>::type = 0>
198 constexpr /* implicit */ Range(Iter str)
199 : b_(str), e_(str + strlen(str)) {}
201 template <class T = Iter, typename detail::IsCharPointer<T>::type = 0>
202 /* implicit */ Range(Iter str)
203 : b_(str), e_(str + strlen(str)) {}
205 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
206 /* implicit */ Range(const std::string& str)
207 : b_(str.data()), e_(b_ + str.size()) {}
209 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
210 Range(const std::string& str, std::string::size_type startFrom) {
211 if (UNLIKELY(startFrom > str.size())) {
212 throw std::out_of_range("index out of range");
214 b_ = str.data() + startFrom;
215 e_ = str.data() + str.size();
218 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
219 Range(const std::string& str,
220 std::string::size_type startFrom,
221 std::string::size_type size) {
222 if (UNLIKELY(startFrom > str.size())) {
223 throw std::out_of_range("index out of range");
225 b_ = str.data() + startFrom;
226 if (str.size() - startFrom < size) {
227 e_ = str.data() + str.size();
233 Range(const Range& other,
235 size_type length = npos)
236 : Range(other.subpiece(first, length))
239 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
240 /* implicit */ Range(const fbstring& str)
241 : b_(str.data()), e_(b_ + str.size()) { }
243 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
244 Range(const fbstring& str, fbstring::size_type startFrom) {
245 if (UNLIKELY(startFrom > str.size())) {
246 throw std::out_of_range("index out of range");
248 b_ = str.data() + startFrom;
249 e_ = str.data() + str.size();
252 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
253 Range(const fbstring& str, fbstring::size_type startFrom,
254 fbstring::size_type size) {
255 if (UNLIKELY(startFrom > str.size())) {
256 throw std::out_of_range("index out of range");
258 b_ = str.data() + startFrom;
259 if (str.size() - startFrom < size) {
260 e_ = str.data() + str.size();
266 // Allow implicit conversion from Range<const char*> (aka StringPiece) to
267 // Range<const unsigned char*> (aka ByteRange), as they're both frequently
268 // used to represent ranges of bytes. Allow explicit conversion in the other
270 template <class OtherIter, typename std::enable_if<
271 (std::is_same<Iter, const unsigned char*>::value &&
272 (std::is_same<OtherIter, const char*>::value ||
273 std::is_same<OtherIter, char*>::value)), int>::type = 0>
274 /* implicit */ Range(const Range<OtherIter>& other)
275 : b_(reinterpret_cast<const unsigned char*>(other.begin())),
276 e_(reinterpret_cast<const unsigned char*>(other.end())) {
279 template <class OtherIter, typename std::enable_if<
280 (std::is_same<Iter, unsigned char*>::value &&
281 std::is_same<OtherIter, char*>::value), int>::type = 0>
282 /* implicit */ Range(const Range<OtherIter>& other)
283 : b_(reinterpret_cast<unsigned char*>(other.begin())),
284 e_(reinterpret_cast<unsigned char*>(other.end())) {
287 template <class OtherIter, typename std::enable_if<
288 (std::is_same<Iter, const char*>::value &&
289 (std::is_same<OtherIter, const unsigned char*>::value ||
290 std::is_same<OtherIter, unsigned char*>::value)), int>::type = 0>
291 explicit Range(const Range<OtherIter>& other)
292 : b_(reinterpret_cast<const char*>(other.begin())),
293 e_(reinterpret_cast<const char*>(other.end())) {
296 template <class OtherIter, typename std::enable_if<
297 (std::is_same<Iter, char*>::value &&
298 std::is_same<OtherIter, unsigned char*>::value), int>::type = 0>
299 explicit Range(const Range<OtherIter>& other)
300 : b_(reinterpret_cast<char*>(other.begin())),
301 e_(reinterpret_cast<char*>(other.end())) {
304 // Allow implicit conversion from Range<From> to Range<To> if From is
305 // implicitly convertible to To.
306 template <class OtherIter, typename std::enable_if<
307 (!std::is_same<Iter, OtherIter>::value &&
308 std::is_convertible<OtherIter, Iter>::value), int>::type = 0>
309 constexpr /* implicit */ Range(const Range<OtherIter>& other)
314 // Allow explicit conversion from Range<From> to Range<To> if From is
315 // explicitly convertible to To.
316 template <class OtherIter, typename std::enable_if<
317 (!std::is_same<Iter, OtherIter>::value &&
318 !std::is_convertible<OtherIter, Iter>::value &&
319 std::is_constructible<Iter, const OtherIter&>::value), int>::type = 0>
320 constexpr explicit Range(const Range<OtherIter>& other)
330 void assign(Iter start, Iter end) {
335 void reset(Iter start, size_type size) {
340 // Works only for Range<const char*>
341 void reset(const std::string& str) {
342 reset(str.data(), str.size());
345 size_type size() const {
349 size_type walk_size() const {
351 return std::distance(b_, e_);
353 bool empty() const { return b_ == e_; }
354 Iter data() const { return b_; }
355 Iter start() const { return b_; }
356 Iter begin() const { return b_; }
357 Iter end() const { return e_; }
358 Iter cbegin() const { return b_; }
359 Iter cend() const { return e_; }
360 value_type& front() {
366 return detail::value_before(e_);
368 const value_type& front() const {
372 const value_type& back() const {
374 return detail::value_before(e_);
376 // Works only for Range<const char*> and Range<char*>
377 std::string str() const { return std::string(b_, size()); }
378 std::string toString() const { return str(); }
379 // Works only for Range<const char*> and Range<char*>
380 fbstring fbstr() const { return fbstring(b_, size()); }
381 fbstring toFbstring() const { return fbstr(); }
383 const_range_type castToConst() const {
384 return const_range_type(*this);
387 // Works only for Range<const char*> and Range<char*>
388 int compare(const const_range_type& o) const {
389 const size_type tsize = this->size();
390 const size_type osize = o.size();
391 const size_type msize = std::min(tsize, osize);
392 int r = traits_type::compare(data(), o.data(), msize);
393 if (r == 0 && tsize != osize) {
394 // We check the signed bit of the subtraction and bit shift it
395 // to produce either 0 or 2. The subtraction yields the
396 // comparison values of either -1 or 1.
397 r = (static_cast<int>(
398 (osize - tsize) >> (CHAR_BIT * sizeof(size_t) - 1)) << 1) - 1;
403 value_type& operator[](size_t i) {
404 DCHECK_GT(size(), i);
408 const value_type& operator[](size_t i) const {
409 DCHECK_GT(size(), i);
413 value_type& at(size_t i) {
414 if (i >= size()) throw std::out_of_range("index out of range");
418 const value_type& at(size_t i) const {
419 if (i >= size()) throw std::out_of_range("index out of range");
423 // Works only for Range<const char*> and Range<char*>
424 uint32_t hash() const {
425 // Taken from fbi/nstring.h:
426 // Quick and dirty bernstein hash...fine for short ascii strings
427 uint32_t hash = 5381;
428 for (size_t ix = 0; ix < size(); ix++) {
429 hash = ((hash << 5) + hash) + b_[ix];
434 void advance(size_type n) {
435 if (UNLIKELY(n > size())) {
436 throw std::out_of_range("index out of range");
441 void subtract(size_type n) {
442 if (UNLIKELY(n > size())) {
443 throw std::out_of_range("index out of range");
458 Range subpiece(size_type first, size_type length = npos) const {
459 if (UNLIKELY(first > size())) {
460 throw std::out_of_range("index out of range");
463 return Range(b_ + first, std::min(length, size() - first));
466 // string work-alike functions
467 size_type find(const_range_type str) const {
468 return qfind(castToConst(), str);
471 size_type find(const_range_type str, size_t pos) const {
472 if (pos > size()) return std::string::npos;
473 size_t ret = qfind(castToConst().subpiece(pos), str);
474 return ret == npos ? ret : ret + pos;
477 size_type find(Iter s, size_t pos, size_t n) const {
478 if (pos > size()) return std::string::npos;
479 auto forFinding = castToConst();
481 pos ? forFinding.subpiece(pos) : forFinding, const_range_type(s, n));
482 return ret == npos ? ret : ret + pos;
485 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
486 size_type find(const Iter s) const {
487 return qfind(castToConst(), const_range_type(s));
490 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
491 size_type find(const Iter s, size_t pos) const {
492 if (pos > size()) return std::string::npos;
493 size_type ret = qfind(castToConst().subpiece(pos), const_range_type(s));
494 return ret == npos ? ret : ret + pos;
497 size_type find(value_type c) const {
498 return qfind(castToConst(), c);
501 size_type rfind(value_type c) const {
502 return folly::rfind(castToConst(), c);
505 size_type find(value_type c, size_t pos) const {
506 if (pos > size()) return std::string::npos;
507 size_type ret = qfind(castToConst().subpiece(pos), c);
508 return ret == npos ? ret : ret + pos;
511 size_type find_first_of(const_range_type needles) const {
512 return qfind_first_of(castToConst(), needles);
515 size_type find_first_of(const_range_type needles, size_t pos) const {
516 if (pos > size()) return std::string::npos;
517 size_type ret = qfind_first_of(castToConst().subpiece(pos), needles);
518 return ret == npos ? ret : ret + pos;
521 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
522 size_type find_first_of(Iter needles) const {
523 return find_first_of(const_range_type(needles));
526 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
527 size_type find_first_of(Iter needles, size_t pos) const {
528 return find_first_of(const_range_type(needles), pos);
531 size_type find_first_of(Iter needles, size_t pos, size_t n) const {
532 return find_first_of(const_range_type(needles, n), pos);
535 size_type find_first_of(value_type c) const {
539 size_type find_first_of(value_type c, size_t pos) const {
544 * Determine whether the range contains the given subrange or item.
546 * Note: Call find() directly if the index is needed.
548 bool contains(const const_range_type& other) const {
549 return find(other) != std::string::npos;
552 bool contains(const value_type& other) const {
553 return find(other) != std::string::npos;
556 void swap(Range& rhs) {
557 std::swap(b_, rhs.b_);
558 std::swap(e_, rhs.e_);
562 * Does this Range start with another range?
564 bool startsWith(const const_range_type& other) const {
565 return size() >= other.size()
566 && castToConst().subpiece(0, other.size()) == other;
568 bool startsWith(value_type c) const {
569 return !empty() && front() == c;
573 * Does this Range end with another range?
575 bool endsWith(const const_range_type& other) const {
576 return size() >= other.size()
577 && castToConst().subpiece(size() - other.size()) == other;
579 bool endsWith(value_type c) const {
580 return !empty() && back() == c;
584 * Remove the given prefix and return true if the range starts with the given
585 * prefix; return false otherwise.
587 bool removePrefix(const const_range_type& prefix) {
588 return startsWith(prefix) && (b_ += prefix.size(), true);
590 bool removePrefix(value_type prefix) {
591 return startsWith(prefix) && (++b_, true);
595 * Remove the given suffix and return true if the range ends with the given
596 * suffix; return false otherwise.
598 bool removeSuffix(const const_range_type& suffix) {
599 return endsWith(suffix) && (e_ -= suffix.size(), true);
601 bool removeSuffix(value_type suffix) {
602 return endsWith(suffix) && (--e_, true);
606 * Replaces the content of the range, starting at position 'pos', with
607 * contents of 'replacement'. Entire 'replacement' must fit into the
608 * range. Returns false if 'replacements' does not fit. Example use:
610 * char in[] = "buffer";
611 * auto msp = MutablesStringPiece(input);
612 * EXPECT_TRUE(msp.replaceAt(2, "tt"));
613 * EXPECT_EQ(msp, "butter");
615 * // not enough space
616 * EXPECT_FALSE(msp.replace(msp.size() - 1, "rr"));
617 * EXPECT_EQ(msp, "butter"); // unchanged
619 bool replaceAt(size_t pos, const_range_type replacement) {
620 if (size() < pos + replacement.size()) {
624 std::copy(replacement.begin(), replacement.end(), begin() + pos);
630 * Replaces all occurences of 'source' with 'dest'. Returns number
631 * of replacements made. Source and dest have to have the same
632 * length. Throws if the lengths are different. If 'source' is a
633 * pattern that is overlapping with itself, we perform sequential
634 * replacement: "aaaaaaa".replaceAll("aa", "ba") --> "bababaa"
638 * char in[] = "buffer";
639 * auto msp = MutablesStringPiece(input);
640 * EXPECT_EQ(msp.replaceAll("ff","tt"), 1);
641 * EXPECT_EQ(msp, "butter");
643 size_t replaceAll(const_range_type source, const_range_type dest) {
644 if (source.size() != dest.size()) {
645 throw std::invalid_argument(
646 "replacement must have the same size as source");
654 size_t num_replaced = 0;
655 size_type found = std::string::npos;
656 while ((found = find(source, pos)) != std::string::npos) {
657 replaceAt(found, dest);
658 pos += source.size();
666 * Splits this `Range` `[b, e)` in the position `i` dictated by the next
667 * occurence of `delimiter`.
669 * Returns a new `Range` `[b, i)` and adjusts this range to start right after
670 * the delimiter's position. This range will be empty if the delimiter is not
671 * found. If called on an empty `Range`, both this and the returned `Range`
676 * folly::StringPiece s("sample string for split_next");
677 * auto p = s.split_step(' ');
679 * // prints "string for split_next"
687 * void tokenize(StringPiece s, char delimiter) {
688 * while (!s.empty()) {
689 * cout << s.split_step(delimiter);
693 * @author: Marcelo Juchem <marcelo@fb.com>
695 Range split_step(value_type delimiter) {
696 auto i = std::find(b_, e_, delimiter);
699 b_ = i == e_ ? e_ : std::next(i);
704 Range split_step(Range delimiter) {
705 auto i = find(delimiter);
706 Range result(b_, i == std::string::npos ? size() : i);
708 b_ = result.end() == e_ ? e_ : std::next(result.end(), delimiter.size());
714 * Convenience method that calls `split_step()` and passes the result to a
715 * functor, returning whatever the functor does. Any additional arguments
716 * `args` passed to this function are perfectly forwarded to the functor.
718 * Say you have a functor with this signature:
720 * Foo fn(Range r) { }
722 * `split_step()`'s return type will be `Foo`. It works just like:
724 * auto result = fn(myRange.split_step(' '));
726 * A functor returning `void` is also supported.
730 * void do_some_parsing(folly::StringPiece s) {
731 * auto version = s.split_step(' ', [&](folly::StringPiece x) {
733 * throw std::invalid_argument("empty string");
735 * return std::strtoull(x.begin(), x.end(), 16);
742 * void parse(folly::StringPiece s) {
743 * s.split_step(' ', parse_field, bar, 10);
744 * s.split_step('\t', parse_field, baz, 20);
746 * auto const kludge = [](folly::StringPiece x, int &out, int def) {
750 * parse_field(x, out, def);
754 * s.split_step('\t', kludge, gaz);
755 * s.split_step(' ', kludge, foo);
764 * static parse_field(folly::StringPiece s, int &out, int def) {
766 * out = folly::to<int>(s);
767 * } catch (std::exception const &) {
773 * @author: Marcelo Juchem <marcelo@fb.com>
775 template <typename TProcess, typename... Args>
776 auto split_step(value_type delimiter, TProcess &&process, Args &&...args)
777 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
778 { return process(split_step(delimiter), std::forward<Args>(args)...); }
780 template <typename TProcess, typename... Args>
781 auto split_step(Range delimiter, TProcess &&process, Args &&...args)
782 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
783 { return process(split_step(delimiter), std::forward<Args>(args)...); }
789 template <class Iter>
790 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
793 void swap(Range<T>& lhs, Range<T>& rhs) {
798 * Create a range from two iterators, with type deduction.
800 template <class Iter>
801 Range<Iter> range(Iter first, Iter last) {
802 return Range<Iter>(first, last);
806 * Creates a range to reference the contents of a contiguous-storage container.
808 // Use pointers for types with '.data()' member
809 template <class Collection,
810 class T = typename std::remove_pointer<
811 decltype(std::declval<Collection>().data())>::type>
812 Range<T*> range(Collection&& v) {
813 return Range<T*>(v.data(), v.data() + v.size());
816 template <class T, size_t n>
817 Range<T*> range(T (&array)[n]) {
818 return Range<T*>(array, array + n);
821 typedef Range<const char*> StringPiece;
822 typedef Range<char*> MutableStringPiece;
823 typedef Range<const unsigned char*> ByteRange;
824 typedef Range<unsigned char*> MutableByteRange;
826 std::ostream& operator<<(std::ostream& os, const StringPiece piece);
827 std::ostream& operator<<(std::ostream& os, const MutableStringPiece piece);
830 * Templated comparison operators
834 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
835 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
839 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
840 return lhs.compare(rhs) < 0;
844 * Specializations of comparison operators for StringPiece
849 template <class A, class B>
850 struct ComparableAsStringPiece {
853 (std::is_convertible<A, StringPiece>::value
854 && std::is_same<B, StringPiece>::value)
856 (std::is_convertible<B, StringPiece>::value
857 && std::is_same<A, StringPiece>::value)
861 } // namespace detail
864 * operator== through conversion for Range<const char*>
866 template <class T, class U>
868 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
869 operator==(const T& lhs, const U& rhs) {
870 return StringPiece(lhs) == StringPiece(rhs);
874 * operator< through conversion for Range<const char*>
876 template <class T, class U>
878 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
879 operator<(const T& lhs, const U& rhs) {
880 return StringPiece(lhs) < StringPiece(rhs);
884 * operator> through conversion for Range<const char*>
886 template <class T, class U>
888 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
889 operator>(const T& lhs, const U& rhs) {
890 return StringPiece(lhs) > StringPiece(rhs);
894 * operator< through conversion for Range<const char*>
896 template <class T, class U>
898 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
899 operator<=(const T& lhs, const U& rhs) {
900 return StringPiece(lhs) <= StringPiece(rhs);
904 * operator> through conversion for Range<const char*>
906 template <class T, class U>
908 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
909 operator>=(const T& lhs, const U& rhs) {
910 return StringPiece(lhs) >= StringPiece(rhs);
913 struct StringPieceHash {
914 std::size_t operator()(const StringPiece str) const {
915 return static_cast<std::size_t>(str.hash());
920 * Finds substrings faster than brute force by borrowing from Boyer-Moore
922 template <class T, class Comp>
923 size_t qfind(const Range<T>& haystack,
924 const Range<T>& needle,
926 // Don't use std::search, use a Boyer-Moore-like trick by comparing
927 // the last characters first
928 auto const nsize = needle.size();
929 if (haystack.size() < nsize) {
930 return std::string::npos;
932 if (!nsize) return 0;
933 auto const nsize_1 = nsize - 1;
934 auto const lastNeedle = needle[nsize_1];
936 // Boyer-Moore skip value for the last char in the needle. Zero is
937 // not a valid value; skip will be computed the first time it's
939 std::string::size_type skip = 0;
941 auto i = haystack.begin();
942 auto iEnd = haystack.end() - nsize_1;
945 // Boyer-Moore: match the last element in the needle
946 while (!eq(i[nsize_1], lastNeedle)) {
949 return std::string::npos;
952 // Here we know that the last char matches
953 // Continue in pedestrian mode
954 for (size_t j = 0; ; ) {
956 if (!eq(i[j], needle[j])) {
957 // Not found, we can skip
958 // Compute the skip value lazily
961 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
968 // Check if done searching
971 return i - haystack.begin();
975 return std::string::npos;
980 size_t qfind_first_byte_of_nosse(const StringPiece haystack,
981 const StringPiece needles);
983 #if FOLLY_HAVE_EMMINTRIN_H && __GNUC_PREREQ(4, 6)
984 size_t qfind_first_byte_of_sse42(const StringPiece haystack,
985 const StringPiece needles);
987 inline size_t qfind_first_byte_of(const StringPiece haystack,
988 const StringPiece needles) {
989 static auto const qfind_first_byte_of_fn =
990 folly::CpuId().sse42() ? qfind_first_byte_of_sse42
991 : qfind_first_byte_of_nosse;
992 return qfind_first_byte_of_fn(haystack, needles);
996 inline size_t qfind_first_byte_of(const StringPiece haystack,
997 const StringPiece needles) {
998 return qfind_first_byte_of_nosse(haystack, needles);
1000 #endif // FOLLY_HAVE_EMMINTRIN_H
1002 } // namespace detail
1004 template <class T, class Comp>
1005 size_t qfind_first_of(const Range<T> & haystack,
1006 const Range<T> & needles,
1008 auto ret = std::find_first_of(haystack.begin(), haystack.end(),
1009 needles.begin(), needles.end(),
1011 return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
1014 struct AsciiCaseSensitive {
1015 bool operator()(char lhs, char rhs) const {
1021 * Check if two ascii characters are case insensitive equal.
1022 * The difference between the lower/upper case characters are the 6-th bit.
1023 * We also check they are alpha chars, in case of xor = 32.
1025 struct AsciiCaseInsensitive {
1026 bool operator()(char lhs, char rhs) const {
1028 if (k == 0) return true;
1029 if (k != 32) return false;
1031 return (k >= 'a' && k <= 'z');
1035 extern const AsciiCaseSensitive asciiCaseSensitive;
1036 extern const AsciiCaseInsensitive asciiCaseInsensitive;
1039 size_t qfind(const Range<T>& haystack,
1040 const typename Range<T>::value_type& needle) {
1041 auto pos = std::find(haystack.begin(), haystack.end(), needle);
1042 return pos == haystack.end() ? std::string::npos : pos - haystack.data();
1046 size_t rfind(const Range<T>& haystack,
1047 const typename Range<T>::value_type& needle) {
1048 for (auto i = haystack.size(); i-- > 0; ) {
1049 if (haystack[i] == needle) {
1053 return std::string::npos;
1056 // specialization for StringPiece
1058 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
1059 auto pos = static_cast<const char*>(
1060 ::memchr(haystack.data(), needle, haystack.size()));
1061 return pos == nullptr ? std::string::npos : pos - haystack.data();
1064 #if FOLLY_HAVE_MEMRCHR
1066 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
1067 auto pos = static_cast<const char*>(
1068 ::memrchr(haystack.data(), needle, haystack.size()));
1069 return pos == nullptr ? std::string::npos : pos - haystack.data();
1073 // specialization for ByteRange
1075 inline size_t qfind(const Range<const unsigned char*>& haystack,
1076 const unsigned char& needle) {
1077 auto pos = static_cast<const unsigned char*>(
1078 ::memchr(haystack.data(), needle, haystack.size()));
1079 return pos == nullptr ? std::string::npos : pos - haystack.data();
1082 #if FOLLY_HAVE_MEMRCHR
1084 inline size_t rfind(const Range<const unsigned char*>& haystack,
1085 const unsigned char& needle) {
1086 auto pos = static_cast<const unsigned char*>(
1087 ::memrchr(haystack.data(), needle, haystack.size()));
1088 return pos == nullptr ? std::string::npos : pos - haystack.data();
1093 size_t qfind_first_of(const Range<T>& haystack,
1094 const Range<T>& needles) {
1095 return qfind_first_of(haystack, needles, asciiCaseSensitive);
1098 // specialization for StringPiece
1100 inline size_t qfind_first_of(const Range<const char*>& haystack,
1101 const Range<const char*>& needles) {
1102 return detail::qfind_first_byte_of(haystack, needles);
1105 // specialization for ByteRange
1107 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
1108 const Range<const unsigned char*>& needles) {
1109 return detail::qfind_first_byte_of(StringPiece(haystack),
1110 StringPiece(needles));
1112 } // !namespace folly
1114 #pragma GCC diagnostic pop
1116 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);
1118 #endif // FOLLY_RANGE_H_