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/Portability.h>
23 #include <folly/hash/SpookyHashV2.h>
24 #include <folly/portability/BitsFunctexcept.h>
25 #include <folly/portability/Constexpr.h>
26 #include <folly/portability/String.h>
28 #include <boost/operators.hpp>
29 #include <glog/logging.h>
39 #include <type_traits>
41 #include <folly/CpuId.h>
42 #include <folly/Likely.h>
43 #include <folly/Traits.h>
44 #include <folly/detail/RangeCommon.h>
45 #include <folly/detail/RangeSse42.h>
47 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
49 FOLLY_GCC_DISABLE_WARNING("-Wshadow")
54 * Ubiquitous helper template for knowing what's a string.
57 struct IsSomeString : std::false_type {};
60 struct IsSomeString<std::string> : std::true_type {};
66 * Finds the first occurrence of needle in haystack. The algorithm is on
67 * average faster than O(haystack.size() * needle.size()) but not as fast
68 * as Boyer-Moore. On the upside, it does not do any upfront
69 * preprocessing and does not allocate memory.
73 class Comp = std::equal_to<typename Range<Iter>::value_type>>
75 qfind(const Range<Iter>& haystack, const Range<Iter>& needle, Comp eq = Comp());
78 * Finds the first occurrence of needle in haystack. The result is the
79 * offset reported to the beginning of haystack, or string::npos if
80 * needle wasn't found.
84 const Range<Iter>& haystack,
85 const typename Range<Iter>::value_type& needle);
88 * Finds the last occurrence of needle in haystack. The result is the
89 * offset reported to the beginning of haystack, or string::npos if
90 * needle wasn't found.
94 const Range<Iter>& haystack,
95 const typename Range<Iter>::value_type& needle);
98 * Finds the first occurrence of any element of needle in
99 * haystack. The algorithm is O(haystack.size() * needle.size()).
101 template <class Iter>
102 inline size_t qfind_first_of(
103 const Range<Iter>& haystack,
104 const Range<Iter>& needle);
107 * Small internal helper - returns the value just before an iterator.
112 * For random-access iterators, the value before is simply i[-1].
114 template <class Iter>
115 typename std::enable_if<
117 typename std::iterator_traits<Iter>::iterator_category,
118 std::random_access_iterator_tag>::value,
119 typename std::iterator_traits<Iter>::reference>::type
120 value_before(Iter i) {
125 * For all other iterators, we need to use the decrement operator.
127 template <class Iter>
128 typename std::enable_if<
130 typename std::iterator_traits<Iter>::iterator_category,
131 std::random_access_iterator_tag>::value,
132 typename std::iterator_traits<Iter>::reference>::type
133 value_before(Iter i) {
138 * Use IsCharPointer<T>::type to enable const char* or char*.
139 * Use IsCharPointer<T>::const_type to enable only const char*.
142 struct IsCharPointer {};
145 struct IsCharPointer<char*> {
150 struct IsCharPointer<const char*> {
151 typedef int const_type;
155 } // namespace detail
158 * Range abstraction keeping a pair of iterators. We couldn't use
159 * boost's similar range abstraction because we need an API identical
160 * with the former StringPiece class, which is used by a lot of other
161 * code. This abstraction does fulfill the needs of boost's
162 * range-oriented algorithms though.
164 * (Keep memory lifetime in mind when using this class, since it
165 * doesn't manage the data it refers to - just like an iterator
168 template <class Iter>
169 class Range : private boost::totally_ordered<Range<Iter>> {
171 typedef std::size_t size_type;
172 typedef Iter iterator;
173 typedef Iter const_iterator;
174 typedef typename std::remove_reference<
175 typename std::iterator_traits<Iter>::reference>::type value_type;
176 using difference_type = typename std::iterator_traits<Iter>::difference_type;
177 typedef typename std::iterator_traits<Iter>::reference reference;
180 * For MutableStringPiece and MutableByteRange we define StringPiece
181 * and ByteRange as const_range_type (for everything else its just
182 * identity). We do that to enable operations such as find with
183 * args which are const.
185 typedef typename std::conditional<
186 std::is_same<Iter, char*>::value ||
187 std::is_same<Iter, unsigned char*>::value,
188 Range<const value_type*>,
189 Range<Iter>>::type const_range_type;
191 typedef std::char_traits<typename std::remove_const<value_type>::type>
194 static const size_type npos;
196 // Works for all iterators
197 constexpr Range() : b_(), e_() {}
199 constexpr Range(const Range&) = default;
200 constexpr Range(Range&&) = default;
203 // Works for all iterators
204 constexpr Range(Iter start, Iter end) : b_(start), e_(end) {}
206 // Works only for random-access iterators
207 constexpr Range(Iter start, size_t size) : b_(start), e_(start + size) {}
209 #if !__clang__ || __CLANG_PREREQ(3, 7) // Clang 3.6 crashes on this line
210 /* implicit */ Range(std::nullptr_t) = delete;
213 constexpr /* implicit */ Range(Iter str)
214 : b_(str), e_(str + constexpr_strlen(str)) {
216 std::is_same<int, typename detail::IsCharPointer<Iter>::type>::value,
217 "This constructor is only available for character ranges");
220 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
221 /* implicit */ Range(const std::string& str)
222 : b_(str.data()), e_(b_ + str.size()) {}
224 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
225 Range(const std::string& str, std::string::size_type startFrom) {
226 if (UNLIKELY(startFrom > str.size())) {
227 std::__throw_out_of_range("index out of range");
229 b_ = str.data() + startFrom;
230 e_ = str.data() + str.size();
233 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
235 const std::string& str,
236 std::string::size_type startFrom,
237 std::string::size_type size) {
238 if (UNLIKELY(startFrom > str.size())) {
239 std::__throw_out_of_range("index out of range");
241 b_ = str.data() + startFrom;
242 if (str.size() - startFrom < size) {
243 e_ = str.data() + str.size();
249 Range(const Range& other, size_type first, size_type length = npos)
250 : Range(other.subpiece(first, length)) {}
254 class = typename std::enable_if<
255 std::is_same<Iter, typename Container::const_pointer>::value>::type,
257 Iter(std::declval<Container const&>().data()),
259 std::declval<Container const&>().data() +
260 std::declval<Container const&>().size()))>
261 /* implicit */ constexpr Range(Container const& container)
262 : b_(container.data()), e_(b_ + container.size()) {}
266 class = typename std::enable_if<
267 std::is_same<Iter, typename Container::const_pointer>::value>::type,
269 Iter(std::declval<Container const&>().data()),
271 std::declval<Container const&>().data() +
272 std::declval<Container const&>().size()))>
273 Range(Container const& container, typename Container::size_type startFrom) {
274 auto const cdata = container.data();
275 auto const csize = container.size();
276 if (UNLIKELY(startFrom > csize)) {
277 std::__throw_out_of_range("index out of range");
279 b_ = cdata + startFrom;
285 class = typename std::enable_if<
286 std::is_same<Iter, typename Container::const_pointer>::value>::type,
288 Iter(std::declval<Container const&>().data()),
290 std::declval<Container const&>().data() +
291 std::declval<Container const&>().size()))>
293 Container const& container,
294 typename Container::size_type startFrom,
295 typename Container::size_type size) {
296 auto const cdata = container.data();
297 auto const csize = container.size();
298 if (UNLIKELY(startFrom > csize)) {
299 std::__throw_out_of_range("index out of range");
301 b_ = cdata + startFrom;
302 if (csize - startFrom < size) {
309 // Allow implicit conversion from Range<const char*> (aka StringPiece) to
310 // Range<const unsigned char*> (aka ByteRange), as they're both frequently
311 // used to represent ranges of bytes. Allow explicit conversion in the other
315 typename std::enable_if<
316 (std::is_same<Iter, const unsigned char*>::value &&
317 (std::is_same<OtherIter, const char*>::value ||
318 std::is_same<OtherIter, char*>::value)),
320 /* implicit */ Range(const Range<OtherIter>& other)
321 : b_(reinterpret_cast<const unsigned char*>(other.begin())),
322 e_(reinterpret_cast<const unsigned char*>(other.end())) {}
326 typename std::enable_if<
327 (std::is_same<Iter, unsigned char*>::value &&
328 std::is_same<OtherIter, char*>::value),
330 /* implicit */ Range(const Range<OtherIter>& other)
331 : b_(reinterpret_cast<unsigned char*>(other.begin())),
332 e_(reinterpret_cast<unsigned char*>(other.end())) {}
336 typename std::enable_if<
337 (std::is_same<Iter, const char*>::value &&
338 (std::is_same<OtherIter, const unsigned char*>::value ||
339 std::is_same<OtherIter, unsigned char*>::value)),
341 explicit Range(const Range<OtherIter>& other)
342 : b_(reinterpret_cast<const char*>(other.begin())),
343 e_(reinterpret_cast<const char*>(other.end())) {}
347 typename std::enable_if<
348 (std::is_same<Iter, char*>::value &&
349 std::is_same<OtherIter, unsigned char*>::value),
351 explicit Range(const Range<OtherIter>& other)
352 : b_(reinterpret_cast<char*>(other.begin())),
353 e_(reinterpret_cast<char*>(other.end())) {}
355 // Allow implicit conversion from Range<From> to Range<To> if From is
356 // implicitly convertible to To.
359 typename std::enable_if<
360 (!std::is_same<Iter, OtherIter>::value &&
361 std::is_convertible<OtherIter, Iter>::value),
363 constexpr /* implicit */ Range(const Range<OtherIter>& other)
364 : b_(other.begin()), e_(other.end()) {}
366 // Allow explicit conversion from Range<From> to Range<To> if From is
367 // explicitly convertible to To.
370 typename std::enable_if<
371 (!std::is_same<Iter, OtherIter>::value &&
372 !std::is_convertible<OtherIter, Iter>::value &&
373 std::is_constructible<Iter, const OtherIter&>::value),
375 constexpr explicit Range(const Range<OtherIter>& other)
376 : b_(other.begin()), e_(other.end()) {}
379 * Allow explicit construction of Range() from a std::array of a
382 * For instance, this allows constructing StringPiece from a
383 * std::array<char, N> or a std::array<const char, N>
388 typename = typename std::enable_if<
389 std::is_convertible<const T*, Iter>::value>::type>
390 constexpr explicit Range(const std::array<T, N>& array)
391 : b_{array.empty() ? nullptr : &array.at(0)},
392 e_{array.empty() ? nullptr : &array.at(0) + N} {}
397 typename std::enable_if<std::is_convertible<T*, Iter>::value>::type>
398 constexpr explicit Range(std::array<T, N>& array)
399 : b_{array.empty() ? nullptr : &array.at(0)},
400 e_{array.empty() ? nullptr : &array.at(0) + N} {}
402 Range& operator=(const Range& rhs) & = default;
403 Range& operator=(Range&& rhs) & = default;
405 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
406 Range& operator=(std::string&& rhs) = delete;
413 void assign(Iter start, Iter end) {
418 void reset(Iter start, size_type size) {
423 // Works only for Range<const char*>
424 void reset(const std::string& str) {
425 reset(str.data(), str.size());
428 constexpr size_type size() const {
429 // It would be nice to assert(b_ <= e_) here. This can be achieved even
430 // in a C++11 compatible constexpr function:
431 // http://ericniebler.com/2014/09/27/assert-and-constexpr-in-cxx11/
432 // Unfortunately current gcc versions have a bug causing it to reject
433 // this check in a constexpr function:
434 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=71448
435 return size_type(e_ - b_);
437 constexpr size_type walk_size() const {
438 return size_type(std::distance(b_, e_));
440 constexpr bool empty() const {
443 constexpr Iter data() const {
446 constexpr Iter start() const {
449 constexpr Iter begin() const {
452 constexpr Iter end() const {
455 constexpr Iter cbegin() const {
458 constexpr Iter cend() const {
461 value_type& front() {
467 return detail::value_before(e_);
469 const value_type& front() const {
473 const value_type& back() const {
475 return detail::value_before(e_);
478 template <typename Tgt>
480 -> decltype(Tgt(std::declval<Iter const&>(), std::declval<size_type>())) {
481 return Tgt(b_, size());
483 // Works only for Range<const char*> and Range<char*>
484 std::string str() const {
485 return to<std::string>();
487 std::string toString() const {
488 return to<std::string>();
491 const_range_type castToConst() const {
492 return const_range_type(*this);
495 // Works only for Range<const char*> and Range<char*>
496 int compare(const const_range_type& o) const {
497 const size_type tsize = this->size();
498 const size_type osize = o.size();
499 const size_type msize = std::min(tsize, osize);
500 int r = traits_type::compare(data(), o.data(), msize);
501 if (r == 0 && tsize != osize) {
502 // We check the signed bit of the subtraction and bit shift it
503 // to produce either 0 or 2. The subtraction yields the
504 // comparison values of either -1 or 1.
505 r = (static_cast<int>((osize - tsize) >> (CHAR_BIT * sizeof(size_t) - 1))
512 value_type& operator[](size_t i) {
513 DCHECK_GT(size(), i);
517 const value_type& operator[](size_t i) const {
518 DCHECK_GT(size(), i);
522 value_type& at(size_t i) {
524 std::__throw_out_of_range("index out of range");
529 const value_type& at(size_t i) const {
531 std::__throw_out_of_range("index out of range");
536 // Do NOT use this function, which was left behind for backwards
537 // compatibility. Use SpookyHashV2 instead -- it is faster, and produces
538 // a 64-bit hash, which means dramatically fewer collisions in large maps.
539 // (The above advice does not apply if you are targeting a 32-bit system.)
541 // Works only for Range<const char*> and Range<char*>
544 // ** WANT TO GET RID OF THIS LINT? **
546 // A) Use a better hash function (*cough*folly::Hash*cough*), but
547 // only if you don't serialize data in a format that depends on
548 // this formula (ie the writer and reader assume this exact hash
549 // function is used).
551 // B) If you have to use this exact function then make your own hasher
552 // object and copy the body over (see thrift example: D3972362).
553 // https://github.com/facebook/fbthrift/commit/f8ed502e24ab4a32a9d5f266580
554 FOLLY_DEPRECATED("Replace with folly::Hash if the hash is not serialized")
555 uint32_t hash() const {
556 // Taken from fbi/nstring.h:
557 // Quick and dirty bernstein hash...fine for short ascii strings
558 uint32_t hash = 5381;
559 for (size_t ix = 0; ix < size(); ix++) {
560 hash = ((hash << 5) + hash) + b_[ix];
565 void advance(size_type n) {
566 if (UNLIKELY(n > size())) {
567 std::__throw_out_of_range("index out of range");
572 void subtract(size_type n) {
573 if (UNLIKELY(n > size())) {
574 std::__throw_out_of_range("index out of range");
579 Range subpiece(size_type first, size_type length = npos) const {
580 if (UNLIKELY(first > size())) {
581 std::__throw_out_of_range("index out of range");
584 return Range(b_ + first, std::min(length, size() - first));
587 // unchecked versions
588 void uncheckedAdvance(size_type n) {
589 DCHECK_LE(n, size());
593 void uncheckedSubtract(size_type n) {
594 DCHECK_LE(n, size());
598 Range uncheckedSubpiece(size_type first, size_type length = npos) const {
599 DCHECK_LE(first, size());
600 return Range(b_ + first, std::min(length, size() - first));
613 // string work-alike functions
614 size_type find(const_range_type str) const {
615 return qfind(castToConst(), str);
618 size_type find(const_range_type str, size_t pos) const {
620 return std::string::npos;
622 size_t ret = qfind(castToConst().subpiece(pos), str);
623 return ret == npos ? ret : ret + pos;
626 size_type find(Iter s, size_t pos, size_t n) const {
628 return std::string::npos;
630 auto forFinding = castToConst();
632 pos ? forFinding.subpiece(pos) : forFinding, const_range_type(s, n));
633 return ret == npos ? ret : ret + pos;
636 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
637 size_type find(const Iter s) const {
638 return qfind(castToConst(), const_range_type(s));
641 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
642 size_type find(const Iter s, size_t pos) const {
644 return std::string::npos;
646 size_type ret = qfind(castToConst().subpiece(pos), const_range_type(s));
647 return ret == npos ? ret : ret + pos;
650 size_type find(value_type c) const {
651 return qfind(castToConst(), c);
654 size_type rfind(value_type c) const {
655 return folly::rfind(castToConst(), c);
658 size_type find(value_type c, size_t pos) const {
660 return std::string::npos;
662 size_type ret = qfind(castToConst().subpiece(pos), c);
663 return ret == npos ? ret : ret + pos;
666 size_type find_first_of(const_range_type needles) const {
667 return qfind_first_of(castToConst(), needles);
670 size_type find_first_of(const_range_type needles, size_t pos) const {
672 return std::string::npos;
674 size_type ret = qfind_first_of(castToConst().subpiece(pos), needles);
675 return ret == npos ? ret : ret + pos;
678 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
679 size_type find_first_of(Iter needles) const {
680 return find_first_of(const_range_type(needles));
683 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
684 size_type find_first_of(Iter needles, size_t pos) const {
685 return find_first_of(const_range_type(needles), pos);
688 size_type find_first_of(Iter needles, size_t pos, size_t n) const {
689 return find_first_of(const_range_type(needles, n), pos);
692 size_type find_first_of(value_type c) const {
696 size_type find_first_of(value_type c, size_t pos) const {
701 * Determine whether the range contains the given subrange or item.
703 * Note: Call find() directly if the index is needed.
705 bool contains(const const_range_type& other) const {
706 return find(other) != std::string::npos;
709 bool contains(const value_type& other) const {
710 return find(other) != std::string::npos;
713 void swap(Range& rhs) {
714 std::swap(b_, rhs.b_);
715 std::swap(e_, rhs.e_);
719 * Does this Range start with another range?
721 bool startsWith(const const_range_type& other) const {
722 return size() >= other.size() &&
723 castToConst().subpiece(0, other.size()) == other;
725 bool startsWith(value_type c) const {
726 return !empty() && front() == c;
729 template <class Comp>
730 bool startsWith(const const_range_type& other, Comp&& eq) const {
731 if (size() < other.size()) {
734 auto const trunc = subpiece(0, other.size());
736 trunc.begin(), trunc.end(), other.begin(), std::forward<Comp>(eq));
740 * Does this Range end with another range?
742 bool endsWith(const const_range_type& other) const {
743 return size() >= other.size() &&
744 castToConst().subpiece(size() - other.size()) == other;
746 bool endsWith(value_type c) const {
747 return !empty() && back() == c;
750 template <class Comp>
751 bool endsWith(const const_range_type& other, Comp&& eq) const {
752 if (size() < other.size()) {
755 auto const trunc = subpiece(size() - other.size());
757 trunc.begin(), trunc.end(), other.begin(), std::forward<Comp>(eq));
760 template <class Comp>
761 bool equals(const const_range_type& other, Comp&& eq) const {
762 return size() == other.size() &&
763 std::equal(begin(), end(), other.begin(), std::forward<Comp>(eq));
767 * Remove the items in [b, e), as long as this subrange is at the beginning
768 * or end of the Range.
770 * Required for boost::algorithm::trim()
772 void erase(Iter b, Iter e) {
775 } else if (e == e_) {
778 std::__throw_out_of_range("index out of range");
783 * Remove the given prefix and return true if the range starts with the given
784 * prefix; return false otherwise.
786 bool removePrefix(const const_range_type& prefix) {
787 return startsWith(prefix) && (b_ += prefix.size(), true);
789 bool removePrefix(value_type prefix) {
790 return startsWith(prefix) && (++b_, true);
794 * Remove the given suffix and return true if the range ends with the given
795 * suffix; return false otherwise.
797 bool removeSuffix(const const_range_type& suffix) {
798 return endsWith(suffix) && (e_ -= suffix.size(), true);
800 bool removeSuffix(value_type suffix) {
801 return endsWith(suffix) && (--e_, true);
805 * Replaces the content of the range, starting at position 'pos', with
806 * contents of 'replacement'. Entire 'replacement' must fit into the
807 * range. Returns false if 'replacements' does not fit. Example use:
809 * char in[] = "buffer";
810 * auto msp = MutablesStringPiece(input);
811 * EXPECT_TRUE(msp.replaceAt(2, "tt"));
812 * EXPECT_EQ(msp, "butter");
814 * // not enough space
815 * EXPECT_FALSE(msp.replace(msp.size() - 1, "rr"));
816 * EXPECT_EQ(msp, "butter"); // unchanged
818 bool replaceAt(size_t pos, const_range_type replacement) {
819 if (size() < pos + replacement.size()) {
823 std::copy(replacement.begin(), replacement.end(), begin() + pos);
829 * Replaces all occurences of 'source' with 'dest'. Returns number
830 * of replacements made. Source and dest have to have the same
831 * length. Throws if the lengths are different. If 'source' is a
832 * pattern that is overlapping with itself, we perform sequential
833 * replacement: "aaaaaaa".replaceAll("aa", "ba") --> "bababaa"
837 * char in[] = "buffer";
838 * auto msp = MutablesStringPiece(input);
839 * EXPECT_EQ(msp.replaceAll("ff","tt"), 1);
840 * EXPECT_EQ(msp, "butter");
842 size_t replaceAll(const_range_type source, const_range_type dest) {
843 if (source.size() != dest.size()) {
844 throw std::invalid_argument(
845 "replacement must have the same size as source");
853 size_t num_replaced = 0;
854 size_type found = std::string::npos;
855 while ((found = find(source, pos)) != std::string::npos) {
856 replaceAt(found, dest);
857 pos += source.size();
865 * Splits this `Range` `[b, e)` in the position `i` dictated by the next
866 * occurence of `delimiter`.
868 * Returns a new `Range` `[b, i)` and adjusts this range to start right after
869 * the delimiter's position. This range will be empty if the delimiter is not
870 * found. If called on an empty `Range`, both this and the returned `Range`
875 * folly::StringPiece s("sample string for split_next");
876 * auto p = s.split_step(' ');
878 * // prints "string for split_next"
886 * void tokenize(StringPiece s, char delimiter) {
887 * while (!s.empty()) {
888 * cout << s.split_step(delimiter);
892 * @author: Marcelo Juchem <marcelo@fb.com>
894 Range split_step(value_type delimiter) {
895 auto i = std::find(b_, e_, delimiter);
898 b_ = i == e_ ? e_ : std::next(i);
903 Range split_step(Range delimiter) {
904 auto i = find(delimiter);
905 Range result(b_, i == std::string::npos ? size() : i);
907 b_ = result.end() == e_
911 typename std::iterator_traits<Iter>::difference_type(
918 * Convenience method that calls `split_step()` and passes the result to a
919 * functor, returning whatever the functor does. Any additional arguments
920 * `args` passed to this function are perfectly forwarded to the functor.
922 * Say you have a functor with this signature:
924 * Foo fn(Range r) { }
926 * `split_step()`'s return type will be `Foo`. It works just like:
928 * auto result = fn(myRange.split_step(' '));
930 * A functor returning `void` is also supported.
934 * void do_some_parsing(folly::StringPiece s) {
935 * auto version = s.split_step(' ', [&](folly::StringPiece x) {
937 * throw std::invalid_argument("empty string");
939 * return std::strtoull(x.begin(), x.end(), 16);
946 * void parse(folly::StringPiece s) {
947 * s.split_step(' ', parse_field, bar, 10);
948 * s.split_step('\t', parse_field, baz, 20);
950 * auto const kludge = [](folly::StringPiece x, int &out, int def) {
954 * parse_field(x, out, def);
958 * s.split_step('\t', kludge, gaz);
959 * s.split_step(' ', kludge, foo);
968 * static parse_field(folly::StringPiece s, int &out, int def) {
970 * out = folly::to<int>(s);
971 * } catch (std::exception const &) {
977 * @author: Marcelo Juchem <marcelo@fb.com>
979 template <typename TProcess, typename... Args>
980 auto split_step(value_type delimiter, TProcess&& process, Args&&... args)
981 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...)) {
982 return process(split_step(delimiter), std::forward<Args>(args)...);
985 template <typename TProcess, typename... Args>
986 auto split_step(Range delimiter, TProcess&& process, Args&&... args)
987 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...)) {
988 return process(split_step(delimiter), std::forward<Args>(args)...);
995 template <class Iter>
996 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
998 template <class Iter>
999 void swap(Range<Iter>& lhs, Range<Iter>& rhs) {
1004 * Create a range from two iterators, with type deduction.
1006 template <class Iter>
1007 constexpr Range<Iter> range(Iter first, Iter last) {
1008 return Range<Iter>(first, last);
1012 * Creates a range to reference the contents of a contiguous-storage container.
1014 // Use pointers for types with '.data()' member
1017 class T = typename std::remove_pointer<
1018 decltype(std::declval<Collection>().data())>::type>
1019 constexpr Range<T*> range(Collection&& v) {
1020 return Range<T*>(v.data(), v.data() + v.size());
1023 template <class T, size_t n>
1024 constexpr Range<T*> range(T (&array)[n]) {
1025 return Range<T*>(array, array + n);
1028 template <class T, size_t n>
1029 constexpr Range<const T*> range(const std::array<T, n>& array) {
1030 return Range<const T*>{array};
1033 typedef Range<const char*> StringPiece;
1034 typedef Range<char*> MutableStringPiece;
1035 typedef Range<const unsigned char*> ByteRange;
1036 typedef Range<unsigned char*> MutableByteRange;
1039 std::basic_ostream<C>& operator<<(
1040 std::basic_ostream<C>& os,
1041 Range<C const*> piece) {
1042 using StreamSize = decltype(os.width());
1043 os.write(piece.start(), static_cast<StreamSize>(piece.size()));
1048 std::basic_ostream<C>& operator<<(std::basic_ostream<C>& os, Range<C*> piece) {
1049 using StreamSize = decltype(os.width());
1050 os.write(piece.start(), static_cast<StreamSize>(piece.size()));
1055 * Templated comparison operators
1058 template <class Iter>
1059 inline bool operator==(const Range<Iter>& lhs, const Range<Iter>& rhs) {
1060 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
1063 template <class Iter>
1064 inline bool operator<(const Range<Iter>& lhs, const Range<Iter>& rhs) {
1065 return lhs.compare(rhs) < 0;
1069 * Specializations of comparison operators for StringPiece
1074 template <class A, class B>
1075 struct ComparableAsStringPiece {
1077 value = (std::is_convertible<A, StringPiece>::value &&
1078 std::is_same<B, StringPiece>::value) ||
1079 (std::is_convertible<B, StringPiece>::value &&
1080 std::is_same<A, StringPiece>::value)
1084 } // namespace detail
1087 * operator== through conversion for Range<const char*>
1089 template <class T, class U>
1090 _t<std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>>
1091 operator==(const T& lhs, const U& rhs) {
1092 return StringPiece(lhs) == StringPiece(rhs);
1096 * operator< through conversion for Range<const char*>
1098 template <class T, class U>
1099 _t<std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>>
1100 operator<(const T& lhs, const U& rhs) {
1101 return StringPiece(lhs) < StringPiece(rhs);
1105 * operator> through conversion for Range<const char*>
1107 template <class T, class U>
1108 _t<std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>>
1109 operator>(const T& lhs, const U& rhs) {
1110 return StringPiece(lhs) > StringPiece(rhs);
1114 * operator< through conversion for Range<const char*>
1116 template <class T, class U>
1117 _t<std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>>
1118 operator<=(const T& lhs, const U& rhs) {
1119 return StringPiece(lhs) <= StringPiece(rhs);
1123 * operator> through conversion for Range<const char*>
1125 template <class T, class U>
1126 _t<std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>>
1127 operator>=(const T& lhs, const U& rhs) {
1128 return StringPiece(lhs) >= StringPiece(rhs);
1132 * Finds substrings faster than brute force by borrowing from Boyer-Moore
1134 template <class Iter, class Comp>
1135 size_t qfind(const Range<Iter>& haystack, const Range<Iter>& needle, Comp eq) {
1136 // Don't use std::search, use a Boyer-Moore-like trick by comparing
1137 // the last characters first
1138 auto const nsize = needle.size();
1139 if (haystack.size() < nsize) {
1140 return std::string::npos;
1145 auto const nsize_1 = nsize - 1;
1146 auto const lastNeedle = needle[nsize_1];
1148 // Boyer-Moore skip value for the last char in the needle. Zero is
1149 // not a valid value; skip will be computed the first time it's
1151 std::string::size_type skip = 0;
1153 auto i = haystack.begin();
1154 auto iEnd = haystack.end() - nsize_1;
1157 // Boyer-Moore: match the last element in the needle
1158 while (!eq(i[nsize_1], lastNeedle)) {
1161 return std::string::npos;
1164 // Here we know that the last char matches
1165 // Continue in pedestrian mode
1166 for (size_t j = 0;;) {
1168 if (!eq(i[j], needle[j])) {
1169 // Not found, we can skip
1170 // Compute the skip value lazily
1173 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
1180 // Check if done searching
1183 return size_t(i - haystack.begin());
1187 return std::string::npos;
1192 inline size_t qfind_first_byte_of(
1193 const StringPiece haystack,
1194 const StringPiece needles) {
1195 static auto const qfind_first_byte_of_fn = folly::CpuId().sse42()
1196 ? qfind_first_byte_of_sse42
1197 : qfind_first_byte_of_nosse;
1198 return qfind_first_byte_of_fn(haystack, needles);
1201 } // namespace detail
1203 template <class Iter, class Comp>
1204 size_t qfind_first_of(
1205 const Range<Iter>& haystack,
1206 const Range<Iter>& needles,
1208 auto ret = std::find_first_of(
1209 haystack.begin(), haystack.end(), needles.begin(), needles.end(), eq);
1210 return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
1213 struct AsciiCaseSensitive {
1214 bool operator()(char lhs, char rhs) const {
1220 * Check if two ascii characters are case insensitive equal.
1221 * The difference between the lower/upper case characters are the 6-th bit.
1222 * We also check they are alpha chars, in case of xor = 32.
1224 struct AsciiCaseInsensitive {
1225 bool operator()(char lhs, char rhs) const {
1234 return (k >= 'a' && k <= 'z');
1238 template <class Iter>
1240 const Range<Iter>& haystack,
1241 const typename Range<Iter>::value_type& needle) {
1242 auto pos = std::find(haystack.begin(), haystack.end(), needle);
1243 return pos == haystack.end() ? std::string::npos : pos - haystack.data();
1246 template <class Iter>
1248 const Range<Iter>& haystack,
1249 const typename Range<Iter>::value_type& needle) {
1250 for (auto i = haystack.size(); i-- > 0;) {
1251 if (haystack[i] == needle) {
1255 return std::string::npos;
1258 // specialization for StringPiece
1260 inline size_t qfind(const Range<const char*>& haystack, const 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 char*>(
1266 ::memchr(haystack.data(), needle, haystack.size()));
1267 return pos == nullptr ? std::string::npos : pos - haystack.data();
1271 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
1272 // memchr expects a not-null pointer, early return if the range is empty.
1273 if (haystack.empty()) {
1274 return std::string::npos;
1276 auto pos = static_cast<const char*>(
1277 ::memrchr(haystack.data(), needle, haystack.size()));
1278 return pos == nullptr ? std::string::npos : pos - haystack.data();
1281 // specialization for ByteRange
1283 inline size_t qfind(
1284 const Range<const unsigned char*>& haystack,
1285 const unsigned char& needle) {
1286 // memchr expects a not-null pointer, early return if the range is empty.
1287 if (haystack.empty()) {
1288 return std::string::npos;
1290 auto pos = static_cast<const unsigned char*>(
1291 ::memchr(haystack.data(), needle, haystack.size()));
1292 return pos == nullptr ? std::string::npos : pos - haystack.data();
1296 inline size_t rfind(
1297 const Range<const unsigned char*>& haystack,
1298 const unsigned char& needle) {
1299 // memchr expects a not-null pointer, early return if the range is empty.
1300 if (haystack.empty()) {
1301 return std::string::npos;
1303 auto pos = static_cast<const unsigned char*>(
1304 ::memrchr(haystack.data(), needle, haystack.size()));
1305 return pos == nullptr ? std::string::npos : pos - haystack.data();
1308 template <class Iter>
1309 size_t qfind_first_of(const Range<Iter>& haystack, const Range<Iter>& needles) {
1310 return qfind_first_of(haystack, needles, AsciiCaseSensitive());
1313 // specialization for StringPiece
1315 inline size_t qfind_first_of(
1316 const Range<const char*>& haystack,
1317 const Range<const char*>& needles) {
1318 return detail::qfind_first_byte_of(haystack, needles);
1321 // specialization for ByteRange
1323 inline size_t qfind_first_of(
1324 const Range<const unsigned char*>& haystack,
1325 const Range<const unsigned char*>& needles) {
1326 return detail::qfind_first_byte_of(
1327 StringPiece(haystack), StringPiece(needles));
1330 template <class Key, class Enable>
1336 typename std::enable_if<std::is_pod<T>::value, void>::type> {
1337 size_t operator()(folly::Range<T*> r) const {
1338 return hash::SpookyHashV2::Hash64(r.begin(), r.size() * sizeof(T), 0);
1343 * _sp is a user-defined literal suffix to make an appropriate Range
1344 * specialization from a literal string.
1346 * Modeled after C++17's `sv` suffix.
1348 inline namespace literals {
1349 inline namespace string_piece_literals {
1350 constexpr Range<char const*> operator"" _sp(
1352 size_t len) noexcept {
1353 return Range<char const*>(str, len);
1356 constexpr Range<char16_t const*> operator"" _sp(
1357 char16_t const* str,
1358 size_t len) noexcept {
1359 return Range<char16_t const*>(str, len);
1362 constexpr Range<char32_t const*> operator"" _sp(
1363 char32_t const* str,
1364 size_t len) noexcept {
1365 return Range<char32_t const*>(str, len);
1368 constexpr Range<wchar_t const*> operator"" _sp(
1370 size_t len) noexcept {
1371 return Range<wchar_t const*>(str, len);
1373 } // namespace string_piece_literals
1374 } // namespace literals
1376 } // namespace folly
1380 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);