2 * Copyright 2017 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/hash/SpookyHashV2.h>
25 #include <folly/portability/BitsFunctexcept.h>
26 #include <folly/portability/Constexpr.h>
27 #include <folly/portability/String.h>
29 #include <boost/operators.hpp>
30 #include <glog/logging.h>
39 #include <type_traits>
41 // libc++ doesn't provide this header, nor does msvc
42 #ifdef FOLLY_HAVE_BITS_CXXCONFIG_H
43 // This file appears in two locations: inside fbcode and in the
44 // libstdc++ source code (when embedding fbstring as std::string).
45 // To aid in this schizophrenic use, two macros are defined in
47 // _LIBSTDCXX_FBSTRING - Set inside libstdc++. This is useful to
48 // gate use inside fbcode v. libstdc++
49 #include <bits/c++config.h>
52 #include <folly/CpuId.h>
53 #include <folly/Likely.h>
54 #include <folly/Traits.h>
55 #include <folly/detail/RangeCommon.h>
56 #include <folly/detail/RangeSse42.h>
58 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
60 FOLLY_GCC_DISABLE_WARNING("-Wshadow")
68 * Finds the first occurrence of needle in haystack. The algorithm is on
69 * average faster than O(haystack.size() * needle.size()) but not as fast
70 * as Boyer-Moore. On the upside, it does not do any upfront
71 * preprocessing and does not allocate memory.
75 class Comp = std::equal_to<typename Range<Iter>::value_type>>
77 qfind(const Range<Iter>& haystack, const Range<Iter>& needle, Comp eq = Comp());
80 * Finds the first occurrence of needle in haystack. The result is the
81 * offset reported to the beginning of haystack, or string::npos if
82 * needle wasn't found.
86 const Range<Iter>& haystack,
87 const typename Range<Iter>::value_type& needle);
90 * Finds the last occurrence of needle in haystack. The result is the
91 * offset reported to the beginning of haystack, or string::npos if
92 * needle wasn't found.
96 const Range<Iter>& haystack,
97 const typename Range<Iter>::value_type& needle);
100 * Finds the first occurrence of any element of needle in
101 * haystack. The algorithm is O(haystack.size() * needle.size()).
103 template <class Iter>
104 inline size_t qfind_first_of(
105 const Range<Iter>& haystack,
106 const Range<Iter>& needle);
109 * Small internal helper - returns the value just before an iterator.
114 * For random-access iterators, the value before is simply i[-1].
116 template <class Iter>
117 typename std::enable_if<
119 typename std::iterator_traits<Iter>::iterator_category,
120 std::random_access_iterator_tag>::value,
121 typename std::iterator_traits<Iter>::reference>::type
122 value_before(Iter i) {
127 * For all other iterators, we need to use the decrement operator.
129 template <class Iter>
130 typename std::enable_if<
132 typename std::iterator_traits<Iter>::iterator_category,
133 std::random_access_iterator_tag>::value,
134 typename std::iterator_traits<Iter>::reference>::type
135 value_before(Iter i) {
140 * Use IsCharPointer<T>::type to enable const char* or char*.
141 * Use IsCharPointer<T>::const_type to enable only const char*.
144 struct IsCharPointer {};
147 struct IsCharPointer<char*> {
152 struct IsCharPointer<const char*> {
153 typedef int const_type;
157 } // namespace detail
160 * Range abstraction keeping a pair of iterators. We couldn't use
161 * boost's similar range abstraction because we need an API identical
162 * with the former StringPiece class, which is used by a lot of other
163 * code. This abstraction does fulfill the needs of boost's
164 * range-oriented algorithms though.
166 * (Keep memory lifetime in mind when using this class, since it
167 * doesn't manage the data it refers to - just like an iterator
170 template <class Iter>
171 class Range : private boost::totally_ordered<Range<Iter>> {
173 typedef std::size_t size_type;
174 typedef Iter iterator;
175 typedef Iter const_iterator;
176 typedef typename std::remove_reference<
177 typename std::iterator_traits<Iter>::reference>::type value_type;
178 using difference_type = typename std::iterator_traits<Iter>::difference_type;
179 typedef typename std::iterator_traits<Iter>::reference reference;
182 * For MutableStringPiece and MutableByteRange we define StringPiece
183 * and ByteRange as const_range_type (for everything else its just
184 * identity). We do that to enable operations such as find with
185 * args which are const.
187 typedef typename std::conditional<
188 std::is_same<Iter, char*>::value ||
189 std::is_same<Iter, unsigned char*>::value,
190 Range<const value_type*>,
191 Range<Iter>>::type const_range_type;
193 typedef std::char_traits<typename std::remove_const<value_type>::type>
196 static const size_type npos;
198 // Works for all iterators
199 constexpr Range() : b_(), e_() {}
201 constexpr Range(const Range&) = default;
202 constexpr Range(Range&&) = default;
205 // Works for all iterators
206 constexpr Range(Iter start, Iter end) : b_(start), e_(end) {}
208 // Works only for random-access iterators
209 constexpr Range(Iter start, size_t size) : b_(start), e_(start + size) {}
211 #if !__clang__ || __CLANG_PREREQ(3, 7) // Clang 3.6 crashes on this line
212 /* implicit */ Range(std::nullptr_t) = delete;
215 template <class T = Iter, typename detail::IsCharPointer<T>::type = 0>
216 constexpr /* implicit */ Range(Iter str)
217 : b_(str), e_(str + constexpr_strlen(str)) {}
219 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
220 /* implicit */ Range(const std::string& str)
221 : b_(str.data()), e_(b_ + str.size()) {}
223 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
224 Range(const std::string& str, std::string::size_type startFrom) {
225 if (UNLIKELY(startFrom > str.size())) {
226 std::__throw_out_of_range("index out of range");
228 b_ = str.data() + startFrom;
229 e_ = str.data() + str.size();
232 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
234 const std::string& str,
235 std::string::size_type startFrom,
236 std::string::size_type size) {
237 if (UNLIKELY(startFrom > str.size())) {
238 std::__throw_out_of_range("index out of range");
240 b_ = str.data() + startFrom;
241 if (str.size() - startFrom < size) {
242 e_ = str.data() + str.size();
248 Range(const Range& other, size_type first, size_type length = npos)
249 : Range(other.subpiece(first, length)) {}
251 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
252 /* implicit */ Range(const fbstring& str)
253 : b_(str.data()), e_(b_ + str.size()) {}
255 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
256 Range(const fbstring& str, fbstring::size_type startFrom) {
257 if (UNLIKELY(startFrom > str.size())) {
258 std::__throw_out_of_range("index out of range");
260 b_ = str.data() + startFrom;
261 e_ = str.data() + str.size();
264 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
267 fbstring::size_type startFrom,
268 fbstring::size_type size) {
269 if (UNLIKELY(startFrom > str.size())) {
270 std::__throw_out_of_range("index out of range");
272 b_ = str.data() + startFrom;
273 if (str.size() - startFrom < size) {
274 e_ = str.data() + str.size();
280 // Allow implicit conversion from Range<const char*> (aka StringPiece) to
281 // Range<const unsigned char*> (aka ByteRange), as they're both frequently
282 // used to represent ranges of bytes. Allow explicit conversion in the other
286 typename std::enable_if<
287 (std::is_same<Iter, const unsigned char*>::value &&
288 (std::is_same<OtherIter, const char*>::value ||
289 std::is_same<OtherIter, char*>::value)),
291 /* implicit */ Range(const Range<OtherIter>& other)
292 : b_(reinterpret_cast<const unsigned char*>(other.begin())),
293 e_(reinterpret_cast<const unsigned char*>(other.end())) {}
297 typename std::enable_if<
298 (std::is_same<Iter, unsigned char*>::value &&
299 std::is_same<OtherIter, char*>::value),
301 /* implicit */ Range(const Range<OtherIter>& other)
302 : b_(reinterpret_cast<unsigned char*>(other.begin())),
303 e_(reinterpret_cast<unsigned char*>(other.end())) {}
307 typename std::enable_if<
308 (std::is_same<Iter, const char*>::value &&
309 (std::is_same<OtherIter, const unsigned char*>::value ||
310 std::is_same<OtherIter, unsigned char*>::value)),
312 explicit Range(const Range<OtherIter>& other)
313 : b_(reinterpret_cast<const char*>(other.begin())),
314 e_(reinterpret_cast<const char*>(other.end())) {}
318 typename std::enable_if<
319 (std::is_same<Iter, char*>::value &&
320 std::is_same<OtherIter, unsigned char*>::value),
322 explicit Range(const Range<OtherIter>& other)
323 : b_(reinterpret_cast<char*>(other.begin())),
324 e_(reinterpret_cast<char*>(other.end())) {}
326 // Allow implicit conversion from Range<From> to Range<To> if From is
327 // implicitly convertible to To.
330 typename std::enable_if<
331 (!std::is_same<Iter, OtherIter>::value &&
332 std::is_convertible<OtherIter, Iter>::value),
334 constexpr /* implicit */ Range(const Range<OtherIter>& other)
335 : b_(other.begin()), e_(other.end()) {}
337 // Allow explicit conversion from Range<From> to Range<To> if From is
338 // explicitly convertible to To.
341 typename std::enable_if<
342 (!std::is_same<Iter, OtherIter>::value &&
343 !std::is_convertible<OtherIter, Iter>::value &&
344 std::is_constructible<Iter, const OtherIter&>::value),
346 constexpr explicit Range(const Range<OtherIter>& other)
347 : b_(other.begin()), e_(other.end()) {}
350 * Allow explicit construction of Range() from a std::array of a
353 * For instance, this allows constructing StringPiece from a
354 * std::array<char, N> or a std::array<const char, N>
359 typename = typename std::enable_if<
360 std::is_convertible<const T*, Iter>::value>::type>
361 constexpr explicit Range(const std::array<T, N>& array)
362 : b_{array.empty() ? nullptr : &array.at(0)},
363 e_{array.empty() ? nullptr : &array.at(0) + N} {}
368 typename std::enable_if<std::is_convertible<T*, Iter>::value>::type>
369 constexpr explicit Range(std::array<T, N>& array)
370 : b_{array.empty() ? nullptr : &array.at(0)},
371 e_{array.empty() ? nullptr : &array.at(0) + N} {}
373 Range& operator=(const Range& rhs) & = default;
374 Range& operator=(Range&& rhs) & = default;
376 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
377 Range& operator=(std::string&& rhs) = delete;
384 void assign(Iter start, Iter end) {
389 void reset(Iter start, size_type size) {
394 // Works only for Range<const char*>
395 void reset(const std::string& str) {
396 reset(str.data(), str.size());
399 constexpr size_type size() const {
400 // It would be nice to assert(b_ <= e_) here. This can be achieved even
401 // in a C++11 compatible constexpr function:
402 // http://ericniebler.com/2014/09/27/assert-and-constexpr-in-cxx11/
403 // Unfortunately current gcc versions have a bug causing it to reject
404 // this check in a constexpr function:
405 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=71448
406 return size_type(e_ - b_);
408 constexpr size_type walk_size() const {
409 return size_type(std::distance(b_, e_));
411 constexpr bool empty() const {
414 constexpr Iter data() const {
417 constexpr Iter start() const {
420 constexpr Iter begin() const {
423 constexpr Iter end() const {
426 constexpr Iter cbegin() const {
429 constexpr Iter cend() const {
432 value_type& front() {
438 return detail::value_before(e_);
440 const value_type& front() const {
444 const value_type& back() const {
446 return detail::value_before(e_);
448 // Works only for Range<const char*> and Range<char*>
449 std::string str() const {
450 return std::string(b_, size());
452 std::string toString() const {
455 // Works only for Range<const char*> and Range<char*>
456 fbstring fbstr() const {
457 return fbstring(b_, size());
459 fbstring toFbstring() const {
463 const_range_type castToConst() const {
464 return const_range_type(*this);
467 // Works only for Range<const char*> and Range<char*>
468 int compare(const const_range_type& o) const {
469 const size_type tsize = this->size();
470 const size_type osize = o.size();
471 const size_type msize = std::min(tsize, osize);
472 int r = traits_type::compare(data(), o.data(), msize);
473 if (r == 0 && tsize != osize) {
474 // We check the signed bit of the subtraction and bit shift it
475 // to produce either 0 or 2. The subtraction yields the
476 // comparison values of either -1 or 1.
477 r = (static_cast<int>((osize - tsize) >> (CHAR_BIT * sizeof(size_t) - 1))
484 value_type& operator[](size_t i) {
485 DCHECK_GT(size(), i);
489 const value_type& operator[](size_t i) const {
490 DCHECK_GT(size(), i);
494 value_type& at(size_t i) {
496 std::__throw_out_of_range("index out of range");
501 const value_type& at(size_t i) const {
503 std::__throw_out_of_range("index out of range");
508 // Do NOT use this function, which was left behind for backwards
509 // compatibility. Use SpookyHashV2 instead -- it is faster, and produces
510 // a 64-bit hash, which means dramatically fewer collisions in large maps.
511 // (The above advice does not apply if you are targeting a 32-bit system.)
513 // Works only for Range<const char*> and Range<char*>
516 // ** WANT TO GET RID OF THIS LINT? **
518 // A) Use a better hash function (*cough*folly::Hash*cough*), but
519 // only if you don't serialize data in a format that depends on
520 // this formula (ie the writer and reader assume this exact hash
521 // function is used).
523 // B) If you have to use this exact function then make your own hasher
524 // object and copy the body over (see thrift example: D3972362).
525 // https://github.com/facebook/fbthrift/commit/f8ed502e24ab4a32a9d5f266580
526 FOLLY_DEPRECATED("Replace with folly::Hash if the hash is not serialized")
527 uint32_t hash() const {
528 // Taken from fbi/nstring.h:
529 // Quick and dirty bernstein hash...fine for short ascii strings
530 uint32_t hash = 5381;
531 for (size_t ix = 0; ix < size(); ix++) {
532 hash = ((hash << 5) + hash) + b_[ix];
537 void advance(size_type n) {
538 if (UNLIKELY(n > size())) {
539 std::__throw_out_of_range("index out of range");
544 void subtract(size_type n) {
545 if (UNLIKELY(n > size())) {
546 std::__throw_out_of_range("index out of range");
551 Range subpiece(size_type first, size_type length = npos) const {
552 if (UNLIKELY(first > size())) {
553 std::__throw_out_of_range("index out of range");
556 return Range(b_ + first, std::min(length, size() - first));
559 // unchecked versions
560 void uncheckedAdvance(size_type n) {
561 DCHECK_LE(n, size());
565 void uncheckedSubtract(size_type n) {
566 DCHECK_LE(n, size());
570 Range uncheckedSubpiece(size_type first, size_type length = npos) const {
571 DCHECK_LE(first, size());
572 return Range(b_ + first, std::min(length, size() - first));
585 // string work-alike functions
586 size_type find(const_range_type str) const {
587 return qfind(castToConst(), str);
590 size_type find(const_range_type str, size_t pos) const {
592 return std::string::npos;
594 size_t ret = qfind(castToConst().subpiece(pos), str);
595 return ret == npos ? ret : ret + pos;
598 size_type find(Iter s, size_t pos, size_t n) const {
600 return std::string::npos;
602 auto forFinding = castToConst();
604 pos ? forFinding.subpiece(pos) : forFinding, const_range_type(s, n));
605 return ret == npos ? ret : ret + pos;
608 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
609 size_type find(const Iter s) const {
610 return qfind(castToConst(), const_range_type(s));
613 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
614 size_type find(const Iter s, size_t pos) const {
616 return std::string::npos;
618 size_type ret = qfind(castToConst().subpiece(pos), const_range_type(s));
619 return ret == npos ? ret : ret + pos;
622 size_type find(value_type c) const {
623 return qfind(castToConst(), c);
626 size_type rfind(value_type c) const {
627 return folly::rfind(castToConst(), c);
630 size_type find(value_type c, size_t pos) const {
632 return std::string::npos;
634 size_type ret = qfind(castToConst().subpiece(pos), c);
635 return ret == npos ? ret : ret + pos;
638 size_type find_first_of(const_range_type needles) const {
639 return qfind_first_of(castToConst(), needles);
642 size_type find_first_of(const_range_type needles, size_t pos) const {
644 return std::string::npos;
646 size_type ret = qfind_first_of(castToConst().subpiece(pos), needles);
647 return ret == npos ? ret : ret + pos;
650 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
651 size_type find_first_of(Iter needles) const {
652 return find_first_of(const_range_type(needles));
655 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
656 size_type find_first_of(Iter needles, size_t pos) const {
657 return find_first_of(const_range_type(needles), pos);
660 size_type find_first_of(Iter needles, size_t pos, size_t n) const {
661 return find_first_of(const_range_type(needles, n), pos);
664 size_type find_first_of(value_type c) const {
668 size_type find_first_of(value_type c, size_t pos) const {
673 * Determine whether the range contains the given subrange or item.
675 * Note: Call find() directly if the index is needed.
677 bool contains(const const_range_type& other) const {
678 return find(other) != std::string::npos;
681 bool contains(const value_type& other) const {
682 return find(other) != std::string::npos;
685 void swap(Range& rhs) {
686 std::swap(b_, rhs.b_);
687 std::swap(e_, rhs.e_);
691 * Does this Range start with another range?
693 bool startsWith(const const_range_type& other) const {
694 return size() >= other.size() &&
695 castToConst().subpiece(0, other.size()) == other;
697 bool startsWith(value_type c) const {
698 return !empty() && front() == c;
701 template <class Comp>
702 bool startsWith(const const_range_type& other, Comp&& eq) const {
703 if (size() < other.size()) {
706 auto const trunc = subpiece(0, other.size());
708 trunc.begin(), trunc.end(), other.begin(), std::forward<Comp>(eq));
712 * Does this Range end with another range?
714 bool endsWith(const const_range_type& other) const {
715 return size() >= other.size() &&
716 castToConst().subpiece(size() - other.size()) == other;
718 bool endsWith(value_type c) const {
719 return !empty() && back() == c;
722 template <class Comp>
723 bool endsWith(const const_range_type& other, Comp&& eq) const {
724 if (size() < other.size()) {
727 auto const trunc = subpiece(size() - other.size());
729 trunc.begin(), trunc.end(), other.begin(), std::forward<Comp>(eq));
732 template <class Comp>
733 bool equals(const const_range_type& other, Comp&& eq) const {
734 return size() == other.size() &&
735 std::equal(begin(), end(), other.begin(), std::forward<Comp>(eq));
739 * Remove the items in [b, e), as long as this subrange is at the beginning
740 * or end of the Range.
742 * Required for boost::algorithm::trim()
744 void erase(Iter b, Iter e) {
747 } else if (e == e_) {
750 std::__throw_out_of_range("index out of range");
755 * Remove the given prefix and return true if the range starts with the given
756 * prefix; return false otherwise.
758 bool removePrefix(const const_range_type& prefix) {
759 return startsWith(prefix) && (b_ += prefix.size(), true);
761 bool removePrefix(value_type prefix) {
762 return startsWith(prefix) && (++b_, true);
766 * Remove the given suffix and return true if the range ends with the given
767 * suffix; return false otherwise.
769 bool removeSuffix(const const_range_type& suffix) {
770 return endsWith(suffix) && (e_ -= suffix.size(), true);
772 bool removeSuffix(value_type suffix) {
773 return endsWith(suffix) && (--e_, true);
777 * Replaces the content of the range, starting at position 'pos', with
778 * contents of 'replacement'. Entire 'replacement' must fit into the
779 * range. Returns false if 'replacements' does not fit. Example use:
781 * char in[] = "buffer";
782 * auto msp = MutablesStringPiece(input);
783 * EXPECT_TRUE(msp.replaceAt(2, "tt"));
784 * EXPECT_EQ(msp, "butter");
786 * // not enough space
787 * EXPECT_FALSE(msp.replace(msp.size() - 1, "rr"));
788 * EXPECT_EQ(msp, "butter"); // unchanged
790 bool replaceAt(size_t pos, const_range_type replacement) {
791 if (size() < pos + replacement.size()) {
795 std::copy(replacement.begin(), replacement.end(), begin() + pos);
801 * Replaces all occurences of 'source' with 'dest'. Returns number
802 * of replacements made. Source and dest have to have the same
803 * length. Throws if the lengths are different. If 'source' is a
804 * pattern that is overlapping with itself, we perform sequential
805 * replacement: "aaaaaaa".replaceAll("aa", "ba") --> "bababaa"
809 * char in[] = "buffer";
810 * auto msp = MutablesStringPiece(input);
811 * EXPECT_EQ(msp.replaceAll("ff","tt"), 1);
812 * EXPECT_EQ(msp, "butter");
814 size_t replaceAll(const_range_type source, const_range_type dest) {
815 if (source.size() != dest.size()) {
816 throw std::invalid_argument(
817 "replacement must have the same size as source");
825 size_t num_replaced = 0;
826 size_type found = std::string::npos;
827 while ((found = find(source, pos)) != std::string::npos) {
828 replaceAt(found, dest);
829 pos += source.size();
837 * Splits this `Range` `[b, e)` in the position `i` dictated by the next
838 * occurence of `delimiter`.
840 * Returns a new `Range` `[b, i)` and adjusts this range to start right after
841 * the delimiter's position. This range will be empty if the delimiter is not
842 * found. If called on an empty `Range`, both this and the returned `Range`
847 * folly::StringPiece s("sample string for split_next");
848 * auto p = s.split_step(' ');
850 * // prints "string for split_next"
858 * void tokenize(StringPiece s, char delimiter) {
859 * while (!s.empty()) {
860 * cout << s.split_step(delimiter);
864 * @author: Marcelo Juchem <marcelo@fb.com>
866 Range split_step(value_type delimiter) {
867 auto i = std::find(b_, e_, delimiter);
870 b_ = i == e_ ? e_ : std::next(i);
875 Range split_step(Range delimiter) {
876 auto i = find(delimiter);
877 Range result(b_, i == std::string::npos ? size() : i);
879 b_ = result.end() == e_
883 typename std::iterator_traits<Iter>::difference_type(
890 * Convenience method that calls `split_step()` and passes the result to a
891 * functor, returning whatever the functor does. Any additional arguments
892 * `args` passed to this function are perfectly forwarded to the functor.
894 * Say you have a functor with this signature:
896 * Foo fn(Range r) { }
898 * `split_step()`'s return type will be `Foo`. It works just like:
900 * auto result = fn(myRange.split_step(' '));
902 * A functor returning `void` is also supported.
906 * void do_some_parsing(folly::StringPiece s) {
907 * auto version = s.split_step(' ', [&](folly::StringPiece x) {
909 * throw std::invalid_argument("empty string");
911 * return std::strtoull(x.begin(), x.end(), 16);
918 * void parse(folly::StringPiece s) {
919 * s.split_step(' ', parse_field, bar, 10);
920 * s.split_step('\t', parse_field, baz, 20);
922 * auto const kludge = [](folly::StringPiece x, int &out, int def) {
926 * parse_field(x, out, def);
930 * s.split_step('\t', kludge, gaz);
931 * s.split_step(' ', kludge, foo);
940 * static parse_field(folly::StringPiece s, int &out, int def) {
942 * out = folly::to<int>(s);
943 * } catch (std::exception const &) {
949 * @author: Marcelo Juchem <marcelo@fb.com>
951 template <typename TProcess, typename... Args>
952 auto split_step(value_type delimiter, TProcess&& process, Args&&... args)
953 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...)) {
954 return process(split_step(delimiter), std::forward<Args>(args)...);
957 template <typename TProcess, typename... Args>
958 auto split_step(Range delimiter, TProcess&& process, Args&&... args)
959 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...)) {
960 return process(split_step(delimiter), std::forward<Args>(args)...);
967 template <class Iter>
968 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
970 template <class Iter>
971 void swap(Range<Iter>& lhs, Range<Iter>& rhs) {
976 * Create a range from two iterators, with type deduction.
978 template <class Iter>
979 constexpr Range<Iter> range(Iter first, Iter last) {
980 return Range<Iter>(first, last);
984 * Creates a range to reference the contents of a contiguous-storage container.
986 // Use pointers for types with '.data()' member
989 class T = typename std::remove_pointer<
990 decltype(std::declval<Collection>().data())>::type>
991 constexpr Range<T*> range(Collection&& v) {
992 return Range<T*>(v.data(), v.data() + v.size());
995 template <class T, size_t n>
996 constexpr Range<T*> range(T (&array)[n]) {
997 return Range<T*>(array, array + n);
1000 template <class T, size_t n>
1001 constexpr Range<const T*> range(const std::array<T, n>& array) {
1002 return Range<const T*>{array};
1005 typedef Range<const char*> StringPiece;
1006 typedef Range<char*> MutableStringPiece;
1007 typedef Range<const unsigned char*> ByteRange;
1008 typedef Range<unsigned char*> MutableByteRange;
1011 std::basic_ostream<C>& operator<<(
1012 std::basic_ostream<C>& os,
1013 Range<C const*> piece) {
1014 using StreamSize = decltype(os.width());
1015 os.write(piece.start(), static_cast<StreamSize>(piece.size()));
1020 std::basic_ostream<C>& operator<<(std::basic_ostream<C>& os, Range<C*> piece) {
1021 using StreamSize = decltype(os.width());
1022 os.write(piece.start(), static_cast<StreamSize>(piece.size()));
1027 * Templated comparison operators
1030 template <class Iter>
1031 inline bool operator==(const Range<Iter>& lhs, const Range<Iter>& rhs) {
1032 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
1035 template <class Iter>
1036 inline bool operator<(const Range<Iter>& lhs, const Range<Iter>& rhs) {
1037 return lhs.compare(rhs) < 0;
1041 * Specializations of comparison operators for StringPiece
1046 template <class A, class B>
1047 struct ComparableAsStringPiece {
1049 value = (std::is_convertible<A, StringPiece>::value &&
1050 std::is_same<B, StringPiece>::value) ||
1051 (std::is_convertible<B, StringPiece>::value &&
1052 std::is_same<A, StringPiece>::value)
1056 } // namespace detail
1059 * operator== through conversion for Range<const char*>
1061 template <class T, class U>
1062 _t<std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>>
1063 operator==(const T& lhs, const U& rhs) {
1064 return StringPiece(lhs) == StringPiece(rhs);
1068 * operator< through conversion for Range<const char*>
1070 template <class T, class U>
1071 _t<std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>>
1072 operator<(const T& lhs, const U& rhs) {
1073 return StringPiece(lhs) < StringPiece(rhs);
1077 * operator> through conversion for Range<const char*>
1079 template <class T, class U>
1080 _t<std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>>
1081 operator>(const T& lhs, const U& rhs) {
1082 return StringPiece(lhs) > StringPiece(rhs);
1086 * operator< through conversion for Range<const char*>
1088 template <class T, class U>
1089 _t<std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>>
1090 operator<=(const T& lhs, const U& rhs) {
1091 return StringPiece(lhs) <= StringPiece(rhs);
1095 * operator> through conversion for Range<const char*>
1097 template <class T, class U>
1098 _t<std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>>
1099 operator>=(const T& lhs, const U& rhs) {
1100 return StringPiece(lhs) >= StringPiece(rhs);
1104 * Finds substrings faster than brute force by borrowing from Boyer-Moore
1106 template <class Iter, class Comp>
1107 size_t qfind(const Range<Iter>& haystack, const Range<Iter>& needle, Comp eq) {
1108 // Don't use std::search, use a Boyer-Moore-like trick by comparing
1109 // the last characters first
1110 auto const nsize = needle.size();
1111 if (haystack.size() < nsize) {
1112 return std::string::npos;
1117 auto const nsize_1 = nsize - 1;
1118 auto const lastNeedle = needle[nsize_1];
1120 // Boyer-Moore skip value for the last char in the needle. Zero is
1121 // not a valid value; skip will be computed the first time it's
1123 std::string::size_type skip = 0;
1125 auto i = haystack.begin();
1126 auto iEnd = haystack.end() - nsize_1;
1129 // Boyer-Moore: match the last element in the needle
1130 while (!eq(i[nsize_1], lastNeedle)) {
1133 return std::string::npos;
1136 // Here we know that the last char matches
1137 // Continue in pedestrian mode
1138 for (size_t j = 0;;) {
1140 if (!eq(i[j], needle[j])) {
1141 // Not found, we can skip
1142 // Compute the skip value lazily
1145 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
1152 // Check if done searching
1155 return size_t(i - haystack.begin());
1159 return std::string::npos;
1164 inline size_t qfind_first_byte_of(
1165 const StringPiece haystack,
1166 const StringPiece needles) {
1167 static auto const qfind_first_byte_of_fn = folly::CpuId().sse42()
1168 ? qfind_first_byte_of_sse42
1169 : qfind_first_byte_of_nosse;
1170 return qfind_first_byte_of_fn(haystack, needles);
1173 } // namespace detail
1175 template <class Iter, class Comp>
1176 size_t qfind_first_of(
1177 const Range<Iter>& haystack,
1178 const Range<Iter>& needles,
1180 auto ret = std::find_first_of(
1181 haystack.begin(), haystack.end(), needles.begin(), needles.end(), eq);
1182 return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
1185 struct AsciiCaseSensitive {
1186 bool operator()(char lhs, char rhs) const {
1192 * Check if two ascii characters are case insensitive equal.
1193 * The difference between the lower/upper case characters are the 6-th bit.
1194 * We also check they are alpha chars, in case of xor = 32.
1196 struct AsciiCaseInsensitive {
1197 bool operator()(char lhs, char rhs) const {
1206 return (k >= 'a' && k <= 'z');
1210 template <class Iter>
1212 const Range<Iter>& haystack,
1213 const typename Range<Iter>::value_type& needle) {
1214 auto pos = std::find(haystack.begin(), haystack.end(), needle);
1215 return pos == haystack.end() ? std::string::npos : pos - haystack.data();
1218 template <class Iter>
1220 const Range<Iter>& haystack,
1221 const typename Range<Iter>::value_type& needle) {
1222 for (auto i = haystack.size(); i-- > 0;) {
1223 if (haystack[i] == needle) {
1227 return std::string::npos;
1230 // specialization for StringPiece
1232 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
1233 // memchr expects a not-null pointer, early return if the range is empty.
1234 if (haystack.empty()) {
1235 return std::string::npos;
1237 auto pos = static_cast<const char*>(
1238 ::memchr(haystack.data(), needle, haystack.size()));
1239 return pos == nullptr ? std::string::npos : pos - haystack.data();
1243 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
1244 // memchr expects a not-null pointer, early return if the range is empty.
1245 if (haystack.empty()) {
1246 return std::string::npos;
1248 auto pos = static_cast<const char*>(
1249 ::memrchr(haystack.data(), needle, haystack.size()));
1250 return pos == nullptr ? std::string::npos : pos - haystack.data();
1253 // specialization for ByteRange
1255 inline size_t qfind(
1256 const Range<const unsigned char*>& haystack,
1257 const unsigned char& needle) {
1258 // memchr expects a not-null pointer, early return if the range is empty.
1259 if (haystack.empty()) {
1260 return std::string::npos;
1262 auto pos = static_cast<const unsigned char*>(
1263 ::memchr(haystack.data(), needle, haystack.size()));
1264 return pos == nullptr ? std::string::npos : pos - haystack.data();
1268 inline size_t rfind(
1269 const Range<const unsigned char*>& haystack,
1270 const unsigned char& needle) {
1271 // memchr expects a not-null pointer, early return if the range is empty.
1272 if (haystack.empty()) {
1273 return std::string::npos;
1275 auto pos = static_cast<const unsigned char*>(
1276 ::memrchr(haystack.data(), needle, haystack.size()));
1277 return pos == nullptr ? std::string::npos : pos - haystack.data();
1280 template <class Iter>
1281 size_t qfind_first_of(const Range<Iter>& haystack, const Range<Iter>& needles) {
1282 return qfind_first_of(haystack, needles, AsciiCaseSensitive());
1285 // specialization for StringPiece
1287 inline size_t qfind_first_of(
1288 const Range<const char*>& haystack,
1289 const Range<const char*>& needles) {
1290 return detail::qfind_first_byte_of(haystack, needles);
1293 // specialization for ByteRange
1295 inline size_t qfind_first_of(
1296 const Range<const unsigned char*>& haystack,
1297 const Range<const unsigned char*>& needles) {
1298 return detail::qfind_first_byte_of(
1299 StringPiece(haystack), StringPiece(needles));
1302 template <class Key, class Enable>
1308 typename std::enable_if<std::is_pod<T>::value, void>::type> {
1309 size_t operator()(folly::Range<T*> r) const {
1310 return hash::SpookyHashV2::Hash64(r.begin(), r.size() * sizeof(T), 0);
1315 * Ubiquitous helper template for knowing what's a string
1318 struct IsSomeString {
1321 std::is_same<T, std::string>::value || std::is_same<T, fbstring>::value
1325 } // namespace folly
1329 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);