2 * Copyright 2016 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)
22 #include <folly/FBString.h>
23 #include <folly/Portability.h>
24 #include <folly/SpookyHashV2.h>
25 #include <folly/portability/Constexpr.h>
26 #include <folly/portability/String.h>
29 #include <boost/operators.hpp>
33 #include <glog/logging.h>
37 #include <type_traits>
39 // libc++ doesn't provide this header, nor does msvc
40 #ifdef FOLLY_HAVE_BITS_CXXCONFIG_H
41 // This file appears in two locations: inside fbcode and in the
42 // libstdc++ source code (when embedding fbstring as std::string).
43 // To aid in this schizophrenic use, two macros are defined in
45 // _LIBSTDCXX_FBSTRING - Set inside libstdc++. This is useful to
46 // gate use inside fbcode v. libstdc++
47 #include <bits/c++config.h>
50 #include <folly/CpuId.h>
51 #include <folly/Traits.h>
52 #include <folly/Likely.h>
53 #include <folly/detail/RangeCommon.h>
54 #include <folly/detail/RangeSse42.h>
56 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
57 #pragma GCC diagnostic push
58 #pragma GCC diagnostic ignored "-Wshadow"
62 template <class T> class Range;
65 * Finds the first occurrence of needle in haystack. The algorithm is on
66 * average faster than O(haystack.size() * needle.size()) but not as fast
67 * as Boyer-Moore. On the upside, it does not do any upfront
68 * preprocessing and does not allocate memory.
70 template <class T, class Comp = std::equal_to<typename Range<T>::value_type>>
71 inline size_t qfind(const Range<T> & haystack,
72 const Range<T> & needle,
76 * Finds the first occurrence of needle in haystack. The result is the
77 * offset reported to the beginning of haystack, or string::npos if
78 * needle wasn't found.
81 size_t qfind(const Range<T> & haystack,
82 const typename Range<T>::value_type& needle);
85 * Finds the last occurrence of needle in haystack. The result is the
86 * offset reported to the beginning of haystack, or string::npos if
87 * needle wasn't found.
90 size_t rfind(const Range<T> & haystack,
91 const typename Range<T>::value_type& needle);
95 * Finds the first occurrence of any element of needle in
96 * haystack. The algorithm is O(haystack.size() * needle.size()).
99 inline size_t qfind_first_of(const Range<T> & haystack,
100 const Range<T> & needle);
103 * Small internal helper - returns the value just before an iterator.
108 * For random-access iterators, the value before is simply i[-1].
110 template <class Iter>
111 typename std::enable_if<
112 std::is_same<typename std::iterator_traits<Iter>::iterator_category,
113 std::random_access_iterator_tag>::value,
114 typename std::iterator_traits<Iter>::reference>::type
115 value_before(Iter i) {
120 * For all other iterators, we need to use the decrement operator.
122 template <class Iter>
123 typename std::enable_if<
124 !std::is_same<typename std::iterator_traits<Iter>::iterator_category,
125 std::random_access_iterator_tag>::value,
126 typename std::iterator_traits<Iter>::reference>::type
127 value_before(Iter i) {
132 * Use IsCharPointer<T>::type to enable const char* or char*.
133 * Use IsCharPointer<T>::const_type to enable only const char*.
135 template <class T> struct IsCharPointer {};
138 struct IsCharPointer<char*> {
143 struct IsCharPointer<const char*> {
144 typedef int const_type;
148 } // namespace detail
151 * Range abstraction keeping a pair of iterators. We couldn't use
152 * boost's similar range abstraction because we need an API identical
153 * with the former StringPiece class, which is used by a lot of other
154 * code. This abstraction does fulfill the needs of boost's
155 * range-oriented algorithms though.
157 * (Keep memory lifetime in mind when using this class, since it
158 * doesn't manage the data it refers to - just like an iterator
161 template <class Iter>
162 class Range : private boost::totally_ordered<Range<Iter> > {
164 typedef std::size_t size_type;
165 typedef Iter iterator;
166 typedef Iter const_iterator;
167 typedef typename std::remove_reference<
168 typename std::iterator_traits<Iter>::reference>::type
170 typedef typename std::iterator_traits<Iter>::reference reference;
173 * For MutableStringPiece and MutableByteRange we define StringPiece
174 * and ByteRange as const_range_type (for everything else its just
175 * identity). We do that to enable operations such as find with
176 * args which are const.
178 typedef typename std::conditional<
179 std::is_same<Iter, char*>::value
180 || std::is_same<Iter, unsigned char*>::value,
181 Range<const value_type*>,
182 Range<Iter>>::type const_range_type;
184 typedef std::char_traits<typename std::remove_const<value_type>::type>
187 static const size_type npos;
189 // Works for all iterators
190 constexpr Range() : b_(), e_() {
193 constexpr Range(const Range&) = default;
194 constexpr Range(Range&&) = default;
197 // Works for all iterators
198 constexpr Range(Iter start, Iter end) : b_(start), e_(end) {
201 // Works only for random-access iterators
202 constexpr Range(Iter start, size_t size)
203 : b_(start), e_(start + size) { }
205 # if !__clang__ || __CLANG_PREREQ(3, 7) // Clang 3.6 crashes on this line
206 /* implicit */ Range(std::nullptr_t) = delete;
209 template <class T = Iter, typename detail::IsCharPointer<T>::type = 0>
210 constexpr /* implicit */ Range(Iter str)
211 : b_(str), e_(str + constexpr_strlen(str)) {}
213 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
214 /* implicit */ Range(const std::string& str)
215 : b_(str.data()), e_(b_ + str.size()) {}
217 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
218 Range(const std::string& str, std::string::size_type startFrom) {
219 if (UNLIKELY(startFrom > str.size())) {
220 throw std::out_of_range("index out of range");
222 b_ = str.data() + startFrom;
223 e_ = str.data() + str.size();
226 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
227 Range(const std::string& str,
228 std::string::size_type startFrom,
229 std::string::size_type size) {
230 if (UNLIKELY(startFrom > str.size())) {
231 throw std::out_of_range("index out of range");
233 b_ = str.data() + startFrom;
234 if (str.size() - startFrom < size) {
235 e_ = str.data() + str.size();
241 Range(const Range& other,
243 size_type length = npos)
244 : Range(other.subpiece(first, length))
247 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
248 /* implicit */ Range(const fbstring& str)
249 : b_(str.data()), e_(b_ + str.size()) { }
251 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
252 Range(const fbstring& str, fbstring::size_type startFrom) {
253 if (UNLIKELY(startFrom > str.size())) {
254 throw std::out_of_range("index out of range");
256 b_ = str.data() + startFrom;
257 e_ = str.data() + str.size();
260 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
261 Range(const fbstring& str, fbstring::size_type startFrom,
262 fbstring::size_type size) {
263 if (UNLIKELY(startFrom > str.size())) {
264 throw std::out_of_range("index out of range");
266 b_ = str.data() + startFrom;
267 if (str.size() - startFrom < size) {
268 e_ = str.data() + str.size();
274 // Allow implicit conversion from Range<const char*> (aka StringPiece) to
275 // Range<const unsigned char*> (aka ByteRange), as they're both frequently
276 // used to represent ranges of bytes. Allow explicit conversion in the other
278 template <class OtherIter, typename std::enable_if<
279 (std::is_same<Iter, const unsigned char*>::value &&
280 (std::is_same<OtherIter, const char*>::value ||
281 std::is_same<OtherIter, char*>::value)), int>::type = 0>
282 /* implicit */ Range(const Range<OtherIter>& other)
283 : b_(reinterpret_cast<const unsigned char*>(other.begin())),
284 e_(reinterpret_cast<const unsigned char*>(other.end())) {
287 template <class OtherIter, typename std::enable_if<
288 (std::is_same<Iter, unsigned char*>::value &&
289 std::is_same<OtherIter, char*>::value), int>::type = 0>
290 /* implicit */ Range(const Range<OtherIter>& other)
291 : b_(reinterpret_cast<unsigned char*>(other.begin())),
292 e_(reinterpret_cast<unsigned char*>(other.end())) {
295 template <class OtherIter, typename std::enable_if<
296 (std::is_same<Iter, const char*>::value &&
297 (std::is_same<OtherIter, const unsigned char*>::value ||
298 std::is_same<OtherIter, unsigned char*>::value)), int>::type = 0>
299 explicit Range(const Range<OtherIter>& other)
300 : b_(reinterpret_cast<const char*>(other.begin())),
301 e_(reinterpret_cast<const char*>(other.end())) {
304 template <class OtherIter, typename std::enable_if<
305 (std::is_same<Iter, char*>::value &&
306 std::is_same<OtherIter, unsigned char*>::value), int>::type = 0>
307 explicit Range(const Range<OtherIter>& other)
308 : b_(reinterpret_cast<char*>(other.begin())),
309 e_(reinterpret_cast<char*>(other.end())) {
312 // Allow implicit conversion from Range<From> to Range<To> if From is
313 // implicitly convertible to To.
314 template <class OtherIter, typename std::enable_if<
315 (!std::is_same<Iter, OtherIter>::value &&
316 std::is_convertible<OtherIter, Iter>::value), int>::type = 0>
317 constexpr /* implicit */ Range(const Range<OtherIter>& other)
322 // Allow explicit conversion from Range<From> to Range<To> if From is
323 // explicitly convertible to To.
324 template <class OtherIter, typename std::enable_if<
325 (!std::is_same<Iter, OtherIter>::value &&
326 !std::is_convertible<OtherIter, Iter>::value &&
327 std::is_constructible<Iter, const OtherIter&>::value), int>::type = 0>
328 constexpr explicit Range(const Range<OtherIter>& other)
333 Range& operator=(const Range& rhs) & = default;
334 Range& operator=(Range&& rhs) & = default;
341 void assign(Iter start, Iter end) {
346 void reset(Iter start, size_type size) {
351 // Works only for Range<const char*>
352 void reset(const std::string& str) {
353 reset(str.data(), str.size());
356 constexpr size_type size() const {
357 // It would be nice to assert(b_ <= e_) here. This can be achieved even
358 // in a C++11 compatible constexpr function:
359 // http://ericniebler.com/2014/09/27/assert-and-constexpr-in-cxx11/
360 // Unfortunately current gcc versions have a bug causing it to reject
361 // this check in a constexpr function:
362 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=71448
365 size_type walk_size() const {
366 return std::distance(b_, e_);
368 bool empty() const { return b_ == e_; }
369 Iter data() const { return b_; }
370 Iter start() const { return b_; }
371 Iter begin() const { return b_; }
372 Iter end() const { return e_; }
373 Iter cbegin() const { return b_; }
374 Iter cend() const { return e_; }
375 value_type& front() {
381 return detail::value_before(e_);
383 const value_type& front() const {
387 const value_type& back() const {
389 return detail::value_before(e_);
391 // Works only for Range<const char*> and Range<char*>
392 std::string str() const { return std::string(b_, size()); }
393 std::string toString() const { return str(); }
394 // Works only for Range<const char*> and Range<char*>
395 fbstring fbstr() const { return fbstring(b_, size()); }
396 fbstring toFbstring() const { return fbstr(); }
398 const_range_type castToConst() const {
399 return const_range_type(*this);
402 // Works only for Range<const char*> and Range<char*>
403 int compare(const const_range_type& o) const {
404 const size_type tsize = this->size();
405 const size_type osize = o.size();
406 const size_type msize = std::min(tsize, osize);
407 int r = traits_type::compare(data(), o.data(), msize);
408 if (r == 0 && tsize != osize) {
409 // We check the signed bit of the subtraction and bit shift it
410 // to produce either 0 or 2. The subtraction yields the
411 // comparison values of either -1 or 1.
412 r = (static_cast<int>(
413 (osize - tsize) >> (CHAR_BIT * sizeof(size_t) - 1)) << 1) - 1;
418 value_type& operator[](size_t i) {
419 DCHECK_GT(size(), i);
423 const value_type& operator[](size_t i) const {
424 DCHECK_GT(size(), i);
428 value_type& at(size_t i) {
429 if (i >= size()) throw std::out_of_range("index out of range");
433 const value_type& at(size_t i) const {
434 if (i >= size()) throw std::out_of_range("index out of range");
438 // Do NOT use this function, which was left behind for backwards
439 // compatibility. Use SpookyHashV2 instead -- it is faster, and produces
440 // a 64-bit hash, which means dramatically fewer collisions in large maps.
441 // (The above advice does not apply if you are targeting a 32-bit system.)
443 // Works only for Range<const char*> and Range<char*>
444 uint32_t hash() const {
445 // Taken from fbi/nstring.h:
446 // Quick and dirty bernstein hash...fine for short ascii strings
447 uint32_t hash = 5381;
448 for (size_t ix = 0; ix < size(); ix++) {
449 hash = ((hash << 5) + hash) + b_[ix];
454 void advance(size_type n) {
455 if (UNLIKELY(n > size())) {
456 throw std::out_of_range("index out of range");
461 void subtract(size_type n) {
462 if (UNLIKELY(n > size())) {
463 throw std::out_of_range("index out of range");
478 Range subpiece(size_type first, size_type length = npos) const {
479 if (UNLIKELY(first > size())) {
480 throw std::out_of_range("index out of range");
483 return Range(b_ + first, std::min(length, size() - first));
486 // string work-alike functions
487 size_type find(const_range_type str) const {
488 return qfind(castToConst(), str);
491 size_type find(const_range_type str, size_t pos) const {
492 if (pos > size()) return std::string::npos;
493 size_t ret = qfind(castToConst().subpiece(pos), str);
494 return ret == npos ? ret : ret + pos;
497 size_type find(Iter s, size_t pos, size_t n) const {
498 if (pos > size()) return std::string::npos;
499 auto forFinding = castToConst();
501 pos ? forFinding.subpiece(pos) : forFinding, const_range_type(s, n));
502 return ret == npos ? ret : ret + pos;
505 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
506 size_type find(const Iter s) const {
507 return qfind(castToConst(), const_range_type(s));
510 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
511 size_type find(const Iter s, size_t pos) const {
512 if (pos > size()) return std::string::npos;
513 size_type ret = qfind(castToConst().subpiece(pos), const_range_type(s));
514 return ret == npos ? ret : ret + pos;
517 size_type find(value_type c) const {
518 return qfind(castToConst(), c);
521 size_type rfind(value_type c) const {
522 return folly::rfind(castToConst(), c);
525 size_type find(value_type c, size_t pos) const {
526 if (pos > size()) return std::string::npos;
527 size_type ret = qfind(castToConst().subpiece(pos), c);
528 return ret == npos ? ret : ret + pos;
531 size_type find_first_of(const_range_type needles) const {
532 return qfind_first_of(castToConst(), needles);
535 size_type find_first_of(const_range_type needles, size_t pos) const {
536 if (pos > size()) return std::string::npos;
537 size_type ret = qfind_first_of(castToConst().subpiece(pos), needles);
538 return ret == npos ? ret : ret + pos;
541 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
542 size_type find_first_of(Iter needles) const {
543 return find_first_of(const_range_type(needles));
546 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
547 size_type find_first_of(Iter needles, size_t pos) const {
548 return find_first_of(const_range_type(needles), pos);
551 size_type find_first_of(Iter needles, size_t pos, size_t n) const {
552 return find_first_of(const_range_type(needles, n), pos);
555 size_type find_first_of(value_type c) const {
559 size_type find_first_of(value_type c, size_t pos) const {
564 * Determine whether the range contains the given subrange or item.
566 * Note: Call find() directly if the index is needed.
568 bool contains(const const_range_type& other) const {
569 return find(other) != std::string::npos;
572 bool contains(const value_type& other) const {
573 return find(other) != std::string::npos;
576 void swap(Range& rhs) {
577 std::swap(b_, rhs.b_);
578 std::swap(e_, rhs.e_);
582 * Does this Range start with another range?
584 bool startsWith(const const_range_type& other) const {
585 return size() >= other.size()
586 && castToConst().subpiece(0, other.size()) == other;
588 bool startsWith(value_type c) const {
589 return !empty() && front() == c;
593 * Does this Range end with another range?
595 bool endsWith(const const_range_type& other) const {
596 return size() >= other.size()
597 && castToConst().subpiece(size() - other.size()) == other;
599 bool endsWith(value_type c) const {
600 return !empty() && back() == c;
604 * Remove the items in [b, e), as long as this subrange is at the beginning
605 * or end of the Range.
607 * Required for boost::algorithm::trim()
609 void erase(Iter b, Iter e) {
612 } else if (e == e_) {
615 throw std::out_of_range("index out of range");
620 * Remove the given prefix and return true if the range starts with the given
621 * prefix; return false otherwise.
623 bool removePrefix(const const_range_type& prefix) {
624 return startsWith(prefix) && (b_ += prefix.size(), true);
626 bool removePrefix(value_type prefix) {
627 return startsWith(prefix) && (++b_, true);
631 * Remove the given suffix and return true if the range ends with the given
632 * suffix; return false otherwise.
634 bool removeSuffix(const const_range_type& suffix) {
635 return endsWith(suffix) && (e_ -= suffix.size(), true);
637 bool removeSuffix(value_type suffix) {
638 return endsWith(suffix) && (--e_, true);
642 * Replaces the content of the range, starting at position 'pos', with
643 * contents of 'replacement'. Entire 'replacement' must fit into the
644 * range. Returns false if 'replacements' does not fit. Example use:
646 * char in[] = "buffer";
647 * auto msp = MutablesStringPiece(input);
648 * EXPECT_TRUE(msp.replaceAt(2, "tt"));
649 * EXPECT_EQ(msp, "butter");
651 * // not enough space
652 * EXPECT_FALSE(msp.replace(msp.size() - 1, "rr"));
653 * EXPECT_EQ(msp, "butter"); // unchanged
655 bool replaceAt(size_t pos, const_range_type replacement) {
656 if (size() < pos + replacement.size()) {
660 std::copy(replacement.begin(), replacement.end(), begin() + pos);
666 * Replaces all occurences of 'source' with 'dest'. Returns number
667 * of replacements made. Source and dest have to have the same
668 * length. Throws if the lengths are different. If 'source' is a
669 * pattern that is overlapping with itself, we perform sequential
670 * replacement: "aaaaaaa".replaceAll("aa", "ba") --> "bababaa"
674 * char in[] = "buffer";
675 * auto msp = MutablesStringPiece(input);
676 * EXPECT_EQ(msp.replaceAll("ff","tt"), 1);
677 * EXPECT_EQ(msp, "butter");
679 size_t replaceAll(const_range_type source, const_range_type dest) {
680 if (source.size() != dest.size()) {
681 throw std::invalid_argument(
682 "replacement must have the same size as source");
690 size_t num_replaced = 0;
691 size_type found = std::string::npos;
692 while ((found = find(source, pos)) != std::string::npos) {
693 replaceAt(found, dest);
694 pos += source.size();
702 * Splits this `Range` `[b, e)` in the position `i` dictated by the next
703 * occurence of `delimiter`.
705 * Returns a new `Range` `[b, i)` and adjusts this range to start right after
706 * the delimiter's position. This range will be empty if the delimiter is not
707 * found. If called on an empty `Range`, both this and the returned `Range`
712 * folly::StringPiece s("sample string for split_next");
713 * auto p = s.split_step(' ');
715 * // prints "string for split_next"
723 * void tokenize(StringPiece s, char delimiter) {
724 * while (!s.empty()) {
725 * cout << s.split_step(delimiter);
729 * @author: Marcelo Juchem <marcelo@fb.com>
731 Range split_step(value_type delimiter) {
732 auto i = std::find(b_, e_, delimiter);
735 b_ = i == e_ ? e_ : std::next(i);
740 Range split_step(Range delimiter) {
741 auto i = find(delimiter);
742 Range result(b_, i == std::string::npos ? size() : i);
744 b_ = result.end() == e_ ? e_ : std::next(result.end(), delimiter.size());
750 * Convenience method that calls `split_step()` and passes the result to a
751 * functor, returning whatever the functor does. Any additional arguments
752 * `args` passed to this function are perfectly forwarded to the functor.
754 * Say you have a functor with this signature:
756 * Foo fn(Range r) { }
758 * `split_step()`'s return type will be `Foo`. It works just like:
760 * auto result = fn(myRange.split_step(' '));
762 * A functor returning `void` is also supported.
766 * void do_some_parsing(folly::StringPiece s) {
767 * auto version = s.split_step(' ', [&](folly::StringPiece x) {
769 * throw std::invalid_argument("empty string");
771 * return std::strtoull(x.begin(), x.end(), 16);
778 * void parse(folly::StringPiece s) {
779 * s.split_step(' ', parse_field, bar, 10);
780 * s.split_step('\t', parse_field, baz, 20);
782 * auto const kludge = [](folly::StringPiece x, int &out, int def) {
786 * parse_field(x, out, def);
790 * s.split_step('\t', kludge, gaz);
791 * s.split_step(' ', kludge, foo);
800 * static parse_field(folly::StringPiece s, int &out, int def) {
802 * out = folly::to<int>(s);
803 * } catch (std::exception const &) {
809 * @author: Marcelo Juchem <marcelo@fb.com>
811 template <typename TProcess, typename... Args>
812 auto split_step(value_type delimiter, TProcess &&process, Args &&...args)
813 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
814 { return process(split_step(delimiter), std::forward<Args>(args)...); }
816 template <typename TProcess, typename... Args>
817 auto split_step(Range delimiter, TProcess &&process, Args &&...args)
818 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
819 { return process(split_step(delimiter), std::forward<Args>(args)...); }
825 template <class Iter>
826 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
829 void swap(Range<T>& lhs, Range<T>& rhs) {
834 * Create a range from two iterators, with type deduction.
836 template <class Iter>
837 Range<Iter> range(Iter first, Iter last) {
838 return Range<Iter>(first, last);
842 * Creates a range to reference the contents of a contiguous-storage container.
844 // Use pointers for types with '.data()' member
845 template <class Collection,
846 class T = typename std::remove_pointer<
847 decltype(std::declval<Collection>().data())>::type>
848 Range<T*> range(Collection&& v) {
849 return Range<T*>(v.data(), v.data() + v.size());
852 template <class T, size_t n>
853 Range<T*> range(T (&array)[n]) {
854 return Range<T*>(array, array + n);
857 typedef Range<const char*> StringPiece;
858 typedef Range<char*> MutableStringPiece;
859 typedef Range<const unsigned char*> ByteRange;
860 typedef Range<unsigned char*> MutableByteRange;
862 inline std::ostream& operator<<(std::ostream& os,
863 const StringPiece piece) {
864 os.write(piece.start(), piece.size());
868 inline std::ostream& operator<<(std::ostream& os,
869 const MutableStringPiece piece) {
870 os.write(piece.start(), piece.size());
875 * Templated comparison operators
879 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
880 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
884 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
885 return lhs.compare(rhs) < 0;
889 * Specializations of comparison operators for StringPiece
894 template <class A, class B>
895 struct ComparableAsStringPiece {
898 (std::is_convertible<A, StringPiece>::value
899 && std::is_same<B, StringPiece>::value)
901 (std::is_convertible<B, StringPiece>::value
902 && std::is_same<A, StringPiece>::value)
906 } // namespace detail
909 * operator== through conversion for Range<const char*>
911 template <class T, class U>
913 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
914 operator==(const T& lhs, const U& rhs) {
915 return StringPiece(lhs) == StringPiece(rhs);
919 * operator< through conversion for Range<const char*>
921 template <class T, class U>
923 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
924 operator<(const T& lhs, const U& rhs) {
925 return StringPiece(lhs) < StringPiece(rhs);
929 * operator> through conversion for Range<const char*>
931 template <class T, class U>
933 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
934 operator>(const T& lhs, const U& rhs) {
935 return StringPiece(lhs) > StringPiece(rhs);
939 * operator< through conversion for Range<const char*>
941 template <class T, class U>
943 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
944 operator<=(const T& lhs, const U& rhs) {
945 return StringPiece(lhs) <= StringPiece(rhs);
949 * operator> through conversion for Range<const char*>
951 template <class T, class U>
953 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
954 operator>=(const T& lhs, const U& rhs) {
955 return StringPiece(lhs) >= StringPiece(rhs);
958 // Do NOT use this, use SpookyHashV2 instead, see commment on hash() above.
959 struct StringPieceHash {
960 std::size_t operator()(const StringPiece str) const {
961 return static_cast<std::size_t>(str.hash());
966 * Finds substrings faster than brute force by borrowing from Boyer-Moore
968 template <class T, class Comp>
969 size_t qfind(const Range<T>& haystack,
970 const Range<T>& needle,
972 // Don't use std::search, use a Boyer-Moore-like trick by comparing
973 // the last characters first
974 auto const nsize = needle.size();
975 if (haystack.size() < nsize) {
976 return std::string::npos;
978 if (!nsize) return 0;
979 auto const nsize_1 = nsize - 1;
980 auto const lastNeedle = needle[nsize_1];
982 // Boyer-Moore skip value for the last char in the needle. Zero is
983 // not a valid value; skip will be computed the first time it's
985 std::string::size_type skip = 0;
987 auto i = haystack.begin();
988 auto iEnd = haystack.end() - nsize_1;
991 // Boyer-Moore: match the last element in the needle
992 while (!eq(i[nsize_1], lastNeedle)) {
995 return std::string::npos;
998 // Here we know that the last char matches
999 // Continue in pedestrian mode
1000 for (size_t j = 0; ; ) {
1002 if (!eq(i[j], needle[j])) {
1003 // Not found, we can skip
1004 // Compute the skip value lazily
1007 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
1014 // Check if done searching
1017 return i - haystack.begin();
1021 return std::string::npos;
1026 inline size_t qfind_first_byte_of(const StringPiece haystack,
1027 const StringPiece needles) {
1028 static auto const qfind_first_byte_of_fn =
1029 folly::CpuId().sse42() ? qfind_first_byte_of_sse42
1030 : qfind_first_byte_of_nosse;
1031 return qfind_first_byte_of_fn(haystack, needles);
1034 } // namespace detail
1036 template <class T, class Comp>
1037 size_t qfind_first_of(const Range<T> & haystack,
1038 const Range<T> & needles,
1040 auto ret = std::find_first_of(haystack.begin(), haystack.end(),
1041 needles.begin(), needles.end(),
1043 return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
1046 struct AsciiCaseSensitive {
1047 bool operator()(char lhs, char rhs) const {
1053 * Check if two ascii characters are case insensitive equal.
1054 * The difference between the lower/upper case characters are the 6-th bit.
1055 * We also check they are alpha chars, in case of xor = 32.
1057 struct AsciiCaseInsensitive {
1058 bool operator()(char lhs, char rhs) const {
1060 if (k == 0) return true;
1061 if (k != 32) return false;
1063 return (k >= 'a' && k <= 'z');
1068 size_t qfind(const Range<T>& haystack,
1069 const typename Range<T>::value_type& needle) {
1070 auto pos = std::find(haystack.begin(), haystack.end(), needle);
1071 return pos == haystack.end() ? std::string::npos : pos - haystack.data();
1075 size_t rfind(const Range<T>& haystack,
1076 const typename Range<T>::value_type& needle) {
1077 for (auto i = haystack.size(); i-- > 0; ) {
1078 if (haystack[i] == needle) {
1082 return std::string::npos;
1085 // specialization for StringPiece
1087 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
1088 // memchr expects a not-null pointer, early return if the range is empty.
1089 if (haystack.empty()) {
1090 return std::string::npos;
1092 auto pos = static_cast<const char*>(
1093 ::memchr(haystack.data(), needle, haystack.size()));
1094 return pos == nullptr ? std::string::npos : pos - haystack.data();
1098 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
1099 // memchr expects a not-null pointer, early return if the range is empty.
1100 if (haystack.empty()) {
1101 return std::string::npos;
1103 auto pos = static_cast<const char*>(
1104 ::memrchr(haystack.data(), needle, haystack.size()));
1105 return pos == nullptr ? std::string::npos : pos - haystack.data();
1108 // specialization for ByteRange
1110 inline size_t qfind(const Range<const unsigned char*>& haystack,
1111 const unsigned char& needle) {
1112 // memchr expects a not-null pointer, early return if the range is empty.
1113 if (haystack.empty()) {
1114 return std::string::npos;
1116 auto pos = static_cast<const unsigned char*>(
1117 ::memchr(haystack.data(), needle, haystack.size()));
1118 return pos == nullptr ? std::string::npos : pos - haystack.data();
1122 inline size_t rfind(const Range<const unsigned char*>& haystack,
1123 const unsigned char& needle) {
1124 // memchr expects a not-null pointer, early return if the range is empty.
1125 if (haystack.empty()) {
1126 return std::string::npos;
1128 auto pos = static_cast<const unsigned char*>(
1129 ::memrchr(haystack.data(), needle, haystack.size()));
1130 return pos == nullptr ? std::string::npos : pos - haystack.data();
1134 size_t qfind_first_of(const Range<T>& haystack,
1135 const Range<T>& needles) {
1136 return qfind_first_of(haystack, needles, AsciiCaseSensitive());
1139 // specialization for StringPiece
1141 inline size_t qfind_first_of(const Range<const char*>& haystack,
1142 const Range<const char*>& needles) {
1143 return detail::qfind_first_byte_of(haystack, needles);
1146 // specialization for ByteRange
1148 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
1149 const Range<const unsigned char*>& needles) {
1150 return detail::qfind_first_byte_of(StringPiece(haystack),
1151 StringPiece(needles));
1154 template<class Key, class Enable>
1158 struct hasher<folly::Range<T*>,
1159 typename std::enable_if<std::is_pod<T>::value, void>::type> {
1160 size_t operator()(folly::Range<T*> r) const {
1161 return hash::SpookyHashV2::Hash64(r.begin(), r.size() * sizeof(T), 0);
1166 * Ubiquitous helper template for knowing what's a string
1168 template <class T> struct IsSomeString {
1169 enum { value = std::is_same<T, std::string>::value
1170 || std::is_same<T, fbstring>::value };
1173 } // !namespace folly
1175 #pragma GCC diagnostic pop
1177 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);