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 constexpr /* implicit */ Range(Iter str)
216 : b_(str), e_(str + constexpr_strlen(str)) {
218 std::is_same<int, typename detail::IsCharPointer<Iter>::type>::value,
219 "This constructor is only available for character ranges");
222 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
223 /* implicit */ Range(const std::string& str)
224 : b_(str.data()), e_(b_ + str.size()) {}
226 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
227 Range(const std::string& str, std::string::size_type startFrom) {
228 if (UNLIKELY(startFrom > str.size())) {
229 std::__throw_out_of_range("index out of range");
231 b_ = str.data() + startFrom;
232 e_ = str.data() + str.size();
235 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
237 const std::string& str,
238 std::string::size_type startFrom,
239 std::string::size_type size) {
240 if (UNLIKELY(startFrom > str.size())) {
241 std::__throw_out_of_range("index out of range");
243 b_ = str.data() + startFrom;
244 if (str.size() - startFrom < size) {
245 e_ = str.data() + str.size();
251 Range(const Range& other, size_type first, size_type length = npos)
252 : Range(other.subpiece(first, length)) {}
254 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
255 /* implicit */ Range(const fbstring& str)
256 : b_(str.data()), e_(b_ + str.size()) {}
258 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
259 Range(const fbstring& str, fbstring::size_type startFrom) {
260 if (UNLIKELY(startFrom > str.size())) {
261 std::__throw_out_of_range("index out of range");
263 b_ = str.data() + startFrom;
264 e_ = str.data() + str.size();
267 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
270 fbstring::size_type startFrom,
271 fbstring::size_type size) {
272 if (UNLIKELY(startFrom > str.size())) {
273 std::__throw_out_of_range("index out of range");
275 b_ = str.data() + startFrom;
276 if (str.size() - startFrom < size) {
277 e_ = str.data() + str.size();
283 // Allow implicit conversion from Range<const char*> (aka StringPiece) to
284 // Range<const unsigned char*> (aka ByteRange), as they're both frequently
285 // used to represent ranges of bytes. Allow explicit conversion in the other
289 typename std::enable_if<
290 (std::is_same<Iter, const unsigned char*>::value &&
291 (std::is_same<OtherIter, const char*>::value ||
292 std::is_same<OtherIter, char*>::value)),
294 /* implicit */ Range(const Range<OtherIter>& other)
295 : b_(reinterpret_cast<const unsigned char*>(other.begin())),
296 e_(reinterpret_cast<const unsigned char*>(other.end())) {}
300 typename std::enable_if<
301 (std::is_same<Iter, unsigned char*>::value &&
302 std::is_same<OtherIter, char*>::value),
304 /* implicit */ Range(const Range<OtherIter>& other)
305 : b_(reinterpret_cast<unsigned char*>(other.begin())),
306 e_(reinterpret_cast<unsigned char*>(other.end())) {}
310 typename std::enable_if<
311 (std::is_same<Iter, const char*>::value &&
312 (std::is_same<OtherIter, const unsigned char*>::value ||
313 std::is_same<OtherIter, unsigned char*>::value)),
315 explicit Range(const Range<OtherIter>& other)
316 : b_(reinterpret_cast<const char*>(other.begin())),
317 e_(reinterpret_cast<const char*>(other.end())) {}
321 typename std::enable_if<
322 (std::is_same<Iter, char*>::value &&
323 std::is_same<OtherIter, unsigned char*>::value),
325 explicit Range(const Range<OtherIter>& other)
326 : b_(reinterpret_cast<char*>(other.begin())),
327 e_(reinterpret_cast<char*>(other.end())) {}
329 // Allow implicit conversion from Range<From> to Range<To> if From is
330 // implicitly convertible to To.
333 typename std::enable_if<
334 (!std::is_same<Iter, OtherIter>::value &&
335 std::is_convertible<OtherIter, Iter>::value),
337 constexpr /* implicit */ Range(const Range<OtherIter>& other)
338 : b_(other.begin()), e_(other.end()) {}
340 // Allow explicit conversion from Range<From> to Range<To> if From is
341 // explicitly convertible to To.
344 typename std::enable_if<
345 (!std::is_same<Iter, OtherIter>::value &&
346 !std::is_convertible<OtherIter, Iter>::value &&
347 std::is_constructible<Iter, const OtherIter&>::value),
349 constexpr explicit Range(const Range<OtherIter>& other)
350 : b_(other.begin()), e_(other.end()) {}
353 * Allow explicit construction of Range() from a std::array of a
356 * For instance, this allows constructing StringPiece from a
357 * std::array<char, N> or a std::array<const char, N>
362 typename = typename std::enable_if<
363 std::is_convertible<const T*, Iter>::value>::type>
364 constexpr explicit Range(const std::array<T, N>& array)
365 : b_{array.empty() ? nullptr : &array.at(0)},
366 e_{array.empty() ? nullptr : &array.at(0) + N} {}
371 typename std::enable_if<std::is_convertible<T*, Iter>::value>::type>
372 constexpr explicit Range(std::array<T, N>& array)
373 : b_{array.empty() ? nullptr : &array.at(0)},
374 e_{array.empty() ? nullptr : &array.at(0) + N} {}
376 Range& operator=(const Range& rhs) & = default;
377 Range& operator=(Range&& rhs) & = default;
379 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
380 Range& operator=(std::string&& rhs) = delete;
387 void assign(Iter start, Iter end) {
392 void reset(Iter start, size_type size) {
397 // Works only for Range<const char*>
398 void reset(const std::string& str) {
399 reset(str.data(), str.size());
402 constexpr size_type size() const {
403 // It would be nice to assert(b_ <= e_) here. This can be achieved even
404 // in a C++11 compatible constexpr function:
405 // http://ericniebler.com/2014/09/27/assert-and-constexpr-in-cxx11/
406 // Unfortunately current gcc versions have a bug causing it to reject
407 // this check in a constexpr function:
408 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=71448
409 return size_type(e_ - b_);
411 constexpr size_type walk_size() const {
412 return size_type(std::distance(b_, e_));
414 constexpr bool empty() const {
417 constexpr Iter data() const {
420 constexpr Iter start() const {
423 constexpr Iter begin() const {
426 constexpr Iter end() const {
429 constexpr Iter cbegin() const {
432 constexpr Iter cend() const {
435 value_type& front() {
441 return detail::value_before(e_);
443 const value_type& front() const {
447 const value_type& back() const {
449 return detail::value_before(e_);
451 // Works only for Range<const char*> and Range<char*>
452 std::string str() const {
453 return std::string(b_, size());
455 std::string toString() const {
458 // Works only for Range<const char*> and Range<char*>
459 fbstring fbstr() const {
460 return fbstring(b_, size());
462 fbstring toFbstring() const {
466 const_range_type castToConst() const {
467 return const_range_type(*this);
470 // Works only for Range<const char*> and Range<char*>
471 int compare(const const_range_type& o) const {
472 const size_type tsize = this->size();
473 const size_type osize = o.size();
474 const size_type msize = std::min(tsize, osize);
475 int r = traits_type::compare(data(), o.data(), msize);
476 if (r == 0 && tsize != osize) {
477 // We check the signed bit of the subtraction and bit shift it
478 // to produce either 0 or 2. The subtraction yields the
479 // comparison values of either -1 or 1.
480 r = (static_cast<int>((osize - tsize) >> (CHAR_BIT * sizeof(size_t) - 1))
487 value_type& operator[](size_t i) {
488 DCHECK_GT(size(), i);
492 const value_type& operator[](size_t i) const {
493 DCHECK_GT(size(), i);
497 value_type& at(size_t i) {
499 std::__throw_out_of_range("index out of range");
504 const value_type& at(size_t i) const {
506 std::__throw_out_of_range("index out of range");
511 // Do NOT use this function, which was left behind for backwards
512 // compatibility. Use SpookyHashV2 instead -- it is faster, and produces
513 // a 64-bit hash, which means dramatically fewer collisions in large maps.
514 // (The above advice does not apply if you are targeting a 32-bit system.)
516 // Works only for Range<const char*> and Range<char*>
519 // ** WANT TO GET RID OF THIS LINT? **
521 // A) Use a better hash function (*cough*folly::Hash*cough*), but
522 // only if you don't serialize data in a format that depends on
523 // this formula (ie the writer and reader assume this exact hash
524 // function is used).
526 // B) If you have to use this exact function then make your own hasher
527 // object and copy the body over (see thrift example: D3972362).
528 // https://github.com/facebook/fbthrift/commit/f8ed502e24ab4a32a9d5f266580
529 FOLLY_DEPRECATED("Replace with folly::Hash if the hash is not serialized")
530 uint32_t hash() const {
531 // Taken from fbi/nstring.h:
532 // Quick and dirty bernstein hash...fine for short ascii strings
533 uint32_t hash = 5381;
534 for (size_t ix = 0; ix < size(); ix++) {
535 hash = ((hash << 5) + hash) + b_[ix];
540 void advance(size_type n) {
541 if (UNLIKELY(n > size())) {
542 std::__throw_out_of_range("index out of range");
547 void subtract(size_type n) {
548 if (UNLIKELY(n > size())) {
549 std::__throw_out_of_range("index out of range");
554 Range subpiece(size_type first, size_type length = npos) const {
555 if (UNLIKELY(first > size())) {
556 std::__throw_out_of_range("index out of range");
559 return Range(b_ + first, std::min(length, size() - first));
562 // unchecked versions
563 void uncheckedAdvance(size_type n) {
564 DCHECK_LE(n, size());
568 void uncheckedSubtract(size_type n) {
569 DCHECK_LE(n, size());
573 Range uncheckedSubpiece(size_type first, size_type length = npos) const {
574 DCHECK_LE(first, size());
575 return Range(b_ + first, std::min(length, size() - first));
588 // string work-alike functions
589 size_type find(const_range_type str) const {
590 return qfind(castToConst(), str);
593 size_type find(const_range_type str, size_t pos) const {
595 return std::string::npos;
597 size_t ret = qfind(castToConst().subpiece(pos), str);
598 return ret == npos ? ret : ret + pos;
601 size_type find(Iter s, size_t pos, size_t n) const {
603 return std::string::npos;
605 auto forFinding = castToConst();
607 pos ? forFinding.subpiece(pos) : forFinding, const_range_type(s, n));
608 return ret == npos ? ret : ret + pos;
611 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
612 size_type find(const Iter s) const {
613 return qfind(castToConst(), const_range_type(s));
616 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
617 size_type find(const Iter s, size_t pos) const {
619 return std::string::npos;
621 size_type ret = qfind(castToConst().subpiece(pos), const_range_type(s));
622 return ret == npos ? ret : ret + pos;
625 size_type find(value_type c) const {
626 return qfind(castToConst(), c);
629 size_type rfind(value_type c) const {
630 return folly::rfind(castToConst(), c);
633 size_type find(value_type c, size_t pos) const {
635 return std::string::npos;
637 size_type ret = qfind(castToConst().subpiece(pos), c);
638 return ret == npos ? ret : ret + pos;
641 size_type find_first_of(const_range_type needles) const {
642 return qfind_first_of(castToConst(), needles);
645 size_type find_first_of(const_range_type needles, size_t pos) const {
647 return std::string::npos;
649 size_type ret = qfind_first_of(castToConst().subpiece(pos), needles);
650 return ret == npos ? ret : ret + pos;
653 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
654 size_type find_first_of(Iter needles) const {
655 return find_first_of(const_range_type(needles));
658 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
659 size_type find_first_of(Iter needles, size_t pos) const {
660 return find_first_of(const_range_type(needles), pos);
663 size_type find_first_of(Iter needles, size_t pos, size_t n) const {
664 return find_first_of(const_range_type(needles, n), pos);
667 size_type find_first_of(value_type c) const {
671 size_type find_first_of(value_type c, size_t pos) const {
676 * Determine whether the range contains the given subrange or item.
678 * Note: Call find() directly if the index is needed.
680 bool contains(const const_range_type& other) const {
681 return find(other) != std::string::npos;
684 bool contains(const value_type& other) const {
685 return find(other) != std::string::npos;
688 void swap(Range& rhs) {
689 std::swap(b_, rhs.b_);
690 std::swap(e_, rhs.e_);
694 * Does this Range start with another range?
696 bool startsWith(const const_range_type& other) const {
697 return size() >= other.size() &&
698 castToConst().subpiece(0, other.size()) == other;
700 bool startsWith(value_type c) const {
701 return !empty() && front() == c;
704 template <class Comp>
705 bool startsWith(const const_range_type& other, Comp&& eq) const {
706 if (size() < other.size()) {
709 auto const trunc = subpiece(0, other.size());
711 trunc.begin(), trunc.end(), other.begin(), std::forward<Comp>(eq));
715 * Does this Range end with another range?
717 bool endsWith(const const_range_type& other) const {
718 return size() >= other.size() &&
719 castToConst().subpiece(size() - other.size()) == other;
721 bool endsWith(value_type c) const {
722 return !empty() && back() == c;
725 template <class Comp>
726 bool endsWith(const const_range_type& other, Comp&& eq) const {
727 if (size() < other.size()) {
730 auto const trunc = subpiece(size() - other.size());
732 trunc.begin(), trunc.end(), other.begin(), std::forward<Comp>(eq));
735 template <class Comp>
736 bool equals(const const_range_type& other, Comp&& eq) const {
737 return size() == other.size() &&
738 std::equal(begin(), end(), other.begin(), std::forward<Comp>(eq));
742 * Remove the items in [b, e), as long as this subrange is at the beginning
743 * or end of the Range.
745 * Required for boost::algorithm::trim()
747 void erase(Iter b, Iter e) {
750 } else if (e == e_) {
753 std::__throw_out_of_range("index out of range");
758 * Remove the given prefix and return true if the range starts with the given
759 * prefix; return false otherwise.
761 bool removePrefix(const const_range_type& prefix) {
762 return startsWith(prefix) && (b_ += prefix.size(), true);
764 bool removePrefix(value_type prefix) {
765 return startsWith(prefix) && (++b_, true);
769 * Remove the given suffix and return true if the range ends with the given
770 * suffix; return false otherwise.
772 bool removeSuffix(const const_range_type& suffix) {
773 return endsWith(suffix) && (e_ -= suffix.size(), true);
775 bool removeSuffix(value_type suffix) {
776 return endsWith(suffix) && (--e_, true);
780 * Replaces the content of the range, starting at position 'pos', with
781 * contents of 'replacement'. Entire 'replacement' must fit into the
782 * range. Returns false if 'replacements' does not fit. Example use:
784 * char in[] = "buffer";
785 * auto msp = MutablesStringPiece(input);
786 * EXPECT_TRUE(msp.replaceAt(2, "tt"));
787 * EXPECT_EQ(msp, "butter");
789 * // not enough space
790 * EXPECT_FALSE(msp.replace(msp.size() - 1, "rr"));
791 * EXPECT_EQ(msp, "butter"); // unchanged
793 bool replaceAt(size_t pos, const_range_type replacement) {
794 if (size() < pos + replacement.size()) {
798 std::copy(replacement.begin(), replacement.end(), begin() + pos);
804 * Replaces all occurences of 'source' with 'dest'. Returns number
805 * of replacements made. Source and dest have to have the same
806 * length. Throws if the lengths are different. If 'source' is a
807 * pattern that is overlapping with itself, we perform sequential
808 * replacement: "aaaaaaa".replaceAll("aa", "ba") --> "bababaa"
812 * char in[] = "buffer";
813 * auto msp = MutablesStringPiece(input);
814 * EXPECT_EQ(msp.replaceAll("ff","tt"), 1);
815 * EXPECT_EQ(msp, "butter");
817 size_t replaceAll(const_range_type source, const_range_type dest) {
818 if (source.size() != dest.size()) {
819 throw std::invalid_argument(
820 "replacement must have the same size as source");
828 size_t num_replaced = 0;
829 size_type found = std::string::npos;
830 while ((found = find(source, pos)) != std::string::npos) {
831 replaceAt(found, dest);
832 pos += source.size();
840 * Splits this `Range` `[b, e)` in the position `i` dictated by the next
841 * occurence of `delimiter`.
843 * Returns a new `Range` `[b, i)` and adjusts this range to start right after
844 * the delimiter's position. This range will be empty if the delimiter is not
845 * found. If called on an empty `Range`, both this and the returned `Range`
850 * folly::StringPiece s("sample string for split_next");
851 * auto p = s.split_step(' ');
853 * // prints "string for split_next"
861 * void tokenize(StringPiece s, char delimiter) {
862 * while (!s.empty()) {
863 * cout << s.split_step(delimiter);
867 * @author: Marcelo Juchem <marcelo@fb.com>
869 Range split_step(value_type delimiter) {
870 auto i = std::find(b_, e_, delimiter);
873 b_ = i == e_ ? e_ : std::next(i);
878 Range split_step(Range delimiter) {
879 auto i = find(delimiter);
880 Range result(b_, i == std::string::npos ? size() : i);
882 b_ = result.end() == e_
886 typename std::iterator_traits<Iter>::difference_type(
893 * Convenience method that calls `split_step()` and passes the result to a
894 * functor, returning whatever the functor does. Any additional arguments
895 * `args` passed to this function are perfectly forwarded to the functor.
897 * Say you have a functor with this signature:
899 * Foo fn(Range r) { }
901 * `split_step()`'s return type will be `Foo`. It works just like:
903 * auto result = fn(myRange.split_step(' '));
905 * A functor returning `void` is also supported.
909 * void do_some_parsing(folly::StringPiece s) {
910 * auto version = s.split_step(' ', [&](folly::StringPiece x) {
912 * throw std::invalid_argument("empty string");
914 * return std::strtoull(x.begin(), x.end(), 16);
921 * void parse(folly::StringPiece s) {
922 * s.split_step(' ', parse_field, bar, 10);
923 * s.split_step('\t', parse_field, baz, 20);
925 * auto const kludge = [](folly::StringPiece x, int &out, int def) {
929 * parse_field(x, out, def);
933 * s.split_step('\t', kludge, gaz);
934 * s.split_step(' ', kludge, foo);
943 * static parse_field(folly::StringPiece s, int &out, int def) {
945 * out = folly::to<int>(s);
946 * } catch (std::exception const &) {
952 * @author: Marcelo Juchem <marcelo@fb.com>
954 template <typename TProcess, typename... Args>
955 auto split_step(value_type delimiter, TProcess&& process, Args&&... args)
956 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...)) {
957 return process(split_step(delimiter), std::forward<Args>(args)...);
960 template <typename TProcess, typename... Args>
961 auto split_step(Range delimiter, TProcess&& process, Args&&... args)
962 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...)) {
963 return process(split_step(delimiter), std::forward<Args>(args)...);
970 template <class Iter>
971 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
973 template <class Iter>
974 void swap(Range<Iter>& lhs, Range<Iter>& rhs) {
979 * Create a range from two iterators, with type deduction.
981 template <class Iter>
982 constexpr Range<Iter> range(Iter first, Iter last) {
983 return Range<Iter>(first, last);
987 * Creates a range to reference the contents of a contiguous-storage container.
989 // Use pointers for types with '.data()' member
992 class T = typename std::remove_pointer<
993 decltype(std::declval<Collection>().data())>::type>
994 constexpr Range<T*> range(Collection&& v) {
995 return Range<T*>(v.data(), v.data() + v.size());
998 template <class T, size_t n>
999 constexpr Range<T*> range(T (&array)[n]) {
1000 return Range<T*>(array, array + n);
1003 template <class T, size_t n>
1004 constexpr Range<const T*> range(const std::array<T, n>& array) {
1005 return Range<const T*>{array};
1008 typedef Range<const char*> StringPiece;
1009 typedef Range<char*> MutableStringPiece;
1010 typedef Range<const unsigned char*> ByteRange;
1011 typedef Range<unsigned char*> MutableByteRange;
1014 std::basic_ostream<C>& operator<<(
1015 std::basic_ostream<C>& os,
1016 Range<C const*> piece) {
1017 using StreamSize = decltype(os.width());
1018 os.write(piece.start(), static_cast<StreamSize>(piece.size()));
1023 std::basic_ostream<C>& operator<<(std::basic_ostream<C>& os, Range<C*> piece) {
1024 using StreamSize = decltype(os.width());
1025 os.write(piece.start(), static_cast<StreamSize>(piece.size()));
1030 * Templated comparison operators
1033 template <class Iter>
1034 inline bool operator==(const Range<Iter>& lhs, const Range<Iter>& rhs) {
1035 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
1038 template <class Iter>
1039 inline bool operator<(const Range<Iter>& lhs, const Range<Iter>& rhs) {
1040 return lhs.compare(rhs) < 0;
1044 * Specializations of comparison operators for StringPiece
1049 template <class A, class B>
1050 struct ComparableAsStringPiece {
1052 value = (std::is_convertible<A, StringPiece>::value &&
1053 std::is_same<B, StringPiece>::value) ||
1054 (std::is_convertible<B, StringPiece>::value &&
1055 std::is_same<A, StringPiece>::value)
1059 } // namespace detail
1062 * operator== through conversion for Range<const char*>
1064 template <class T, class U>
1065 _t<std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>>
1066 operator==(const T& lhs, const U& rhs) {
1067 return StringPiece(lhs) == StringPiece(rhs);
1071 * operator< through conversion for Range<const char*>
1073 template <class T, class U>
1074 _t<std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>>
1075 operator<(const T& lhs, const U& rhs) {
1076 return StringPiece(lhs) < StringPiece(rhs);
1080 * operator> through conversion for Range<const char*>
1082 template <class T, class U>
1083 _t<std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>>
1084 operator>(const T& lhs, const U& rhs) {
1085 return StringPiece(lhs) > StringPiece(rhs);
1089 * operator< through conversion for Range<const char*>
1091 template <class T, class U>
1092 _t<std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>>
1093 operator<=(const T& lhs, const U& rhs) {
1094 return StringPiece(lhs) <= StringPiece(rhs);
1098 * operator> through conversion for Range<const char*>
1100 template <class T, class U>
1101 _t<std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>>
1102 operator>=(const T& lhs, const U& rhs) {
1103 return StringPiece(lhs) >= StringPiece(rhs);
1107 * Finds substrings faster than brute force by borrowing from Boyer-Moore
1109 template <class Iter, class Comp>
1110 size_t qfind(const Range<Iter>& haystack, const Range<Iter>& needle, Comp eq) {
1111 // Don't use std::search, use a Boyer-Moore-like trick by comparing
1112 // the last characters first
1113 auto const nsize = needle.size();
1114 if (haystack.size() < nsize) {
1115 return std::string::npos;
1120 auto const nsize_1 = nsize - 1;
1121 auto const lastNeedle = needle[nsize_1];
1123 // Boyer-Moore skip value for the last char in the needle. Zero is
1124 // not a valid value; skip will be computed the first time it's
1126 std::string::size_type skip = 0;
1128 auto i = haystack.begin();
1129 auto iEnd = haystack.end() - nsize_1;
1132 // Boyer-Moore: match the last element in the needle
1133 while (!eq(i[nsize_1], lastNeedle)) {
1136 return std::string::npos;
1139 // Here we know that the last char matches
1140 // Continue in pedestrian mode
1141 for (size_t j = 0;;) {
1143 if (!eq(i[j], needle[j])) {
1144 // Not found, we can skip
1145 // Compute the skip value lazily
1148 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
1155 // Check if done searching
1158 return size_t(i - haystack.begin());
1162 return std::string::npos;
1167 inline size_t qfind_first_byte_of(
1168 const StringPiece haystack,
1169 const StringPiece needles) {
1170 static auto const qfind_first_byte_of_fn = folly::CpuId().sse42()
1171 ? qfind_first_byte_of_sse42
1172 : qfind_first_byte_of_nosse;
1173 return qfind_first_byte_of_fn(haystack, needles);
1176 } // namespace detail
1178 template <class Iter, class Comp>
1179 size_t qfind_first_of(
1180 const Range<Iter>& haystack,
1181 const Range<Iter>& needles,
1183 auto ret = std::find_first_of(
1184 haystack.begin(), haystack.end(), needles.begin(), needles.end(), eq);
1185 return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
1188 struct AsciiCaseSensitive {
1189 bool operator()(char lhs, char rhs) const {
1195 * Check if two ascii characters are case insensitive equal.
1196 * The difference between the lower/upper case characters are the 6-th bit.
1197 * We also check they are alpha chars, in case of xor = 32.
1199 struct AsciiCaseInsensitive {
1200 bool operator()(char lhs, char rhs) const {
1209 return (k >= 'a' && k <= 'z');
1213 template <class Iter>
1215 const Range<Iter>& haystack,
1216 const typename Range<Iter>::value_type& needle) {
1217 auto pos = std::find(haystack.begin(), haystack.end(), needle);
1218 return pos == haystack.end() ? std::string::npos : pos - haystack.data();
1221 template <class Iter>
1223 const Range<Iter>& haystack,
1224 const typename Range<Iter>::value_type& needle) {
1225 for (auto i = haystack.size(); i-- > 0;) {
1226 if (haystack[i] == needle) {
1230 return std::string::npos;
1233 // specialization for StringPiece
1235 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
1236 // memchr expects a not-null pointer, early return if the range is empty.
1237 if (haystack.empty()) {
1238 return std::string::npos;
1240 auto pos = static_cast<const char*>(
1241 ::memchr(haystack.data(), needle, haystack.size()));
1242 return pos == nullptr ? std::string::npos : pos - haystack.data();
1246 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
1247 // memchr expects a not-null pointer, early return if the range is empty.
1248 if (haystack.empty()) {
1249 return std::string::npos;
1251 auto pos = static_cast<const char*>(
1252 ::memrchr(haystack.data(), needle, haystack.size()));
1253 return pos == nullptr ? std::string::npos : pos - haystack.data();
1256 // specialization for ByteRange
1258 inline size_t qfind(
1259 const Range<const unsigned char*>& haystack,
1260 const unsigned char& needle) {
1261 // memchr expects a not-null pointer, early return if the range is empty.
1262 if (haystack.empty()) {
1263 return std::string::npos;
1265 auto pos = static_cast<const unsigned char*>(
1266 ::memchr(haystack.data(), needle, haystack.size()));
1267 return pos == nullptr ? std::string::npos : pos - haystack.data();
1271 inline size_t rfind(
1272 const Range<const unsigned char*>& haystack,
1273 const unsigned char& needle) {
1274 // memchr expects a not-null pointer, early return if the range is empty.
1275 if (haystack.empty()) {
1276 return std::string::npos;
1278 auto pos = static_cast<const unsigned char*>(
1279 ::memrchr(haystack.data(), needle, haystack.size()));
1280 return pos == nullptr ? std::string::npos : pos - haystack.data();
1283 template <class Iter>
1284 size_t qfind_first_of(const Range<Iter>& haystack, const Range<Iter>& needles) {
1285 return qfind_first_of(haystack, needles, AsciiCaseSensitive());
1288 // specialization for StringPiece
1290 inline size_t qfind_first_of(
1291 const Range<const char*>& haystack,
1292 const Range<const char*>& needles) {
1293 return detail::qfind_first_byte_of(haystack, needles);
1296 // specialization for ByteRange
1298 inline size_t qfind_first_of(
1299 const Range<const unsigned char*>& haystack,
1300 const Range<const unsigned char*>& needles) {
1301 return detail::qfind_first_byte_of(
1302 StringPiece(haystack), StringPiece(needles));
1305 template <class Key, class Enable>
1311 typename std::enable_if<std::is_pod<T>::value, void>::type> {
1312 size_t operator()(folly::Range<T*> r) const {
1313 return hash::SpookyHashV2::Hash64(r.begin(), r.size() * sizeof(T), 0);
1318 * Ubiquitous helper template for knowing what's a string
1321 struct IsSomeString {
1324 std::is_same<T, std::string>::value || std::is_same<T, fbstring>::value
1329 * _sp is a user-defined literal suffix to make an appropriate Range
1330 * specialization from a literal string.
1332 * Modeled after C++17's `sv` suffix.
1334 inline namespace literals {
1335 inline namespace string_piece_literals {
1336 constexpr Range<char const*> operator"" _sp(
1338 size_t len) noexcept {
1339 return Range<char const*>(str, len);
1342 constexpr Range<char16_t const*> operator"" _sp(
1343 char16_t const* str,
1344 size_t len) noexcept {
1345 return Range<char16_t const*>(str, len);
1348 constexpr Range<char32_t const*> operator"" _sp(
1349 char32_t const* str,
1350 size_t len) noexcept {
1351 return Range<char32_t const*>(str, len);
1354 constexpr Range<wchar_t const*> operator"" _sp(
1356 size_t len) noexcept {
1357 return Range<wchar_t const*>(str, len);
1359 } // inline namespace string_piece_literals
1360 } // inline namespace literals
1362 } // namespace folly
1366 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);