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/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/Traits.h>
54 #include <folly/Likely.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")
64 template <class Iter> class Range;
67 * Finds the first occurrence of needle in haystack. The algorithm is on
68 * average faster than O(haystack.size() * needle.size()) but not as fast
69 * as Boyer-Moore. On the upside, it does not do any upfront
70 * preprocessing and does not allocate memory.
73 class Comp = std::equal_to<typename Range<Iter>::value_type>>
74 inline size_t qfind(const Range<Iter> & haystack,
75 const Range<Iter> & needle,
79 * Finds the first occurrence of needle in haystack. The result is the
80 * offset reported to the beginning of haystack, or string::npos if
81 * needle wasn't found.
84 size_t qfind(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.
93 size_t rfind(const Range<Iter> & haystack,
94 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(const Range<Iter> & haystack,
103 const Range<Iter> & needle);
106 * Small internal helper - returns the value just before an iterator.
111 * For random-access iterators, the value before is simply i[-1].
113 template <class Iter>
114 typename std::enable_if<
115 std::is_same<typename std::iterator_traits<Iter>::iterator_category,
116 std::random_access_iterator_tag>::value,
117 typename std::iterator_traits<Iter>::reference>::type
118 value_before(Iter i) {
123 * For all other iterators, we need to use the decrement operator.
125 template <class Iter>
126 typename std::enable_if<
127 !std::is_same<typename std::iterator_traits<Iter>::iterator_category,
128 std::random_access_iterator_tag>::value,
129 typename std::iterator_traits<Iter>::reference>::type
130 value_before(Iter i) {
135 * Use IsCharPointer<T>::type to enable const char* or char*.
136 * Use IsCharPointer<T>::const_type to enable only const char*.
138 template <class T> struct IsCharPointer {};
141 struct IsCharPointer<char*> {
146 struct IsCharPointer<const char*> {
147 typedef int const_type;
151 } // namespace detail
154 * Range abstraction keeping a pair of iterators. We couldn't use
155 * boost's similar range abstraction because we need an API identical
156 * with the former StringPiece class, which is used by a lot of other
157 * code. This abstraction does fulfill the needs of boost's
158 * range-oriented algorithms though.
160 * (Keep memory lifetime in mind when using this class, since it
161 * doesn't manage the data it refers to - just like an iterator
164 template <class Iter>
165 class Range : private boost::totally_ordered<Range<Iter> > {
167 typedef std::size_t size_type;
168 typedef Iter iterator;
169 typedef Iter const_iterator;
170 typedef typename std::remove_reference<
171 typename std::iterator_traits<Iter>::reference>::type
173 using difference_type = typename std::iterator_traits<Iter>::difference_type;
174 typedef typename std::iterator_traits<Iter>::reference reference;
177 * For MutableStringPiece and MutableByteRange we define StringPiece
178 * and ByteRange as const_range_type (for everything else its just
179 * identity). We do that to enable operations such as find with
180 * args which are const.
182 typedef typename std::conditional<
183 std::is_same<Iter, char*>::value
184 || std::is_same<Iter, unsigned char*>::value,
185 Range<const value_type*>,
186 Range<Iter>>::type const_range_type;
188 typedef std::char_traits<typename std::remove_const<value_type>::type>
191 static const size_type npos;
193 // Works for all iterators
194 constexpr Range() : b_(), e_() {
197 constexpr Range(const Range&) = default;
198 constexpr Range(Range&&) = default;
201 // Works for all iterators
202 constexpr Range(Iter start, Iter end) : b_(start), e_(end) {
205 // Works only for random-access iterators
206 constexpr Range(Iter start, size_t size)
207 : b_(start), e_(start + size) { }
209 /* implicit */ Range(std::nullptr_t) = delete;
211 template <class T = Iter, typename detail::IsCharPointer<T>::type = 0>
212 constexpr /* implicit */ Range(Iter str)
213 : b_(str), e_(str + constexpr_strlen(str)) {}
215 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
216 /* implicit */ Range(const std::string& str)
217 : b_(str.data()), e_(b_ + str.size()) {}
219 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
220 Range(const std::string& str, std::string::size_type startFrom) {
221 if (UNLIKELY(startFrom > str.size())) {
222 std::__throw_out_of_range("index out of range");
224 b_ = str.data() + startFrom;
225 e_ = str.data() + str.size();
228 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
229 Range(const std::string& str,
230 std::string::size_type startFrom,
231 std::string::size_type size) {
232 if (UNLIKELY(startFrom > str.size())) {
233 std::__throw_out_of_range("index out of range");
235 b_ = str.data() + startFrom;
236 if (str.size() - startFrom < size) {
237 e_ = str.data() + str.size();
243 Range(const Range& other,
245 size_type length = npos)
246 : Range(other.subpiece(first, length))
249 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
250 /* implicit */ Range(const fbstring& str)
251 : b_(str.data()), e_(b_ + str.size()) { }
253 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
254 Range(const fbstring& str, fbstring::size_type startFrom) {
255 if (UNLIKELY(startFrom > str.size())) {
256 std::__throw_out_of_range("index out of range");
258 b_ = str.data() + startFrom;
259 e_ = str.data() + str.size();
262 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
263 Range(const fbstring& str, fbstring::size_type startFrom,
264 fbstring::size_type size) {
265 if (UNLIKELY(startFrom > str.size())) {
266 std::__throw_out_of_range("index out of range");
268 b_ = str.data() + startFrom;
269 if (str.size() - startFrom < size) {
270 e_ = str.data() + str.size();
276 // Allow implicit conversion from Range<const char*> (aka StringPiece) to
277 // Range<const unsigned char*> (aka ByteRange), as they're both frequently
278 // used to represent ranges of bytes. Allow explicit conversion in the other
280 template <class OtherIter, typename std::enable_if<
281 (std::is_same<Iter, const unsigned char*>::value &&
282 (std::is_same<OtherIter, const char*>::value ||
283 std::is_same<OtherIter, char*>::value)), int>::type = 0>
284 /* implicit */ Range(const Range<OtherIter>& other)
285 : b_(reinterpret_cast<const unsigned char*>(other.begin())),
286 e_(reinterpret_cast<const unsigned char*>(other.end())) {
289 template <class OtherIter, typename std::enable_if<
290 (std::is_same<Iter, unsigned char*>::value &&
291 std::is_same<OtherIter, char*>::value), int>::type = 0>
292 /* implicit */ Range(const Range<OtherIter>& other)
293 : b_(reinterpret_cast<unsigned char*>(other.begin())),
294 e_(reinterpret_cast<unsigned char*>(other.end())) {
297 template <class OtherIter, typename std::enable_if<
298 (std::is_same<Iter, const char*>::value &&
299 (std::is_same<OtherIter, const unsigned char*>::value ||
300 std::is_same<OtherIter, unsigned char*>::value)), int>::type = 0>
301 explicit Range(const Range<OtherIter>& other)
302 : b_(reinterpret_cast<const char*>(other.begin())),
303 e_(reinterpret_cast<const char*>(other.end())) {
306 template <class OtherIter, typename std::enable_if<
307 (std::is_same<Iter, char*>::value &&
308 std::is_same<OtherIter, unsigned char*>::value), int>::type = 0>
309 explicit Range(const Range<OtherIter>& other)
310 : b_(reinterpret_cast<char*>(other.begin())),
311 e_(reinterpret_cast<char*>(other.end())) {
314 // Allow implicit conversion from Range<From> to Range<To> if From is
315 // implicitly convertible to To.
316 template <class OtherIter, typename std::enable_if<
317 (!std::is_same<Iter, OtherIter>::value &&
318 std::is_convertible<OtherIter, Iter>::value), int>::type = 0>
319 constexpr /* implicit */ Range(const Range<OtherIter>& other)
324 // Allow explicit conversion from Range<From> to Range<To> if From is
325 // explicitly convertible to To.
326 template <class OtherIter, typename std::enable_if<
327 (!std::is_same<Iter, OtherIter>::value &&
328 !std::is_convertible<OtherIter, Iter>::value &&
329 std::is_constructible<Iter, const OtherIter&>::value), int>::type = 0>
330 constexpr explicit Range(const Range<OtherIter>& other)
336 * Allow explicit construction of Range() from a std::array of a
339 * For instance, this allows constructing StringPiece from a
340 * std::array<char, N> or a std::array<const char, N>
345 typename = typename std::enable_if<
346 std::is_convertible<const T*, Iter>::value>::type>
347 constexpr explicit Range(const std::array<T, N>& array)
348 : b_{array.empty() ? nullptr : &array.at(0)},
349 e_{array.empty() ? nullptr : &array.at(0) + N} {}
354 typename std::enable_if<std::is_convertible<T*, Iter>::value>::type>
355 constexpr explicit Range(std::array<T, N>& array)
356 : b_{array.empty() ? nullptr : &array.at(0)},
357 e_{array.empty() ? nullptr : &array.at(0) + N} {}
359 Range& operator=(const Range& rhs) & = default;
360 Range& operator=(Range&& rhs) & = default;
362 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
363 Range& operator=(std::string&& rhs) = delete;
370 void assign(Iter start, Iter end) {
375 void reset(Iter start, size_type size) {
380 // Works only for Range<const char*>
381 void reset(const std::string& str) {
382 reset(str.data(), str.size());
385 constexpr size_type size() const {
386 // It would be nice to assert(b_ <= e_) here. This can be achieved even
387 // in a C++11 compatible constexpr function:
388 // http://ericniebler.com/2014/09/27/assert-and-constexpr-in-cxx11/
389 // Unfortunately current gcc versions have a bug causing it to reject
390 // this check in a constexpr function:
391 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=71448
392 return size_type(e_ - b_);
394 constexpr size_type walk_size() const {
395 return size_type(std::distance(b_, e_));
397 constexpr bool empty() const {
400 constexpr Iter data() const {
403 constexpr Iter start() const {
406 constexpr Iter begin() const {
409 constexpr Iter end() const {
412 constexpr Iter cbegin() const {
415 constexpr Iter cend() const {
418 value_type& front() {
424 return detail::value_before(e_);
426 const value_type& front() const {
430 const value_type& back() const {
432 return detail::value_before(e_);
434 // Works only for Range<const char*> and Range<char*>
435 std::string str() const { return std::string(b_, size()); }
436 std::string toString() const { return str(); }
437 // Works only for Range<const char*> and Range<char*>
438 fbstring fbstr() const { return fbstring(b_, size()); }
439 fbstring toFbstring() const { return fbstr(); }
441 const_range_type castToConst() const {
442 return const_range_type(*this);
445 // Works only for Range<const char*> and Range<char*>
446 int compare(const const_range_type& o) const {
447 const size_type tsize = this->size();
448 const size_type osize = o.size();
449 const size_type msize = std::min(tsize, osize);
450 int r = traits_type::compare(data(), o.data(), msize);
451 if (r == 0 && tsize != osize) {
452 // We check the signed bit of the subtraction and bit shift it
453 // to produce either 0 or 2. The subtraction yields the
454 // comparison values of either -1 or 1.
455 r = (static_cast<int>(
456 (osize - tsize) >> (CHAR_BIT * sizeof(size_t) - 1)) << 1) - 1;
461 value_type& operator[](size_t i) {
462 DCHECK_GT(size(), i);
466 const value_type& operator[](size_t i) const {
467 DCHECK_GT(size(), i);
471 value_type& at(size_t i) {
472 if (i >= size()) std::__throw_out_of_range("index out of range");
476 const value_type& at(size_t i) const {
477 if (i >= size()) std::__throw_out_of_range("index out of range");
481 // Do NOT use this function, which was left behind for backwards
482 // compatibility. Use SpookyHashV2 instead -- it is faster, and produces
483 // a 64-bit hash, which means dramatically fewer collisions in large maps.
484 // (The above advice does not apply if you are targeting a 32-bit system.)
486 // Works only for Range<const char*> and Range<char*>
489 // ** WANT TO GET RID OF THIS LINT? **
491 // A) Use a better hash function (*cough*folly::Hash*cough*), but
492 // only if you don't serialize data in a format that depends on
493 // this formula (ie the writer and reader assume this exact hash
494 // function is used).
496 // B) If you have to use this exact function then make your own hasher
497 // object and copy the body over (see thrift example: D3972362).
498 // https://github.com/facebook/fbthrift/commit/f8ed502e24ab4a32a9d5f266580
499 FOLLY_DEPRECATED("Replace with folly::Hash if the hash is not serialized")
500 uint32_t hash() const {
501 // Taken from fbi/nstring.h:
502 // Quick and dirty bernstein hash...fine for short ascii strings
503 uint32_t hash = 5381;
504 for (size_t ix = 0; ix < size(); ix++) {
505 hash = ((hash << 5) + hash) + b_[ix];
510 void advance(size_type n) {
511 if (UNLIKELY(n > size())) {
512 std::__throw_out_of_range("index out of range");
517 void subtract(size_type n) {
518 if (UNLIKELY(n > size())) {
519 std::__throw_out_of_range("index out of range");
524 Range subpiece(size_type first, size_type length = npos) const {
525 if (UNLIKELY(first > size())) {
526 std::__throw_out_of_range("index out of range");
529 return Range(b_ + first, std::min(length, size() - first));
532 // unchecked versions
533 void uncheckedAdvance(size_type n) {
534 DCHECK_LE(n, size());
538 void uncheckedSubtract(size_type n) {
539 DCHECK_LE(n, size());
543 Range uncheckedSubpiece(size_type first, size_type length = npos) const {
544 DCHECK_LE(first, size());
545 return Range(b_ + first, std::min(length, size() - first));
558 // string work-alike functions
559 size_type find(const_range_type str) const {
560 return qfind(castToConst(), str);
563 size_type find(const_range_type str, size_t pos) const {
564 if (pos > size()) return std::string::npos;
565 size_t ret = qfind(castToConst().subpiece(pos), str);
566 return ret == npos ? ret : ret + pos;
569 size_type find(Iter s, size_t pos, size_t n) const {
570 if (pos > size()) return std::string::npos;
571 auto forFinding = castToConst();
573 pos ? forFinding.subpiece(pos) : forFinding, const_range_type(s, n));
574 return ret == npos ? ret : ret + pos;
577 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
578 size_type find(const Iter s) const {
579 return qfind(castToConst(), const_range_type(s));
582 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
583 size_type find(const Iter s, size_t pos) const {
584 if (pos > size()) return std::string::npos;
585 size_type ret = qfind(castToConst().subpiece(pos), const_range_type(s));
586 return ret == npos ? ret : ret + pos;
589 size_type find(value_type c) const {
590 return qfind(castToConst(), c);
593 size_type rfind(value_type c) const {
594 return folly::rfind(castToConst(), c);
597 size_type find(value_type c, size_t pos) const {
598 if (pos > size()) return std::string::npos;
599 size_type ret = qfind(castToConst().subpiece(pos), c);
600 return ret == npos ? ret : ret + pos;
603 size_type find_first_of(const_range_type needles) const {
604 return qfind_first_of(castToConst(), needles);
607 size_type find_first_of(const_range_type needles, size_t pos) const {
608 if (pos > size()) return std::string::npos;
609 size_type ret = qfind_first_of(castToConst().subpiece(pos), needles);
610 return ret == npos ? ret : ret + pos;
613 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
614 size_type find_first_of(Iter needles) const {
615 return find_first_of(const_range_type(needles));
618 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
619 size_type find_first_of(Iter needles, size_t pos) const {
620 return find_first_of(const_range_type(needles), pos);
623 size_type find_first_of(Iter needles, size_t pos, size_t n) const {
624 return find_first_of(const_range_type(needles, n), pos);
627 size_type find_first_of(value_type c) const {
631 size_type find_first_of(value_type c, size_t pos) const {
636 * Determine whether the range contains the given subrange or item.
638 * Note: Call find() directly if the index is needed.
640 bool contains(const const_range_type& other) const {
641 return find(other) != std::string::npos;
644 bool contains(const value_type& other) const {
645 return find(other) != std::string::npos;
648 void swap(Range& rhs) {
649 std::swap(b_, rhs.b_);
650 std::swap(e_, rhs.e_);
654 * Does this Range start with another range?
656 bool startsWith(const const_range_type& other) const {
657 return size() >= other.size()
658 && castToConst().subpiece(0, other.size()) == other;
660 bool startsWith(value_type c) const {
661 return !empty() && front() == c;
664 template <class Comp>
665 bool startsWith(const const_range_type& other, Comp&& eq) const {
666 if (size() < other.size()) {
669 auto const trunc = subpiece(0, other.size());
671 trunc.begin(), trunc.end(), other.begin(), std::forward<Comp>(eq));
675 * Does this Range end with another range?
677 bool endsWith(const const_range_type& other) const {
678 return size() >= other.size()
679 && castToConst().subpiece(size() - other.size()) == other;
681 bool endsWith(value_type c) const {
682 return !empty() && back() == c;
685 template <class Comp>
686 bool endsWith(const const_range_type& other, Comp&& eq) const {
687 if (size() < other.size()) {
690 auto const trunc = subpiece(size() - other.size());
692 trunc.begin(), trunc.end(), other.begin(), std::forward<Comp>(eq));
696 * Remove the items in [b, e), as long as this subrange is at the beginning
697 * or end of the Range.
699 * Required for boost::algorithm::trim()
701 void erase(Iter b, Iter e) {
704 } else if (e == e_) {
707 std::__throw_out_of_range("index out of range");
712 * Remove the given prefix and return true if the range starts with the given
713 * prefix; return false otherwise.
715 bool removePrefix(const const_range_type& prefix) {
716 return startsWith(prefix) && (b_ += prefix.size(), true);
718 bool removePrefix(value_type prefix) {
719 return startsWith(prefix) && (++b_, true);
723 * Remove the given suffix and return true if the range ends with the given
724 * suffix; return false otherwise.
726 bool removeSuffix(const const_range_type& suffix) {
727 return endsWith(suffix) && (e_ -= suffix.size(), true);
729 bool removeSuffix(value_type suffix) {
730 return endsWith(suffix) && (--e_, true);
734 * Replaces the content of the range, starting at position 'pos', with
735 * contents of 'replacement'. Entire 'replacement' must fit into the
736 * range. Returns false if 'replacements' does not fit. Example use:
738 * char in[] = "buffer";
739 * auto msp = MutablesStringPiece(input);
740 * EXPECT_TRUE(msp.replaceAt(2, "tt"));
741 * EXPECT_EQ(msp, "butter");
743 * // not enough space
744 * EXPECT_FALSE(msp.replace(msp.size() - 1, "rr"));
745 * EXPECT_EQ(msp, "butter"); // unchanged
747 bool replaceAt(size_t pos, const_range_type replacement) {
748 if (size() < pos + replacement.size()) {
752 std::copy(replacement.begin(), replacement.end(), begin() + pos);
758 * Replaces all occurences of 'source' with 'dest'. Returns number
759 * of replacements made. Source and dest have to have the same
760 * length. Throws if the lengths are different. If 'source' is a
761 * pattern that is overlapping with itself, we perform sequential
762 * replacement: "aaaaaaa".replaceAll("aa", "ba") --> "bababaa"
766 * char in[] = "buffer";
767 * auto msp = MutablesStringPiece(input);
768 * EXPECT_EQ(msp.replaceAll("ff","tt"), 1);
769 * EXPECT_EQ(msp, "butter");
771 size_t replaceAll(const_range_type source, const_range_type dest) {
772 if (source.size() != dest.size()) {
773 throw std::invalid_argument(
774 "replacement must have the same size as source");
782 size_t num_replaced = 0;
783 size_type found = std::string::npos;
784 while ((found = find(source, pos)) != std::string::npos) {
785 replaceAt(found, dest);
786 pos += source.size();
794 * Splits this `Range` `[b, e)` in the position `i` dictated by the next
795 * occurence of `delimiter`.
797 * Returns a new `Range` `[b, i)` and adjusts this range to start right after
798 * the delimiter's position. This range will be empty if the delimiter is not
799 * found. If called on an empty `Range`, both this and the returned `Range`
804 * folly::StringPiece s("sample string for split_next");
805 * auto p = s.split_step(' ');
807 * // prints "string for split_next"
815 * void tokenize(StringPiece s, char delimiter) {
816 * while (!s.empty()) {
817 * cout << s.split_step(delimiter);
821 * @author: Marcelo Juchem <marcelo@fb.com>
823 Range split_step(value_type delimiter) {
824 auto i = std::find(b_, e_, delimiter);
827 b_ = i == e_ ? e_ : std::next(i);
832 Range split_step(Range delimiter) {
833 auto i = find(delimiter);
834 Range result(b_, i == std::string::npos ? size() : i);
836 b_ = result.end() == e_
840 typename std::iterator_traits<Iter>::difference_type(
847 * Convenience method that calls `split_step()` and passes the result to a
848 * functor, returning whatever the functor does. Any additional arguments
849 * `args` passed to this function are perfectly forwarded to the functor.
851 * Say you have a functor with this signature:
853 * Foo fn(Range r) { }
855 * `split_step()`'s return type will be `Foo`. It works just like:
857 * auto result = fn(myRange.split_step(' '));
859 * A functor returning `void` is also supported.
863 * void do_some_parsing(folly::StringPiece s) {
864 * auto version = s.split_step(' ', [&](folly::StringPiece x) {
866 * throw std::invalid_argument("empty string");
868 * return std::strtoull(x.begin(), x.end(), 16);
875 * void parse(folly::StringPiece s) {
876 * s.split_step(' ', parse_field, bar, 10);
877 * s.split_step('\t', parse_field, baz, 20);
879 * auto const kludge = [](folly::StringPiece x, int &out, int def) {
883 * parse_field(x, out, def);
887 * s.split_step('\t', kludge, gaz);
888 * s.split_step(' ', kludge, foo);
897 * static parse_field(folly::StringPiece s, int &out, int def) {
899 * out = folly::to<int>(s);
900 * } catch (std::exception const &) {
906 * @author: Marcelo Juchem <marcelo@fb.com>
908 template <typename TProcess, typename... Args>
909 auto split_step(value_type delimiter, TProcess &&process, Args &&...args)
910 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
911 { return process(split_step(delimiter), std::forward<Args>(args)...); }
913 template <typename TProcess, typename... Args>
914 auto split_step(Range delimiter, TProcess &&process, Args &&...args)
915 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
916 { return process(split_step(delimiter), std::forward<Args>(args)...); }
922 template <class Iter>
923 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
925 template <class Iter>
926 void swap(Range<Iter>& lhs, Range<Iter>& rhs) {
931 * Create a range from two iterators, with type deduction.
933 template <class Iter>
934 constexpr Range<Iter> range(Iter first, Iter last) {
935 return Range<Iter>(first, last);
939 * Creates a range to reference the contents of a contiguous-storage container.
941 // Use pointers for types with '.data()' member
944 class T = typename std::remove_pointer<
945 decltype(std::declval<Collection>().data())>::type>
946 constexpr Range<T*> range(Collection&& v) {
947 return Range<T*>(v.data(), v.data() + v.size());
950 template <class T, size_t n>
951 constexpr Range<T*> range(T (&array)[n]) {
952 return Range<T*>(array, array + n);
955 template <class T, size_t n>
956 constexpr Range<const T*> range(const std::array<T, n>& array) {
957 return Range<const T*>{array};
960 typedef Range<const char*> StringPiece;
961 typedef Range<char*> MutableStringPiece;
962 typedef Range<const unsigned char*> ByteRange;
963 typedef Range<unsigned char*> MutableByteRange;
965 inline std::ostream& operator<<(std::ostream& os,
966 const StringPiece piece) {
967 os.write(piece.start(), std::streamsize(piece.size()));
971 inline std::ostream& operator<<(std::ostream& os,
972 const MutableStringPiece piece) {
973 os.write(piece.start(), std::streamsize(piece.size()));
978 * Templated comparison operators
981 template <class Iter>
982 inline bool operator==(const Range<Iter>& lhs, const Range<Iter>& rhs) {
983 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
986 template <class Iter>
987 inline bool operator<(const Range<Iter>& lhs, const Range<Iter>& rhs) {
988 return lhs.compare(rhs) < 0;
992 * Specializations of comparison operators for StringPiece
997 template <class A, class B>
998 struct ComparableAsStringPiece {
1001 (std::is_convertible<A, StringPiece>::value
1002 && std::is_same<B, StringPiece>::value)
1004 (std::is_convertible<B, StringPiece>::value
1005 && std::is_same<A, StringPiece>::value)
1009 } // namespace detail
1012 * operator== through conversion for Range<const char*>
1014 template <class T, class U>
1016 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
1017 operator==(const T& lhs, const U& rhs) {
1018 return StringPiece(lhs) == StringPiece(rhs);
1022 * operator< through conversion for Range<const char*>
1024 template <class T, class U>
1026 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
1027 operator<(const T& lhs, const U& rhs) {
1028 return StringPiece(lhs) < StringPiece(rhs);
1032 * operator> through conversion for Range<const char*>
1034 template <class T, class U>
1036 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
1037 operator>(const T& lhs, const U& rhs) {
1038 return StringPiece(lhs) > StringPiece(rhs);
1042 * operator< through conversion for Range<const char*>
1044 template <class T, class U>
1046 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
1047 operator<=(const T& lhs, const U& rhs) {
1048 return StringPiece(lhs) <= StringPiece(rhs);
1052 * operator> through conversion for Range<const char*>
1054 template <class T, class U>
1056 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
1057 operator>=(const T& lhs, const U& rhs) {
1058 return StringPiece(lhs) >= StringPiece(rhs);
1062 * Finds substrings faster than brute force by borrowing from Boyer-Moore
1064 template <class Iter, class Comp>
1065 size_t qfind(const Range<Iter>& haystack,
1066 const Range<Iter>& needle,
1068 // Don't use std::search, use a Boyer-Moore-like trick by comparing
1069 // the last characters first
1070 auto const nsize = needle.size();
1071 if (haystack.size() < nsize) {
1072 return std::string::npos;
1074 if (!nsize) return 0;
1075 auto const nsize_1 = nsize - 1;
1076 auto const lastNeedle = needle[nsize_1];
1078 // Boyer-Moore skip value for the last char in the needle. Zero is
1079 // not a valid value; skip will be computed the first time it's
1081 std::string::size_type skip = 0;
1083 auto i = haystack.begin();
1084 auto iEnd = haystack.end() - nsize_1;
1087 // Boyer-Moore: match the last element in the needle
1088 while (!eq(i[nsize_1], lastNeedle)) {
1091 return std::string::npos;
1094 // Here we know that the last char matches
1095 // Continue in pedestrian mode
1096 for (size_t j = 0; ; ) {
1098 if (!eq(i[j], needle[j])) {
1099 // Not found, we can skip
1100 // Compute the skip value lazily
1103 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
1110 // Check if done searching
1113 return size_t(i - haystack.begin());
1117 return std::string::npos;
1122 inline size_t qfind_first_byte_of(const StringPiece haystack,
1123 const StringPiece needles) {
1124 static auto const qfind_first_byte_of_fn =
1125 folly::CpuId().sse42() ? qfind_first_byte_of_sse42
1126 : qfind_first_byte_of_nosse;
1127 return qfind_first_byte_of_fn(haystack, needles);
1130 } // namespace detail
1132 template <class Iter, class Comp>
1133 size_t qfind_first_of(const Range<Iter> & haystack,
1134 const Range<Iter> & needles,
1136 auto ret = std::find_first_of(haystack.begin(), haystack.end(),
1137 needles.begin(), needles.end(),
1139 return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
1142 struct AsciiCaseSensitive {
1143 bool operator()(char lhs, char rhs) const {
1149 * Check if two ascii characters are case insensitive equal.
1150 * The difference between the lower/upper case characters are the 6-th bit.
1151 * We also check they are alpha chars, in case of xor = 32.
1153 struct AsciiCaseInsensitive {
1154 bool operator()(char lhs, char rhs) const {
1156 if (k == 0) return true;
1157 if (k != 32) return false;
1159 return (k >= 'a' && k <= 'z');
1163 template <class Iter>
1164 size_t qfind(const Range<Iter>& haystack,
1165 const typename Range<Iter>::value_type& needle) {
1166 auto pos = std::find(haystack.begin(), haystack.end(), needle);
1167 return pos == haystack.end() ? std::string::npos : pos - haystack.data();
1170 template <class Iter>
1171 size_t rfind(const Range<Iter>& haystack,
1172 const typename Range<Iter>::value_type& needle) {
1173 for (auto i = haystack.size(); i-- > 0; ) {
1174 if (haystack[i] == needle) {
1178 return std::string::npos;
1181 // specialization for StringPiece
1183 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
1184 // memchr expects a not-null pointer, early return if the range is empty.
1185 if (haystack.empty()) {
1186 return std::string::npos;
1188 auto pos = static_cast<const char*>(
1189 ::memchr(haystack.data(), needle, haystack.size()));
1190 return pos == nullptr ? std::string::npos : pos - haystack.data();
1194 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
1195 // memchr expects a not-null pointer, early return if the range is empty.
1196 if (haystack.empty()) {
1197 return std::string::npos;
1199 auto pos = static_cast<const char*>(
1200 ::memrchr(haystack.data(), needle, haystack.size()));
1201 return pos == nullptr ? std::string::npos : pos - haystack.data();
1204 // specialization for ByteRange
1206 inline size_t qfind(const Range<const unsigned char*>& haystack,
1207 const unsigned char& needle) {
1208 // memchr expects a not-null pointer, early return if the range is empty.
1209 if (haystack.empty()) {
1210 return std::string::npos;
1212 auto pos = static_cast<const unsigned char*>(
1213 ::memchr(haystack.data(), needle, haystack.size()));
1214 return pos == nullptr ? std::string::npos : pos - haystack.data();
1218 inline size_t rfind(const Range<const unsigned char*>& haystack,
1219 const unsigned char& needle) {
1220 // memchr expects a not-null pointer, early return if the range is empty.
1221 if (haystack.empty()) {
1222 return std::string::npos;
1224 auto pos = static_cast<const unsigned char*>(
1225 ::memrchr(haystack.data(), needle, haystack.size()));
1226 return pos == nullptr ? std::string::npos : pos - haystack.data();
1229 template <class Iter>
1230 size_t qfind_first_of(const Range<Iter>& haystack,
1231 const Range<Iter>& needles) {
1232 return qfind_first_of(haystack, needles, AsciiCaseSensitive());
1235 // specialization for StringPiece
1237 inline size_t qfind_first_of(const Range<const char*>& haystack,
1238 const Range<const char*>& needles) {
1239 return detail::qfind_first_byte_of(haystack, needles);
1242 // specialization for ByteRange
1244 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
1245 const Range<const unsigned char*>& needles) {
1246 return detail::qfind_first_byte_of(StringPiece(haystack),
1247 StringPiece(needles));
1250 template<class Key, class Enable>
1254 struct hasher<folly::Range<T*>,
1255 typename std::enable_if<std::is_pod<T>::value, void>::type> {
1256 size_t operator()(folly::Range<T*> r) const {
1257 return hash::SpookyHashV2::Hash64(r.begin(), r.size() * sizeof(T), 0);
1262 * Ubiquitous helper template for knowing what's a string
1264 template <class T> struct IsSomeString {
1265 enum { value = std::is_same<T, std::string>::value
1266 || std::is_same<T, fbstring>::value };
1269 } // !namespace folly
1273 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);