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>
25 #include <folly/SpookyHashV2.h>
28 #include <boost/operators.hpp>
31 #include <glog/logging.h>
35 #include <type_traits>
37 // libc++ doesn't provide this header, nor does msvc
38 #ifdef FOLLY_HAVE_BITS_CXXCONFIG_H
39 // This file appears in two locations: inside fbcode and in the
40 // libstdc++ source code (when embedding fbstring as std::string).
41 // To aid in this schizophrenic use, two macros are defined in
43 // _LIBSTDCXX_FBSTRING - Set inside libstdc++. This is useful to
44 // gate use inside fbcode v. libstdc++
45 #include <bits/c++config.h>
48 #include <folly/CpuId.h>
49 #include <folly/Traits.h>
50 #include <folly/Likely.h>
52 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
53 #pragma GCC diagnostic push
54 #pragma GCC diagnostic ignored "-Wshadow"
58 template <class T> class Range;
61 * Finds the first occurrence of needle in haystack. The algorithm is on
62 * average faster than O(haystack.size() * needle.size()) but not as fast
63 * as Boyer-Moore. On the upside, it does not do any upfront
64 * preprocessing and does not allocate memory.
66 template <class T, class Comp = std::equal_to<typename Range<T>::value_type>>
67 inline size_t qfind(const Range<T> & haystack,
68 const Range<T> & needle,
72 * Finds the first occurrence of needle in haystack. The result is the
73 * offset reported to the beginning of haystack, or string::npos if
74 * needle wasn't found.
77 size_t qfind(const Range<T> & haystack,
78 const typename Range<T>::value_type& needle);
81 * Finds the last occurrence of needle in haystack. The result is the
82 * offset reported to the beginning of haystack, or string::npos if
83 * needle wasn't found.
86 size_t rfind(const Range<T> & haystack,
87 const typename Range<T>::value_type& needle);
91 * Finds the first occurrence of any element of needle in
92 * haystack. The algorithm is O(haystack.size() * needle.size()).
95 inline size_t qfind_first_of(const Range<T> & haystack,
96 const Range<T> & needle);
99 * Small internal helper - returns the value just before an iterator.
104 * For random-access iterators, the value before is simply i[-1].
106 template <class Iter>
107 typename std::enable_if<
108 std::is_same<typename std::iterator_traits<Iter>::iterator_category,
109 std::random_access_iterator_tag>::value,
110 typename std::iterator_traits<Iter>::reference>::type
111 value_before(Iter i) {
116 * For all other iterators, we need to use the decrement operator.
118 template <class Iter>
119 typename std::enable_if<
120 !std::is_same<typename std::iterator_traits<Iter>::iterator_category,
121 std::random_access_iterator_tag>::value,
122 typename std::iterator_traits<Iter>::reference>::type
123 value_before(Iter i) {
128 * Use IsCharPointer<T>::type to enable const char* or char*.
129 * Use IsCharPointer<T>::const_type to enable only const char*.
131 template <class T> struct IsCharPointer {};
134 struct IsCharPointer<char*> {
139 struct IsCharPointer<const char*> {
140 typedef int const_type;
144 } // namespace detail
147 * Range abstraction keeping a pair of iterators. We couldn't use
148 * boost's similar range abstraction because we need an API identical
149 * with the former StringPiece class, which is used by a lot of other
150 * code. This abstraction does fulfill the needs of boost's
151 * range-oriented algorithms though.
153 * (Keep memory lifetime in mind when using this class, since it
154 * doesn't manage the data it refers to - just like an iterator
157 template <class Iter>
158 class Range : private boost::totally_ordered<Range<Iter> > {
160 typedef std::size_t size_type;
161 typedef Iter iterator;
162 typedef Iter const_iterator;
163 typedef typename std::remove_reference<
164 typename std::iterator_traits<Iter>::reference>::type
166 typedef typename std::iterator_traits<Iter>::reference reference;
169 * For MutableStringPiece and MutableByteRange we define StringPiece
170 * and ByteRange as const_range_type (for everything else its just
171 * identity). We do that to enable operations such as find with
172 * args which are const.
174 typedef typename std::conditional<
175 std::is_same<Iter, char*>::value
176 || std::is_same<Iter, unsigned char*>::value,
177 Range<const value_type*>,
178 Range<Iter>>::type const_range_type;
180 typedef std::char_traits<typename std::remove_const<value_type>::type>
183 static const size_type npos;
185 // Works for all iterators
186 constexpr Range() : b_(), e_() {
189 constexpr Range(const Range&) = default;
190 constexpr Range(Range&&) = default;
193 // Works for all iterators
194 constexpr Range(Iter start, Iter end) : b_(start), e_(end) {
197 // Works only for random-access iterators
198 constexpr Range(Iter start, size_t size)
199 : b_(start), e_(start + size) { }
201 #if FOLLY_HAVE_CONSTEXPR_STRLEN
202 template <class T = Iter, typename detail::IsCharPointer<T>::type = 0>
203 constexpr /* implicit */ Range(Iter str)
204 : b_(str), e_(str + strlen(str)) {}
206 template <class T = Iter, typename detail::IsCharPointer<T>::type = 0>
207 /* implicit */ Range(Iter str)
208 : b_(str), e_(str + strlen(str)) {}
210 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
211 /* implicit */ Range(const std::string& str)
212 : b_(str.data()), e_(b_ + str.size()) {}
214 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
215 Range(const std::string& str, std::string::size_type startFrom) {
216 if (UNLIKELY(startFrom > str.size())) {
217 throw std::out_of_range("index out of range");
219 b_ = str.data() + startFrom;
220 e_ = str.data() + str.size();
223 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
224 Range(const std::string& str,
225 std::string::size_type startFrom,
226 std::string::size_type size) {
227 if (UNLIKELY(startFrom > str.size())) {
228 throw std::out_of_range("index out of range");
230 b_ = str.data() + startFrom;
231 if (str.size() - startFrom < size) {
232 e_ = str.data() + str.size();
238 Range(const Range& other,
240 size_type length = npos)
241 : Range(other.subpiece(first, length))
244 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
245 /* implicit */ Range(const fbstring& str)
246 : b_(str.data()), e_(b_ + str.size()) { }
248 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
249 Range(const fbstring& str, fbstring::size_type startFrom) {
250 if (UNLIKELY(startFrom > str.size())) {
251 throw std::out_of_range("index out of range");
253 b_ = str.data() + startFrom;
254 e_ = str.data() + str.size();
257 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
258 Range(const fbstring& str, fbstring::size_type startFrom,
259 fbstring::size_type size) {
260 if (UNLIKELY(startFrom > str.size())) {
261 throw std::out_of_range("index out of range");
263 b_ = str.data() + startFrom;
264 if (str.size() - startFrom < size) {
265 e_ = str.data() + str.size();
271 // Allow implicit conversion from Range<const char*> (aka StringPiece) to
272 // Range<const unsigned char*> (aka ByteRange), as they're both frequently
273 // used to represent ranges of bytes. Allow explicit conversion in the other
275 template <class OtherIter, typename std::enable_if<
276 (std::is_same<Iter, const unsigned char*>::value &&
277 (std::is_same<OtherIter, const char*>::value ||
278 std::is_same<OtherIter, char*>::value)), int>::type = 0>
279 /* implicit */ Range(const Range<OtherIter>& other)
280 : b_(reinterpret_cast<const unsigned char*>(other.begin())),
281 e_(reinterpret_cast<const unsigned char*>(other.end())) {
284 template <class OtherIter, typename std::enable_if<
285 (std::is_same<Iter, unsigned char*>::value &&
286 std::is_same<OtherIter, char*>::value), int>::type = 0>
287 /* implicit */ Range(const Range<OtherIter>& other)
288 : b_(reinterpret_cast<unsigned char*>(other.begin())),
289 e_(reinterpret_cast<unsigned char*>(other.end())) {
292 template <class OtherIter, typename std::enable_if<
293 (std::is_same<Iter, const char*>::value &&
294 (std::is_same<OtherIter, const unsigned char*>::value ||
295 std::is_same<OtherIter, unsigned char*>::value)), int>::type = 0>
296 explicit Range(const Range<OtherIter>& other)
297 : b_(reinterpret_cast<const char*>(other.begin())),
298 e_(reinterpret_cast<const char*>(other.end())) {
301 template <class OtherIter, typename std::enable_if<
302 (std::is_same<Iter, char*>::value &&
303 std::is_same<OtherIter, unsigned char*>::value), int>::type = 0>
304 explicit Range(const Range<OtherIter>& other)
305 : b_(reinterpret_cast<char*>(other.begin())),
306 e_(reinterpret_cast<char*>(other.end())) {
309 // Allow implicit conversion from Range<From> to Range<To> if From is
310 // implicitly convertible to To.
311 template <class OtherIter, typename std::enable_if<
312 (!std::is_same<Iter, OtherIter>::value &&
313 std::is_convertible<OtherIter, Iter>::value), int>::type = 0>
314 constexpr /* implicit */ Range(const Range<OtherIter>& other)
319 // Allow explicit conversion from Range<From> to Range<To> if From is
320 // explicitly convertible to To.
321 template <class OtherIter, typename std::enable_if<
322 (!std::is_same<Iter, OtherIter>::value &&
323 !std::is_convertible<OtherIter, Iter>::value &&
324 std::is_constructible<Iter, const OtherIter&>::value), int>::type = 0>
325 constexpr explicit Range(const Range<OtherIter>& other)
330 Range& operator=(const Range& rhs) & = default;
331 Range& operator=(Range&& rhs) & = default;
338 void assign(Iter start, Iter end) {
343 void reset(Iter start, size_type size) {
348 // Works only for Range<const char*>
349 void reset(const std::string& str) {
350 reset(str.data(), str.size());
353 size_type size() const {
357 size_type walk_size() const {
359 return std::distance(b_, e_);
361 bool empty() const { return b_ == e_; }
362 Iter data() const { return b_; }
363 Iter start() const { return b_; }
364 Iter begin() const { return b_; }
365 Iter end() const { return e_; }
366 Iter cbegin() const { return b_; }
367 Iter cend() const { return e_; }
368 value_type& front() {
374 return detail::value_before(e_);
376 const value_type& front() const {
380 const value_type& back() const {
382 return detail::value_before(e_);
384 // Works only for Range<const char*> and Range<char*>
385 std::string str() const { return std::string(b_, size()); }
386 std::string toString() const { return str(); }
387 // Works only for Range<const char*> and Range<char*>
388 fbstring fbstr() const { return fbstring(b_, size()); }
389 fbstring toFbstring() const { return fbstr(); }
391 const_range_type castToConst() const {
392 return const_range_type(*this);
395 // Works only for Range<const char*> and Range<char*>
396 int compare(const const_range_type& o) const {
397 const size_type tsize = this->size();
398 const size_type osize = o.size();
399 const size_type msize = std::min(tsize, osize);
400 int r = traits_type::compare(data(), o.data(), msize);
401 if (r == 0 && tsize != osize) {
402 // We check the signed bit of the subtraction and bit shift it
403 // to produce either 0 or 2. The subtraction yields the
404 // comparison values of either -1 or 1.
405 r = (static_cast<int>(
406 (osize - tsize) >> (CHAR_BIT * sizeof(size_t) - 1)) << 1) - 1;
411 value_type& operator[](size_t i) {
412 DCHECK_GT(size(), i);
416 const value_type& operator[](size_t i) const {
417 DCHECK_GT(size(), i);
421 value_type& at(size_t i) {
422 if (i >= size()) throw std::out_of_range("index out of range");
426 const value_type& at(size_t i) const {
427 if (i >= size()) throw std::out_of_range("index out of range");
431 // Do NOT use this function, which was left behind for backwards
432 // compatibility. Use SpookyHashV2 instead -- it is faster, and produces
433 // a 64-bit hash, which means dramatically fewer collisions in large maps.
434 // (The above advice does not apply if you are targeting a 32-bit system.)
436 // Works only for Range<const char*> and Range<char*>
437 uint32_t hash() const {
438 // Taken from fbi/nstring.h:
439 // Quick and dirty bernstein hash...fine for short ascii strings
440 uint32_t hash = 5381;
441 for (size_t ix = 0; ix < size(); ix++) {
442 hash = ((hash << 5) + hash) + b_[ix];
447 void advance(size_type n) {
448 if (UNLIKELY(n > size())) {
449 throw std::out_of_range("index out of range");
454 void subtract(size_type n) {
455 if (UNLIKELY(n > size())) {
456 throw std::out_of_range("index out of range");
471 Range subpiece(size_type first, size_type length = npos) const {
472 if (UNLIKELY(first > size())) {
473 throw std::out_of_range("index out of range");
476 return Range(b_ + first, std::min(length, size() - first));
479 // string work-alike functions
480 size_type find(const_range_type str) const {
481 return qfind(castToConst(), str);
484 size_type find(const_range_type str, size_t pos) const {
485 if (pos > size()) return std::string::npos;
486 size_t ret = qfind(castToConst().subpiece(pos), str);
487 return ret == npos ? ret : ret + pos;
490 size_type find(Iter s, size_t pos, size_t n) const {
491 if (pos > size()) return std::string::npos;
492 auto forFinding = castToConst();
494 pos ? forFinding.subpiece(pos) : forFinding, const_range_type(s, n));
495 return ret == npos ? ret : ret + pos;
498 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
499 size_type find(const Iter s) const {
500 return qfind(castToConst(), const_range_type(s));
503 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
504 size_type find(const Iter s, size_t pos) const {
505 if (pos > size()) return std::string::npos;
506 size_type ret = qfind(castToConst().subpiece(pos), const_range_type(s));
507 return ret == npos ? ret : ret + pos;
510 size_type find(value_type c) const {
511 return qfind(castToConst(), c);
514 size_type rfind(value_type c) const {
515 return folly::rfind(castToConst(), c);
518 size_type find(value_type c, size_t pos) const {
519 if (pos > size()) return std::string::npos;
520 size_type ret = qfind(castToConst().subpiece(pos), c);
521 return ret == npos ? ret : ret + pos;
524 size_type find_first_of(const_range_type needles) const {
525 return qfind_first_of(castToConst(), needles);
528 size_type find_first_of(const_range_type needles, size_t pos) const {
529 if (pos > size()) return std::string::npos;
530 size_type ret = qfind_first_of(castToConst().subpiece(pos), needles);
531 return ret == npos ? ret : ret + pos;
534 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
535 size_type find_first_of(Iter needles) const {
536 return find_first_of(const_range_type(needles));
539 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
540 size_type find_first_of(Iter needles, size_t pos) const {
541 return find_first_of(const_range_type(needles), pos);
544 size_type find_first_of(Iter needles, size_t pos, size_t n) const {
545 return find_first_of(const_range_type(needles, n), pos);
548 size_type find_first_of(value_type c) const {
552 size_type find_first_of(value_type c, size_t pos) const {
557 * Determine whether the range contains the given subrange or item.
559 * Note: Call find() directly if the index is needed.
561 bool contains(const const_range_type& other) const {
562 return find(other) != std::string::npos;
565 bool contains(const value_type& other) const {
566 return find(other) != std::string::npos;
569 void swap(Range& rhs) {
570 std::swap(b_, rhs.b_);
571 std::swap(e_, rhs.e_);
575 * Does this Range start with another range?
577 bool startsWith(const const_range_type& other) const {
578 return size() >= other.size()
579 && castToConst().subpiece(0, other.size()) == other;
581 bool startsWith(value_type c) const {
582 return !empty() && front() == c;
586 * Does this Range end with another range?
588 bool endsWith(const const_range_type& other) const {
589 return size() >= other.size()
590 && castToConst().subpiece(size() - other.size()) == other;
592 bool endsWith(value_type c) const {
593 return !empty() && back() == c;
597 * Remove the given prefix and return true if the range starts with the given
598 * prefix; return false otherwise.
600 bool removePrefix(const const_range_type& prefix) {
601 return startsWith(prefix) && (b_ += prefix.size(), true);
603 bool removePrefix(value_type prefix) {
604 return startsWith(prefix) && (++b_, true);
608 * Remove the given suffix and return true if the range ends with the given
609 * suffix; return false otherwise.
611 bool removeSuffix(const const_range_type& suffix) {
612 return endsWith(suffix) && (e_ -= suffix.size(), true);
614 bool removeSuffix(value_type suffix) {
615 return endsWith(suffix) && (--e_, true);
619 * Replaces the content of the range, starting at position 'pos', with
620 * contents of 'replacement'. Entire 'replacement' must fit into the
621 * range. Returns false if 'replacements' does not fit. Example use:
623 * char in[] = "buffer";
624 * auto msp = MutablesStringPiece(input);
625 * EXPECT_TRUE(msp.replaceAt(2, "tt"));
626 * EXPECT_EQ(msp, "butter");
628 * // not enough space
629 * EXPECT_FALSE(msp.replace(msp.size() - 1, "rr"));
630 * EXPECT_EQ(msp, "butter"); // unchanged
632 bool replaceAt(size_t pos, const_range_type replacement) {
633 if (size() < pos + replacement.size()) {
637 std::copy(replacement.begin(), replacement.end(), begin() + pos);
643 * Replaces all occurences of 'source' with 'dest'. Returns number
644 * of replacements made. Source and dest have to have the same
645 * length. Throws if the lengths are different. If 'source' is a
646 * pattern that is overlapping with itself, we perform sequential
647 * replacement: "aaaaaaa".replaceAll("aa", "ba") --> "bababaa"
651 * char in[] = "buffer";
652 * auto msp = MutablesStringPiece(input);
653 * EXPECT_EQ(msp.replaceAll("ff","tt"), 1);
654 * EXPECT_EQ(msp, "butter");
656 size_t replaceAll(const_range_type source, const_range_type dest) {
657 if (source.size() != dest.size()) {
658 throw std::invalid_argument(
659 "replacement must have the same size as source");
667 size_t num_replaced = 0;
668 size_type found = std::string::npos;
669 while ((found = find(source, pos)) != std::string::npos) {
670 replaceAt(found, dest);
671 pos += source.size();
679 * Splits this `Range` `[b, e)` in the position `i` dictated by the next
680 * occurence of `delimiter`.
682 * Returns a new `Range` `[b, i)` and adjusts this range to start right after
683 * the delimiter's position. This range will be empty if the delimiter is not
684 * found. If called on an empty `Range`, both this and the returned `Range`
689 * folly::StringPiece s("sample string for split_next");
690 * auto p = s.split_step(' ');
692 * // prints "string for split_next"
700 * void tokenize(StringPiece s, char delimiter) {
701 * while (!s.empty()) {
702 * cout << s.split_step(delimiter);
706 * @author: Marcelo Juchem <marcelo@fb.com>
708 Range split_step(value_type delimiter) {
709 auto i = std::find(b_, e_, delimiter);
712 b_ = i == e_ ? e_ : std::next(i);
717 Range split_step(Range delimiter) {
718 auto i = find(delimiter);
719 Range result(b_, i == std::string::npos ? size() : i);
721 b_ = result.end() == e_ ? e_ : std::next(result.end(), delimiter.size());
727 * Convenience method that calls `split_step()` and passes the result to a
728 * functor, returning whatever the functor does. Any additional arguments
729 * `args` passed to this function are perfectly forwarded to the functor.
731 * Say you have a functor with this signature:
733 * Foo fn(Range r) { }
735 * `split_step()`'s return type will be `Foo`. It works just like:
737 * auto result = fn(myRange.split_step(' '));
739 * A functor returning `void` is also supported.
743 * void do_some_parsing(folly::StringPiece s) {
744 * auto version = s.split_step(' ', [&](folly::StringPiece x) {
746 * throw std::invalid_argument("empty string");
748 * return std::strtoull(x.begin(), x.end(), 16);
755 * void parse(folly::StringPiece s) {
756 * s.split_step(' ', parse_field, bar, 10);
757 * s.split_step('\t', parse_field, baz, 20);
759 * auto const kludge = [](folly::StringPiece x, int &out, int def) {
763 * parse_field(x, out, def);
767 * s.split_step('\t', kludge, gaz);
768 * s.split_step(' ', kludge, foo);
777 * static parse_field(folly::StringPiece s, int &out, int def) {
779 * out = folly::to<int>(s);
780 * } catch (std::exception const &) {
786 * @author: Marcelo Juchem <marcelo@fb.com>
788 template <typename TProcess, typename... Args>
789 auto split_step(value_type delimiter, TProcess &&process, Args &&...args)
790 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
791 { return process(split_step(delimiter), std::forward<Args>(args)...); }
793 template <typename TProcess, typename... Args>
794 auto split_step(Range delimiter, TProcess &&process, Args &&...args)
795 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
796 { return process(split_step(delimiter), std::forward<Args>(args)...); }
802 template <class Iter>
803 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
806 void swap(Range<T>& lhs, Range<T>& rhs) {
811 * Create a range from two iterators, with type deduction.
813 template <class Iter>
814 Range<Iter> range(Iter first, Iter last) {
815 return Range<Iter>(first, last);
819 * Creates a range to reference the contents of a contiguous-storage container.
821 // Use pointers for types with '.data()' member
822 template <class Collection,
823 class T = typename std::remove_pointer<
824 decltype(std::declval<Collection>().data())>::type>
825 Range<T*> range(Collection&& v) {
826 return Range<T*>(v.data(), v.data() + v.size());
829 template <class T, size_t n>
830 Range<T*> range(T (&array)[n]) {
831 return Range<T*>(array, array + n);
834 typedef Range<const char*> StringPiece;
835 typedef Range<char*> MutableStringPiece;
836 typedef Range<const unsigned char*> ByteRange;
837 typedef Range<unsigned char*> MutableByteRange;
839 inline std::ostream& operator<<(std::ostream& os,
840 const StringPiece piece) {
841 os.write(piece.start(), piece.size());
845 inline std::ostream& operator<<(std::ostream& os,
846 const MutableStringPiece piece) {
847 os.write(piece.start(), piece.size());
852 * Templated comparison operators
856 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
857 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
861 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
862 return lhs.compare(rhs) < 0;
866 * Specializations of comparison operators for StringPiece
871 template <class A, class B>
872 struct ComparableAsStringPiece {
875 (std::is_convertible<A, StringPiece>::value
876 && std::is_same<B, StringPiece>::value)
878 (std::is_convertible<B, StringPiece>::value
879 && std::is_same<A, StringPiece>::value)
883 } // namespace detail
886 * operator== through conversion for Range<const char*>
888 template <class T, class U>
890 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
891 operator==(const T& lhs, const U& rhs) {
892 return StringPiece(lhs) == StringPiece(rhs);
896 * operator< through conversion for Range<const char*>
898 template <class T, class U>
900 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
901 operator<(const T& lhs, const U& rhs) {
902 return StringPiece(lhs) < StringPiece(rhs);
906 * operator> through conversion for Range<const char*>
908 template <class T, class U>
910 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
911 operator>(const T& lhs, const U& rhs) {
912 return StringPiece(lhs) > StringPiece(rhs);
916 * operator< through conversion for Range<const char*>
918 template <class T, class U>
920 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
921 operator<=(const T& lhs, const U& rhs) {
922 return StringPiece(lhs) <= StringPiece(rhs);
926 * operator> through conversion for Range<const char*>
928 template <class T, class U>
930 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
931 operator>=(const T& lhs, const U& rhs) {
932 return StringPiece(lhs) >= StringPiece(rhs);
935 // Do NOT use this, use SpookyHashV2 instead, see commment on hash() above.
936 struct StringPieceHash {
937 std::size_t operator()(const StringPiece str) const {
938 return static_cast<std::size_t>(str.hash());
943 * Finds substrings faster than brute force by borrowing from Boyer-Moore
945 template <class T, class Comp>
946 size_t qfind(const Range<T>& haystack,
947 const Range<T>& needle,
949 // Don't use std::search, use a Boyer-Moore-like trick by comparing
950 // the last characters first
951 auto const nsize = needle.size();
952 if (haystack.size() < nsize) {
953 return std::string::npos;
955 if (!nsize) return 0;
956 auto const nsize_1 = nsize - 1;
957 auto const lastNeedle = needle[nsize_1];
959 // Boyer-Moore skip value for the last char in the needle. Zero is
960 // not a valid value; skip will be computed the first time it's
962 std::string::size_type skip = 0;
964 auto i = haystack.begin();
965 auto iEnd = haystack.end() - nsize_1;
968 // Boyer-Moore: match the last element in the needle
969 while (!eq(i[nsize_1], lastNeedle)) {
972 return std::string::npos;
975 // Here we know that the last char matches
976 // Continue in pedestrian mode
977 for (size_t j = 0; ; ) {
979 if (!eq(i[j], needle[j])) {
980 // Not found, we can skip
981 // Compute the skip value lazily
984 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
991 // Check if done searching
994 return i - haystack.begin();
998 return std::string::npos;
1003 size_t qfind_first_byte_of_nosse(const StringPiece haystack,
1004 const StringPiece needles);
1006 #if FOLLY_HAVE_EMMINTRIN_H && __GNUC_PREREQ(4, 6)
1007 size_t qfind_first_byte_of_sse42(const StringPiece haystack,
1008 const StringPiece needles);
1010 inline size_t qfind_first_byte_of(const StringPiece haystack,
1011 const StringPiece needles) {
1012 static auto const qfind_first_byte_of_fn =
1013 folly::CpuId().sse42() ? qfind_first_byte_of_sse42
1014 : qfind_first_byte_of_nosse;
1015 return qfind_first_byte_of_fn(haystack, needles);
1019 inline size_t qfind_first_byte_of(const StringPiece haystack,
1020 const StringPiece needles) {
1021 return qfind_first_byte_of_nosse(haystack, needles);
1023 #endif // FOLLY_HAVE_EMMINTRIN_H
1025 } // namespace detail
1027 template <class T, class Comp>
1028 size_t qfind_first_of(const Range<T> & haystack,
1029 const Range<T> & needles,
1031 auto ret = std::find_first_of(haystack.begin(), haystack.end(),
1032 needles.begin(), needles.end(),
1034 return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
1037 struct AsciiCaseSensitive {
1038 bool operator()(char lhs, char rhs) const {
1044 * Check if two ascii characters are case insensitive equal.
1045 * The difference between the lower/upper case characters are the 6-th bit.
1046 * We also check they are alpha chars, in case of xor = 32.
1048 struct AsciiCaseInsensitive {
1049 bool operator()(char lhs, char rhs) const {
1051 if (k == 0) return true;
1052 if (k != 32) return false;
1054 return (k >= 'a' && k <= 'z');
1058 extern const AsciiCaseSensitive asciiCaseSensitive;
1059 extern const AsciiCaseInsensitive asciiCaseInsensitive;
1062 size_t qfind(const Range<T>& haystack,
1063 const typename Range<T>::value_type& needle) {
1064 auto pos = std::find(haystack.begin(), haystack.end(), needle);
1065 return pos == haystack.end() ? std::string::npos : pos - haystack.data();
1069 size_t rfind(const Range<T>& haystack,
1070 const typename Range<T>::value_type& needle) {
1071 for (auto i = haystack.size(); i-- > 0; ) {
1072 if (haystack[i] == needle) {
1076 return std::string::npos;
1079 // specialization for StringPiece
1081 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
1082 auto pos = static_cast<const char*>(
1083 ::memchr(haystack.data(), needle, haystack.size()));
1084 return pos == nullptr ? std::string::npos : pos - haystack.data();
1087 #if FOLLY_HAVE_MEMRCHR
1089 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
1090 auto pos = static_cast<const char*>(
1091 ::memrchr(haystack.data(), needle, haystack.size()));
1092 return pos == nullptr ? std::string::npos : pos - haystack.data();
1096 // specialization for ByteRange
1098 inline size_t qfind(const Range<const unsigned char*>& haystack,
1099 const unsigned char& needle) {
1100 auto pos = static_cast<const unsigned char*>(
1101 ::memchr(haystack.data(), needle, haystack.size()));
1102 return pos == nullptr ? std::string::npos : pos - haystack.data();
1105 #if FOLLY_HAVE_MEMRCHR
1107 inline size_t rfind(const Range<const unsigned char*>& haystack,
1108 const unsigned char& needle) {
1109 auto pos = static_cast<const unsigned char*>(
1110 ::memrchr(haystack.data(), needle, haystack.size()));
1111 return pos == nullptr ? std::string::npos : pos - haystack.data();
1116 size_t qfind_first_of(const Range<T>& haystack,
1117 const Range<T>& needles) {
1118 return qfind_first_of(haystack, needles, asciiCaseSensitive);
1121 // specialization for StringPiece
1123 inline size_t qfind_first_of(const Range<const char*>& haystack,
1124 const Range<const char*>& needles) {
1125 return detail::qfind_first_byte_of(haystack, needles);
1128 // specialization for ByteRange
1130 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
1131 const Range<const unsigned char*>& needles) {
1132 return detail::qfind_first_byte_of(StringPiece(haystack),
1133 StringPiece(needles));
1139 template <class T> struct hasher<folly::Range<T*>> {
1140 size_t operator()(folly::Range<T*> r) const {
1141 return hash::SpookyHashV2::Hash64(r.begin(), r.size() * sizeof(T), 0);
1145 } // !namespace folly
1147 #pragma GCC diagnostic pop
1149 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);
1151 #endif // FOLLY_RANGE_H_