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>
28 #include <glog/logging.h>
32 #include <type_traits>
34 // libc++ doesn't provide this header, nor does msvc
35 #ifdef FOLLY_HAVE_BITS_CXXCONFIG_H
36 // This file appears in two locations: inside fbcode and in the
37 // libstdc++ source code (when embedding fbstring as std::string).
38 // To aid in this schizophrenic use, two macros are defined in
40 // _LIBSTDCXX_FBSTRING - Set inside libstdc++. This is useful to
41 // gate use inside fbcode v. libstdc++
42 #include <bits/c++config.h>
45 #include <folly/CpuId.h>
46 #include <folly/Traits.h>
47 #include <folly/Likely.h>
49 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
50 #pragma GCC diagnostic push
51 #pragma GCC diagnostic ignored "-Wshadow"
55 template <class T> class Range;
58 * Finds the first occurrence of needle in haystack. The algorithm is on
59 * average faster than O(haystack.size() * needle.size()) but not as fast
60 * as Boyer-Moore. On the upside, it does not do any upfront
61 * preprocessing and does not allocate memory.
63 template <class T, class Comp = std::equal_to<typename Range<T>::value_type>>
64 inline size_t qfind(const Range<T> & haystack,
65 const Range<T> & needle,
69 * Finds the first occurrence of needle in haystack. The result is the
70 * offset reported to the beginning of haystack, or string::npos if
71 * needle wasn't found.
74 size_t qfind(const Range<T> & haystack,
75 const typename Range<T>::value_type& needle);
78 * Finds the last occurrence of needle in haystack. The result is the
79 * offset reported to the beginning of haystack, or string::npos if
80 * needle wasn't found.
83 size_t rfind(const Range<T> & haystack,
84 const typename Range<T>::value_type& needle);
88 * Finds the first occurrence of any element of needle in
89 * haystack. The algorithm is O(haystack.size() * needle.size()).
92 inline size_t qfind_first_of(const Range<T> & haystack,
93 const Range<T> & needle);
96 * Small internal helper - returns the value just before an iterator.
101 * For random-access iterators, the value before is simply i[-1].
103 template <class Iter>
104 typename std::enable_if<
105 std::is_same<typename std::iterator_traits<Iter>::iterator_category,
106 std::random_access_iterator_tag>::value,
107 typename std::iterator_traits<Iter>::reference>::type
108 value_before(Iter i) {
113 * For all other iterators, we need to use the decrement operator.
115 template <class Iter>
116 typename std::enable_if<
117 !std::is_same<typename std::iterator_traits<Iter>::iterator_category,
118 std::random_access_iterator_tag>::value,
119 typename std::iterator_traits<Iter>::reference>::type
120 value_before(Iter i) {
125 * Use IsCharPointer<T>::type to enable const char* or char*.
126 * Use IsCharPointer<T>::const_type to enable only const char*.
128 template <class T> struct IsCharPointer {};
131 struct IsCharPointer<char*> {
136 struct IsCharPointer<const char*> {
137 typedef int const_type;
141 } // namespace detail
144 * Range abstraction keeping a pair of iterators. We couldn't use
145 * boost's similar range abstraction because we need an API identical
146 * with the former StringPiece class, which is used by a lot of other
147 * code. This abstraction does fulfill the needs of boost's
148 * range-oriented algorithms though.
150 * (Keep memory lifetime in mind when using this class, since it
151 * doesn't manage the data it refers to - just like an iterator
154 template <class Iter>
155 class Range : private boost::totally_ordered<Range<Iter> > {
157 typedef std::size_t size_type;
158 typedef Iter iterator;
159 typedef Iter const_iterator;
160 typedef typename std::remove_reference<
161 typename std::iterator_traits<Iter>::reference>::type
163 typedef typename std::iterator_traits<Iter>::reference reference;
166 * For MutableStringPiece and MutableByteRange we define StringPiece
167 * and ByteRange as const_range_type (for everything else its just
168 * identity). We do that to enable operations such as find with
169 * args which are const.
171 typedef typename std::conditional<
172 std::is_same<Iter, char*>::value
173 || std::is_same<Iter, unsigned char*>::value,
174 Range<const value_type*>,
175 Range<Iter>>::type const_range_type;
177 typedef std::char_traits<typename std::remove_const<value_type>::type>
180 static const size_type npos;
182 // Works for all iterators
183 constexpr Range() : b_(), e_() {
187 // Works for all iterators
188 constexpr Range(Iter start, Iter end) : b_(start), e_(end) {
191 // Works only for random-access iterators
192 constexpr Range(Iter start, size_t size)
193 : b_(start), e_(start + size) { }
195 #if FOLLY_HAVE_CONSTEXPR_STRLEN
196 template <class T = Iter, typename detail::IsCharPointer<T>::type = 0>
197 constexpr /* implicit */ Range(Iter str)
198 : b_(str), e_(str + strlen(str)) {}
200 template <class T = Iter, typename detail::IsCharPointer<T>::type = 0>
201 /* implicit */ Range(Iter str)
202 : b_(str), e_(str + strlen(str)) {}
204 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
205 /* implicit */ Range(const std::string& str)
206 : b_(str.data()), e_(b_ + str.size()) {}
208 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
209 Range(const std::string& str, std::string::size_type startFrom) {
210 if (UNLIKELY(startFrom > str.size())) {
211 throw std::out_of_range("index out of range");
213 b_ = str.data() + startFrom;
214 e_ = str.data() + str.size();
217 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
218 Range(const std::string& str,
219 std::string::size_type startFrom,
220 std::string::size_type size) {
221 if (UNLIKELY(startFrom > str.size())) {
222 throw std::out_of_range("index out of range");
224 b_ = str.data() + startFrom;
225 if (str.size() - startFrom < size) {
226 e_ = str.data() + str.size();
232 Range(const Range& other,
234 size_type length = npos)
235 : Range(other.subpiece(first, length))
238 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
239 /* implicit */ Range(const fbstring& str)
240 : b_(str.data()), e_(b_ + str.size()) { }
242 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
243 Range(const fbstring& str, fbstring::size_type startFrom) {
244 if (UNLIKELY(startFrom > str.size())) {
245 throw std::out_of_range("index out of range");
247 b_ = str.data() + startFrom;
248 e_ = str.data() + str.size();
251 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
252 Range(const fbstring& str, fbstring::size_type startFrom,
253 fbstring::size_type size) {
254 if (UNLIKELY(startFrom > str.size())) {
255 throw std::out_of_range("index out of range");
257 b_ = str.data() + startFrom;
258 if (str.size() - startFrom < size) {
259 e_ = str.data() + str.size();
265 // Allow implicit conversion from Range<const char*> (aka StringPiece) to
266 // Range<const unsigned char*> (aka ByteRange), as they're both frequently
267 // used to represent ranges of bytes. Allow explicit conversion in the other
269 template <class OtherIter, typename std::enable_if<
270 (std::is_same<Iter, const unsigned char*>::value &&
271 (std::is_same<OtherIter, const char*>::value ||
272 std::is_same<OtherIter, char*>::value)), int>::type = 0>
273 /* implicit */ Range(const Range<OtherIter>& other)
274 : b_(reinterpret_cast<const unsigned char*>(other.begin())),
275 e_(reinterpret_cast<const unsigned char*>(other.end())) {
278 template <class OtherIter, typename std::enable_if<
279 (std::is_same<Iter, unsigned char*>::value &&
280 std::is_same<OtherIter, char*>::value), int>::type = 0>
281 /* implicit */ Range(const Range<OtherIter>& other)
282 : b_(reinterpret_cast<unsigned char*>(other.begin())),
283 e_(reinterpret_cast<unsigned char*>(other.end())) {
286 template <class OtherIter, typename std::enable_if<
287 (std::is_same<Iter, const char*>::value &&
288 (std::is_same<OtherIter, const unsigned char*>::value ||
289 std::is_same<OtherIter, unsigned char*>::value)), int>::type = 0>
290 explicit Range(const Range<OtherIter>& other)
291 : b_(reinterpret_cast<const char*>(other.begin())),
292 e_(reinterpret_cast<const char*>(other.end())) {
295 template <class OtherIter, typename std::enable_if<
296 (std::is_same<Iter, char*>::value &&
297 std::is_same<OtherIter, unsigned char*>::value), int>::type = 0>
298 explicit Range(const Range<OtherIter>& other)
299 : b_(reinterpret_cast<char*>(other.begin())),
300 e_(reinterpret_cast<char*>(other.end())) {
303 // Allow implicit conversion from Range<From> to Range<To> if From is
304 // implicitly convertible to To.
305 template <class OtherIter, typename std::enable_if<
306 (!std::is_same<Iter, OtherIter>::value &&
307 std::is_convertible<OtherIter, Iter>::value), int>::type = 0>
308 constexpr /* implicit */ Range(const Range<OtherIter>& other)
313 // Allow explicit conversion from Range<From> to Range<To> if From is
314 // explicitly 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 &&
318 std::is_constructible<Iter, const OtherIter&>::value), int>::type = 0>
319 constexpr explicit Range(const Range<OtherIter>& other)
329 void assign(Iter start, Iter end) {
334 void reset(Iter start, size_type size) {
339 // Works only for Range<const char*>
340 void reset(const std::string& str) {
341 reset(str.data(), str.size());
344 size_type size() const {
348 size_type walk_size() const {
350 return std::distance(b_, e_);
352 bool empty() const { return b_ == e_; }
353 Iter data() const { return b_; }
354 Iter start() const { return b_; }
355 Iter begin() const { return b_; }
356 Iter end() const { return e_; }
357 Iter cbegin() const { return b_; }
358 Iter cend() const { return e_; }
359 value_type& front() {
365 return detail::value_before(e_);
367 const value_type& front() const {
371 const value_type& back() const {
373 return detail::value_before(e_);
375 // Works only for Range<const char*> and Range<char*>
376 std::string str() const { return std::string(b_, size()); }
377 std::string toString() const { return str(); }
378 // Works only for Range<const char*> and Range<char*>
379 fbstring fbstr() const { return fbstring(b_, size()); }
380 fbstring toFbstring() const { return fbstr(); }
382 const_range_type castToConst() const {
383 return const_range_type(*this);
386 // Works only for Range<const char*> and Range<char*>
387 int compare(const const_range_type& o) const {
388 const size_type tsize = this->size();
389 const size_type osize = o.size();
390 const size_type msize = std::min(tsize, osize);
391 int r = traits_type::compare(data(), o.data(), msize);
392 if (r == 0 && tsize != osize) {
393 // We check the signed bit of the subtraction and bit shift it
394 // to produce either 0 or 2. The subtraction yields the
395 // comparison values of either -1 or 1.
396 r = (static_cast<int>(
397 (osize - tsize) >> (CHAR_BIT * sizeof(size_t) - 1)) << 1) - 1;
402 value_type& operator[](size_t i) {
403 DCHECK_GT(size(), i);
407 const value_type& operator[](size_t i) const {
408 DCHECK_GT(size(), i);
412 value_type& at(size_t i) {
413 if (i >= size()) throw std::out_of_range("index out of range");
417 const value_type& at(size_t i) const {
418 if (i >= size()) throw std::out_of_range("index out of range");
422 // Works only for Range<const char*> and Range<char*>
423 uint32_t hash() const {
424 // Taken from fbi/nstring.h:
425 // Quick and dirty bernstein hash...fine for short ascii strings
426 uint32_t hash = 5381;
427 for (size_t ix = 0; ix < size(); ix++) {
428 hash = ((hash << 5) + hash) + b_[ix];
433 void advance(size_type n) {
434 if (UNLIKELY(n > size())) {
435 throw std::out_of_range("index out of range");
440 void subtract(size_type n) {
441 if (UNLIKELY(n > size())) {
442 throw std::out_of_range("index out of range");
457 Range subpiece(size_type first, size_type length = npos) const {
458 if (UNLIKELY(first > size())) {
459 throw std::out_of_range("index out of range");
462 return Range(b_ + first, std::min(length, size() - first));
465 // string work-alike functions
466 size_type find(const_range_type str) const {
467 return qfind(castToConst(), str);
470 size_type find(const_range_type str, size_t pos) const {
471 if (pos > size()) return std::string::npos;
472 size_t ret = qfind(castToConst().subpiece(pos), str);
473 return ret == npos ? ret : ret + pos;
476 size_type find(Iter s, size_t pos, size_t n) const {
477 if (pos > size()) return std::string::npos;
478 auto forFinding = castToConst();
480 pos ? forFinding.subpiece(pos) : forFinding, const_range_type(s, n));
481 return ret == npos ? ret : ret + pos;
484 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
485 size_type find(const Iter s) const {
486 return qfind(castToConst(), const_range_type(s));
489 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
490 size_type find(const Iter s, size_t pos) const {
491 if (pos > size()) return std::string::npos;
492 size_type ret = qfind(castToConst().subpiece(pos), const_range_type(s));
493 return ret == npos ? ret : ret + pos;
496 size_type find(value_type c) const {
497 return qfind(castToConst(), c);
500 size_type rfind(value_type c) const {
501 return folly::rfind(castToConst(), c);
504 size_type find(value_type c, size_t pos) const {
505 if (pos > size()) return std::string::npos;
506 size_type ret = qfind(castToConst().subpiece(pos), c);
507 return ret == npos ? ret : ret + pos;
510 size_type find_first_of(const_range_type needles) const {
511 return qfind_first_of(castToConst(), needles);
514 size_type find_first_of(const_range_type needles, size_t pos) const {
515 if (pos > size()) return std::string::npos;
516 size_type ret = qfind_first_of(castToConst().subpiece(pos), needles);
517 return ret == npos ? ret : ret + pos;
520 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
521 size_type find_first_of(Iter needles) const {
522 return find_first_of(const_range_type(needles));
525 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
526 size_type find_first_of(Iter needles, size_t pos) const {
527 return find_first_of(const_range_type(needles), pos);
530 size_type find_first_of(Iter needles, size_t pos, size_t n) const {
531 return find_first_of(const_range_type(needles, n), pos);
534 size_type find_first_of(value_type c) const {
538 size_type find_first_of(value_type c, size_t pos) const {
543 * Determine whether the range contains the given subrange or item.
545 * Note: Call find() directly if the index is needed.
547 bool contains(const const_range_type& other) const {
548 return find(other) != std::string::npos;
551 bool contains(const value_type& other) const {
552 return find(other) != std::string::npos;
555 void swap(Range& rhs) {
556 std::swap(b_, rhs.b_);
557 std::swap(e_, rhs.e_);
561 * Does this Range start with another range?
563 bool startsWith(const const_range_type& other) const {
564 return size() >= other.size()
565 && castToConst().subpiece(0, other.size()) == other;
567 bool startsWith(value_type c) const {
568 return !empty() && front() == c;
572 * Does this Range end with another range?
574 bool endsWith(const const_range_type& other) const {
575 return size() >= other.size()
576 && castToConst().subpiece(size() - other.size()) == other;
578 bool endsWith(value_type c) const {
579 return !empty() && back() == c;
583 * Remove the given prefix and return true if the range starts with the given
584 * prefix; return false otherwise.
586 bool removePrefix(const const_range_type& prefix) {
587 return startsWith(prefix) && (b_ += prefix.size(), true);
589 bool removePrefix(value_type prefix) {
590 return startsWith(prefix) && (++b_, true);
594 * Remove the given suffix and return true if the range ends with the given
595 * suffix; return false otherwise.
597 bool removeSuffix(const const_range_type& suffix) {
598 return endsWith(suffix) && (e_ -= suffix.size(), true);
600 bool removeSuffix(value_type suffix) {
601 return endsWith(suffix) && (--e_, true);
605 * Replaces the content of the range, starting at position 'pos', with
606 * contents of 'replacement'. Entire 'replacement' must fit into the
607 * range. Returns false if 'replacements' does not fit. Example use:
609 * char in[] = "buffer";
610 * auto msp = MutablesStringPiece(input);
611 * EXPECT_TRUE(msp.replaceAt(2, "tt"));
612 * EXPECT_EQ(msp, "butter");
614 * // not enough space
615 * EXPECT_FALSE(msp.replace(msp.size() - 1, "rr"));
616 * EXPECT_EQ(msp, "butter"); // unchanged
618 bool replaceAt(size_t pos, const_range_type replacement) {
619 if (size() < pos + replacement.size()) {
623 std::copy(replacement.begin(), replacement.end(), begin() + pos);
629 * Replaces all occurences of 'source' with 'dest'. Returns number
630 * of replacements made. Source and dest have to have the same
631 * length. Throws if the lengths are different. If 'source' is a
632 * pattern that is overlapping with itself, we perform sequential
633 * replacement: "aaaaaaa".replaceAll("aa", "ba") --> "bababaa"
637 * char in[] = "buffer";
638 * auto msp = MutablesStringPiece(input);
639 * EXPECT_EQ(msp.replaceAll("ff","tt"), 1);
640 * EXPECT_EQ(msp, "butter");
642 size_t replaceAll(const_range_type source, const_range_type dest) {
643 if (source.size() != dest.size()) {
644 throw std::invalid_argument(
645 "replacement must have the same size as source");
653 size_t num_replaced = 0;
654 size_type found = std::string::npos;
655 while ((found = find(source, pos)) != std::string::npos) {
656 replaceAt(found, dest);
657 pos += source.size();
665 * Splits this `Range` `[b, e)` in the position `i` dictated by the next
666 * occurence of `delimiter`.
668 * Returns a new `Range` `[b, i)` and adjusts this range to start right after
669 * the delimiter's position. This range will be empty if the delimiter is not
670 * found. If called on an empty `Range`, both this and the returned `Range`
675 * folly::StringPiece s("sample string for split_next");
676 * auto p = s.split_step(' ');
678 * // prints "string for split_next"
686 * void tokenize(StringPiece s, char delimiter) {
687 * while (!s.empty()) {
688 * cout << s.split_step(delimiter);
692 * @author: Marcelo Juchem <marcelo@fb.com>
694 Range split_step(value_type delimiter) {
695 auto i = std::find(b_, e_, delimiter);
698 b_ = i == e_ ? e_ : std::next(i);
703 Range split_step(Range delimiter) {
704 auto i = find(delimiter);
705 Range result(b_, i == std::string::npos ? size() : i);
707 b_ = result.end() == e_ ? e_ : std::next(result.end(), delimiter.size());
713 * Convenience method that calls `split_step()` and passes the result to a
714 * functor, returning whatever the functor does. Any additional arguments
715 * `args` passed to this function are perfectly forwarded to the functor.
717 * Say you have a functor with this signature:
719 * Foo fn(Range r) { }
721 * `split_step()`'s return type will be `Foo`. It works just like:
723 * auto result = fn(myRange.split_step(' '));
725 * A functor returning `void` is also supported.
729 * void do_some_parsing(folly::StringPiece s) {
730 * auto version = s.split_step(' ', [&](folly::StringPiece x) {
732 * throw std::invalid_argument("empty string");
734 * return std::strtoull(x.begin(), x.end(), 16);
741 * void parse(folly::StringPiece s) {
742 * s.split_step(' ', parse_field, bar, 10);
743 * s.split_step('\t', parse_field, baz, 20);
745 * auto const kludge = [](folly::StringPiece x, int &out, int def) {
749 * parse_field(x, out, def);
753 * s.split_step('\t', kludge, gaz);
754 * s.split_step(' ', kludge, foo);
763 * static parse_field(folly::StringPiece s, int &out, int def) {
765 * out = folly::to<int>(s);
766 * } catch (std::exception const &) {
772 * @author: Marcelo Juchem <marcelo@fb.com>
774 template <typename TProcess, typename... Args>
775 auto split_step(value_type delimiter, TProcess &&process, Args &&...args)
776 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
777 { return process(split_step(delimiter), std::forward<Args>(args)...); }
779 template <typename TProcess, typename... Args>
780 auto split_step(Range delimiter, TProcess &&process, Args &&...args)
781 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
782 { return process(split_step(delimiter), std::forward<Args>(args)...); }
788 template <class Iter>
789 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
792 void swap(Range<T>& lhs, Range<T>& rhs) {
797 * Create a range from two iterators, with type deduction.
799 template <class Iter>
800 Range<Iter> range(Iter first, Iter last) {
801 return Range<Iter>(first, last);
805 * Creates a range to reference the contents of a contiguous-storage container.
807 // Use pointers for types with '.data()' member
808 template <class Collection,
809 class T = typename std::remove_pointer<
810 decltype(std::declval<Collection>().data())>::type>
811 Range<T*> range(Collection&& v) {
812 return Range<T*>(v.data(), v.data() + v.size());
815 template <class T, size_t n>
816 Range<T*> range(T (&array)[n]) {
817 return Range<T*>(array, array + n);
820 typedef Range<const char*> StringPiece;
821 typedef Range<char*> MutableStringPiece;
822 typedef Range<const unsigned char*> ByteRange;
823 typedef Range<unsigned char*> MutableByteRange;
825 std::ostream& operator<<(std::ostream& os, const StringPiece piece);
826 std::ostream& operator<<(std::ostream& os, const MutableStringPiece piece);
829 * Templated comparison operators
833 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
834 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
838 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
839 return lhs.compare(rhs) < 0;
843 * Specializations of comparison operators for StringPiece
848 template <class A, class B>
849 struct ComparableAsStringPiece {
852 (std::is_convertible<A, StringPiece>::value
853 && std::is_same<B, StringPiece>::value)
855 (std::is_convertible<B, StringPiece>::value
856 && std::is_same<A, StringPiece>::value)
860 } // namespace detail
863 * operator== through conversion for Range<const char*>
865 template <class T, class U>
867 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
868 operator==(const T& lhs, const U& rhs) {
869 return StringPiece(lhs) == StringPiece(rhs);
873 * operator< through conversion for Range<const char*>
875 template <class T, class U>
877 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
878 operator<(const T& lhs, const U& rhs) {
879 return StringPiece(lhs) < StringPiece(rhs);
883 * operator> through conversion for Range<const char*>
885 template <class T, class U>
887 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
888 operator>(const T& lhs, const U& rhs) {
889 return StringPiece(lhs) > StringPiece(rhs);
893 * operator< through conversion for Range<const char*>
895 template <class T, class U>
897 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
898 operator<=(const T& lhs, const U& rhs) {
899 return StringPiece(lhs) <= StringPiece(rhs);
903 * operator> through conversion for Range<const char*>
905 template <class T, class U>
907 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
908 operator>=(const T& lhs, const U& rhs) {
909 return StringPiece(lhs) >= StringPiece(rhs);
912 struct StringPieceHash {
913 std::size_t operator()(const StringPiece str) const {
914 return static_cast<std::size_t>(str.hash());
919 * Finds substrings faster than brute force by borrowing from Boyer-Moore
921 template <class T, class Comp>
922 size_t qfind(const Range<T>& haystack,
923 const Range<T>& needle,
925 // Don't use std::search, use a Boyer-Moore-like trick by comparing
926 // the last characters first
927 auto const nsize = needle.size();
928 if (haystack.size() < nsize) {
929 return std::string::npos;
931 if (!nsize) return 0;
932 auto const nsize_1 = nsize - 1;
933 auto const lastNeedle = needle[nsize_1];
935 // Boyer-Moore skip value for the last char in the needle. Zero is
936 // not a valid value; skip will be computed the first time it's
938 std::string::size_type skip = 0;
940 auto i = haystack.begin();
941 auto iEnd = haystack.end() - nsize_1;
944 // Boyer-Moore: match the last element in the needle
945 while (!eq(i[nsize_1], lastNeedle)) {
948 return std::string::npos;
951 // Here we know that the last char matches
952 // Continue in pedestrian mode
953 for (size_t j = 0; ; ) {
955 if (!eq(i[j], needle[j])) {
956 // Not found, we can skip
957 // Compute the skip value lazily
960 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
967 // Check if done searching
970 return i - haystack.begin();
974 return std::string::npos;
979 size_t qfind_first_byte_of_nosse(const StringPiece haystack,
980 const StringPiece needles);
982 #if FOLLY_HAVE_EMMINTRIN_H && __GNUC_PREREQ(4, 6)
983 size_t qfind_first_byte_of_sse42(const StringPiece haystack,
984 const StringPiece needles);
986 inline size_t qfind_first_byte_of(const StringPiece haystack,
987 const StringPiece needles) {
988 static auto const qfind_first_byte_of_fn =
989 folly::CpuId().sse42() ? qfind_first_byte_of_sse42
990 : qfind_first_byte_of_nosse;
991 return qfind_first_byte_of_fn(haystack, needles);
995 inline size_t qfind_first_byte_of(const StringPiece haystack,
996 const StringPiece needles) {
997 return qfind_first_byte_of_nosse(haystack, needles);
999 #endif // FOLLY_HAVE_EMMINTRIN_H
1001 } // namespace detail
1003 template <class T, class Comp>
1004 size_t qfind_first_of(const Range<T> & haystack,
1005 const Range<T> & needles,
1007 auto ret = std::find_first_of(haystack.begin(), haystack.end(),
1008 needles.begin(), needles.end(),
1010 return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
1013 struct AsciiCaseSensitive {
1014 bool operator()(char lhs, char rhs) const {
1020 * Check if two ascii characters are case insensitive equal.
1021 * The difference between the lower/upper case characters are the 6-th bit.
1022 * We also check they are alpha chars, in case of xor = 32.
1024 struct AsciiCaseInsensitive {
1025 bool operator()(char lhs, char rhs) const {
1027 if (k == 0) return true;
1028 if (k != 32) return false;
1030 return (k >= 'a' && k <= 'z');
1034 extern const AsciiCaseSensitive asciiCaseSensitive;
1035 extern const AsciiCaseInsensitive asciiCaseInsensitive;
1038 size_t qfind(const Range<T>& haystack,
1039 const typename Range<T>::value_type& needle) {
1040 auto pos = std::find(haystack.begin(), haystack.end(), needle);
1041 return pos == haystack.end() ? std::string::npos : pos - haystack.data();
1045 size_t rfind(const Range<T>& haystack,
1046 const typename Range<T>::value_type& needle) {
1047 for (auto i = haystack.size(); i-- > 0; ) {
1048 if (haystack[i] == needle) {
1052 return std::string::npos;
1055 // specialization for StringPiece
1057 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
1058 auto pos = static_cast<const char*>(
1059 ::memchr(haystack.data(), needle, haystack.size()));
1060 return pos == nullptr ? std::string::npos : pos - haystack.data();
1063 #if FOLLY_HAVE_MEMRCHR
1065 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
1066 auto pos = static_cast<const char*>(
1067 ::memrchr(haystack.data(), needle, haystack.size()));
1068 return pos == nullptr ? std::string::npos : pos - haystack.data();
1072 // specialization for ByteRange
1074 inline size_t qfind(const Range<const unsigned char*>& haystack,
1075 const unsigned char& needle) {
1076 auto pos = static_cast<const unsigned char*>(
1077 ::memchr(haystack.data(), needle, haystack.size()));
1078 return pos == nullptr ? std::string::npos : pos - haystack.data();
1081 #if FOLLY_HAVE_MEMRCHR
1083 inline size_t rfind(const Range<const unsigned char*>& haystack,
1084 const unsigned char& needle) {
1085 auto pos = static_cast<const unsigned char*>(
1086 ::memrchr(haystack.data(), needle, haystack.size()));
1087 return pos == nullptr ? std::string::npos : pos - haystack.data();
1092 size_t qfind_first_of(const Range<T>& haystack,
1093 const Range<T>& needles) {
1094 return qfind_first_of(haystack, needles, asciiCaseSensitive);
1097 // specialization for StringPiece
1099 inline size_t qfind_first_of(const Range<const char*>& haystack,
1100 const Range<const char*>& needles) {
1101 return detail::qfind_first_byte_of(haystack, needles);
1104 // specialization for ByteRange
1106 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
1107 const Range<const unsigned char*>& needles) {
1108 return detail::qfind_first_byte_of(StringPiece(haystack),
1109 StringPiece(needles));
1111 } // !namespace folly
1113 #pragma GCC diagnostic pop
1115 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);
1117 #endif // FOLLY_RANGE_H_