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/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 # if !__clang__ || __CLANG_PREREQ(3, 7) // Clang 3.6 crashes on this line
210 /* implicit */ Range(std::nullptr_t) = delete;
213 template <class T = Iter, typename detail::IsCharPointer<T>::type = 0>
214 constexpr /* implicit */ Range(Iter str)
215 : b_(str), e_(str + constexpr_strlen(str)) {}
217 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
218 /* implicit */ Range(const std::string& str)
219 : b_(str.data()), e_(b_ + str.size()) {}
221 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
222 Range(const std::string& str, std::string::size_type startFrom) {
223 if (UNLIKELY(startFrom > str.size())) {
224 std::__throw_out_of_range("index out of range");
226 b_ = str.data() + startFrom;
227 e_ = str.data() + str.size();
230 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
231 Range(const std::string& str,
232 std::string::size_type startFrom,
233 std::string::size_type size) {
234 if (UNLIKELY(startFrom > str.size())) {
235 std::__throw_out_of_range("index out of range");
237 b_ = str.data() + startFrom;
238 if (str.size() - startFrom < size) {
239 e_ = str.data() + str.size();
245 Range(const Range& other,
247 size_type length = npos)
248 : Range(other.subpiece(first, length))
251 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
252 /* implicit */ Range(const fbstring& str)
253 : b_(str.data()), e_(b_ + str.size()) { }
255 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
256 Range(const fbstring& str, fbstring::size_type startFrom) {
257 if (UNLIKELY(startFrom > str.size())) {
258 std::__throw_out_of_range("index out of range");
260 b_ = str.data() + startFrom;
261 e_ = str.data() + str.size();
264 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
265 Range(const fbstring& str, fbstring::size_type startFrom,
266 fbstring::size_type size) {
267 if (UNLIKELY(startFrom > str.size())) {
268 std::__throw_out_of_range("index out of range");
270 b_ = str.data() + startFrom;
271 if (str.size() - startFrom < size) {
272 e_ = str.data() + str.size();
278 // Allow implicit conversion from Range<const char*> (aka StringPiece) to
279 // Range<const unsigned char*> (aka ByteRange), as they're both frequently
280 // used to represent ranges of bytes. Allow explicit conversion in the other
282 template <class OtherIter, typename std::enable_if<
283 (std::is_same<Iter, const unsigned char*>::value &&
284 (std::is_same<OtherIter, const char*>::value ||
285 std::is_same<OtherIter, char*>::value)), int>::type = 0>
286 /* implicit */ Range(const Range<OtherIter>& other)
287 : b_(reinterpret_cast<const unsigned char*>(other.begin())),
288 e_(reinterpret_cast<const unsigned char*>(other.end())) {
291 template <class OtherIter, typename std::enable_if<
292 (std::is_same<Iter, unsigned char*>::value &&
293 std::is_same<OtherIter, char*>::value), int>::type = 0>
294 /* implicit */ Range(const Range<OtherIter>& other)
295 : b_(reinterpret_cast<unsigned char*>(other.begin())),
296 e_(reinterpret_cast<unsigned char*>(other.end())) {
299 template <class OtherIter, typename std::enable_if<
300 (std::is_same<Iter, const char*>::value &&
301 (std::is_same<OtherIter, const unsigned char*>::value ||
302 std::is_same<OtherIter, unsigned char*>::value)), int>::type = 0>
303 explicit Range(const Range<OtherIter>& other)
304 : b_(reinterpret_cast<const char*>(other.begin())),
305 e_(reinterpret_cast<const char*>(other.end())) {
308 template <class OtherIter, typename std::enable_if<
309 (std::is_same<Iter, char*>::value &&
310 std::is_same<OtherIter, unsigned char*>::value), int>::type = 0>
311 explicit Range(const Range<OtherIter>& other)
312 : b_(reinterpret_cast<char*>(other.begin())),
313 e_(reinterpret_cast<char*>(other.end())) {
316 // Allow implicit conversion from Range<From> to Range<To> if From is
317 // implicitly convertible to To.
318 template <class OtherIter, typename std::enable_if<
319 (!std::is_same<Iter, OtherIter>::value &&
320 std::is_convertible<OtherIter, Iter>::value), int>::type = 0>
321 constexpr /* implicit */ Range(const Range<OtherIter>& other)
326 // Allow explicit conversion from Range<From> to Range<To> if From is
327 // explicitly convertible to To.
328 template <class OtherIter, typename std::enable_if<
329 (!std::is_same<Iter, OtherIter>::value &&
330 !std::is_convertible<OtherIter, Iter>::value &&
331 std::is_constructible<Iter, const OtherIter&>::value), int>::type = 0>
332 constexpr explicit Range(const Range<OtherIter>& other)
338 * Allow explicit construction of Range() from a std::array of a
341 * For instance, this allows constructing StringPiece from a
342 * std::array<char, N> or a std::array<const char, N>
347 typename = typename std::enable_if<
348 std::is_convertible<const T*, Iter>::value>::type>
349 constexpr explicit Range(const std::array<T, N>& array)
350 : b_{array.empty() ? nullptr : &array.at(0)},
351 e_{array.empty() ? nullptr : &array.at(0) + N} {}
356 typename std::enable_if<std::is_convertible<T*, Iter>::value>::type>
357 constexpr explicit Range(std::array<T, N>& array)
358 : b_{array.empty() ? nullptr : &array.at(0)},
359 e_{array.empty() ? nullptr : &array.at(0) + N} {}
361 Range& operator=(const Range& rhs) & = default;
362 Range& operator=(Range&& rhs) & = default;
364 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
365 Range& operator=(std::string&& rhs) = delete;
372 void assign(Iter start, Iter end) {
377 void reset(Iter start, size_type size) {
382 // Works only for Range<const char*>
383 void reset(const std::string& str) {
384 reset(str.data(), str.size());
387 constexpr size_type size() const {
388 // It would be nice to assert(b_ <= e_) here. This can be achieved even
389 // in a C++11 compatible constexpr function:
390 // http://ericniebler.com/2014/09/27/assert-and-constexpr-in-cxx11/
391 // Unfortunately current gcc versions have a bug causing it to reject
392 // this check in a constexpr function:
393 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=71448
394 return size_type(e_ - b_);
396 constexpr size_type walk_size() const {
397 return size_type(std::distance(b_, e_));
399 constexpr bool empty() const {
402 constexpr Iter data() const {
405 constexpr Iter start() const {
408 constexpr Iter begin() const {
411 constexpr Iter end() const {
414 constexpr Iter cbegin() const {
417 constexpr Iter cend() const {
420 value_type& front() {
426 return detail::value_before(e_);
428 const value_type& front() const {
432 const value_type& back() const {
434 return detail::value_before(e_);
436 // Works only for Range<const char*> and Range<char*>
437 std::string str() const { return std::string(b_, size()); }
438 std::string toString() const { return str(); }
439 // Works only for Range<const char*> and Range<char*>
440 fbstring fbstr() const { return fbstring(b_, size()); }
441 fbstring toFbstring() const { return fbstr(); }
443 const_range_type castToConst() const {
444 return const_range_type(*this);
447 // Works only for Range<const char*> and Range<char*>
448 int compare(const const_range_type& o) const {
449 const size_type tsize = this->size();
450 const size_type osize = o.size();
451 const size_type msize = std::min(tsize, osize);
452 int r = traits_type::compare(data(), o.data(), msize);
453 if (r == 0 && tsize != osize) {
454 // We check the signed bit of the subtraction and bit shift it
455 // to produce either 0 or 2. The subtraction yields the
456 // comparison values of either -1 or 1.
457 r = (static_cast<int>(
458 (osize - tsize) >> (CHAR_BIT * sizeof(size_t) - 1)) << 1) - 1;
463 value_type& operator[](size_t i) {
464 DCHECK_GT(size(), i);
468 const value_type& operator[](size_t i) const {
469 DCHECK_GT(size(), i);
473 value_type& at(size_t i) {
474 if (i >= size()) std::__throw_out_of_range("index out of range");
478 const value_type& at(size_t i) const {
479 if (i >= size()) std::__throw_out_of_range("index out of range");
483 // Do NOT use this function, which was left behind for backwards
484 // compatibility. Use SpookyHashV2 instead -- it is faster, and produces
485 // a 64-bit hash, which means dramatically fewer collisions in large maps.
486 // (The above advice does not apply if you are targeting a 32-bit system.)
488 // Works only for Range<const char*> and Range<char*>
491 // ** WANT TO GET RID OF THIS LINT? **
493 // A) Use a better hash function (*cough*folly::Hash*cough*), but
494 // only if you don't serialize data in a format that depends on
495 // this formula (ie the writer and reader assume this exact hash
496 // function is used).
498 // B) If you have to use this exact function then make your own hasher
499 // object and copy the body over (see thrift example: D3972362).
500 // https://github.com/facebook/fbthrift/commit/f8ed502e24ab4a32a9d5f266580
501 FOLLY_DEPRECATED("Replace with folly::Hash if the hash is not serialized")
502 uint32_t hash() const {
503 // Taken from fbi/nstring.h:
504 // Quick and dirty bernstein hash...fine for short ascii strings
505 uint32_t hash = 5381;
506 for (size_t ix = 0; ix < size(); ix++) {
507 hash = ((hash << 5) + hash) + b_[ix];
512 void advance(size_type n) {
513 if (UNLIKELY(n > size())) {
514 std::__throw_out_of_range("index out of range");
519 void subtract(size_type n) {
520 if (UNLIKELY(n > size())) {
521 std::__throw_out_of_range("index out of range");
526 Range subpiece(size_type first, size_type length = npos) const {
527 if (UNLIKELY(first > size())) {
528 std::__throw_out_of_range("index out of range");
531 return Range(b_ + first, std::min(length, size() - first));
534 // unchecked versions
535 void uncheckedAdvance(size_type n) {
536 DCHECK_LE(n, size());
540 void uncheckedSubtract(size_type n) {
541 DCHECK_LE(n, size());
545 Range uncheckedSubpiece(size_type first, size_type length = npos) const {
546 DCHECK_LE(first, size());
547 return Range(b_ + first, std::min(length, size() - first));
560 // string work-alike functions
561 size_type find(const_range_type str) const {
562 return qfind(castToConst(), str);
565 size_type find(const_range_type str, size_t pos) const {
566 if (pos > size()) return std::string::npos;
567 size_t ret = qfind(castToConst().subpiece(pos), str);
568 return ret == npos ? ret : ret + pos;
571 size_type find(Iter s, size_t pos, size_t n) const {
572 if (pos > size()) return std::string::npos;
573 auto forFinding = castToConst();
575 pos ? forFinding.subpiece(pos) : forFinding, const_range_type(s, n));
576 return ret == npos ? ret : ret + pos;
579 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
580 size_type find(const Iter s) const {
581 return qfind(castToConst(), const_range_type(s));
584 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
585 size_type find(const Iter s, size_t pos) const {
586 if (pos > size()) return std::string::npos;
587 size_type ret = qfind(castToConst().subpiece(pos), const_range_type(s));
588 return ret == npos ? ret : ret + pos;
591 size_type find(value_type c) const {
592 return qfind(castToConst(), c);
595 size_type rfind(value_type c) const {
596 return folly::rfind(castToConst(), c);
599 size_type find(value_type c, size_t pos) const {
600 if (pos > size()) return std::string::npos;
601 size_type ret = qfind(castToConst().subpiece(pos), c);
602 return ret == npos ? ret : ret + pos;
605 size_type find_first_of(const_range_type needles) const {
606 return qfind_first_of(castToConst(), needles);
609 size_type find_first_of(const_range_type needles, size_t pos) const {
610 if (pos > size()) return std::string::npos;
611 size_type ret = qfind_first_of(castToConst().subpiece(pos), needles);
612 return ret == npos ? ret : ret + pos;
615 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
616 size_type find_first_of(Iter needles) const {
617 return find_first_of(const_range_type(needles));
620 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
621 size_type find_first_of(Iter needles, size_t pos) const {
622 return find_first_of(const_range_type(needles), pos);
625 size_type find_first_of(Iter needles, size_t pos, size_t n) const {
626 return find_first_of(const_range_type(needles, n), pos);
629 size_type find_first_of(value_type c) const {
633 size_type find_first_of(value_type c, size_t pos) const {
638 * Determine whether the range contains the given subrange or item.
640 * Note: Call find() directly if the index is needed.
642 bool contains(const const_range_type& other) const {
643 return find(other) != std::string::npos;
646 bool contains(const value_type& other) const {
647 return find(other) != std::string::npos;
650 void swap(Range& rhs) {
651 std::swap(b_, rhs.b_);
652 std::swap(e_, rhs.e_);
656 * Does this Range start with another range?
658 bool startsWith(const const_range_type& other) const {
659 return size() >= other.size()
660 && castToConst().subpiece(0, other.size()) == other;
662 bool startsWith(value_type c) const {
663 return !empty() && front() == c;
666 template <class Comp>
667 bool startsWith(const const_range_type& other, Comp&& eq) const {
668 if (size() < other.size()) {
671 auto const trunc = subpiece(0, other.size());
673 trunc.begin(), trunc.end(), other.begin(), std::forward<Comp>(eq));
677 * Does this Range end with another range?
679 bool endsWith(const const_range_type& other) const {
680 return size() >= other.size()
681 && castToConst().subpiece(size() - other.size()) == other;
683 bool endsWith(value_type c) const {
684 return !empty() && back() == c;
687 template <class Comp>
688 bool endsWith(const const_range_type& other, Comp&& eq) const {
689 if (size() < other.size()) {
692 auto const trunc = subpiece(size() - other.size());
694 trunc.begin(), trunc.end(), other.begin(), std::forward<Comp>(eq));
697 template <class Comp>
698 bool equals(const const_range_type& other, Comp&& eq) const {
699 return size() == other.size() &&
700 std::equal(begin(), end(), other.begin(), std::forward<Comp>(eq));
704 * Remove the items in [b, e), as long as this subrange is at the beginning
705 * or end of the Range.
707 * Required for boost::algorithm::trim()
709 void erase(Iter b, Iter e) {
712 } else if (e == e_) {
715 std::__throw_out_of_range("index out of range");
720 * Remove the given prefix and return true if the range starts with the given
721 * prefix; return false otherwise.
723 bool removePrefix(const const_range_type& prefix) {
724 return startsWith(prefix) && (b_ += prefix.size(), true);
726 bool removePrefix(value_type prefix) {
727 return startsWith(prefix) && (++b_, true);
731 * Remove the given suffix and return true if the range ends with the given
732 * suffix; return false otherwise.
734 bool removeSuffix(const const_range_type& suffix) {
735 return endsWith(suffix) && (e_ -= suffix.size(), true);
737 bool removeSuffix(value_type suffix) {
738 return endsWith(suffix) && (--e_, true);
742 * Replaces the content of the range, starting at position 'pos', with
743 * contents of 'replacement'. Entire 'replacement' must fit into the
744 * range. Returns false if 'replacements' does not fit. Example use:
746 * char in[] = "buffer";
747 * auto msp = MutablesStringPiece(input);
748 * EXPECT_TRUE(msp.replaceAt(2, "tt"));
749 * EXPECT_EQ(msp, "butter");
751 * // not enough space
752 * EXPECT_FALSE(msp.replace(msp.size() - 1, "rr"));
753 * EXPECT_EQ(msp, "butter"); // unchanged
755 bool replaceAt(size_t pos, const_range_type replacement) {
756 if (size() < pos + replacement.size()) {
760 std::copy(replacement.begin(), replacement.end(), begin() + pos);
766 * Replaces all occurences of 'source' with 'dest'. Returns number
767 * of replacements made. Source and dest have to have the same
768 * length. Throws if the lengths are different. If 'source' is a
769 * pattern that is overlapping with itself, we perform sequential
770 * replacement: "aaaaaaa".replaceAll("aa", "ba") --> "bababaa"
774 * char in[] = "buffer";
775 * auto msp = MutablesStringPiece(input);
776 * EXPECT_EQ(msp.replaceAll("ff","tt"), 1);
777 * EXPECT_EQ(msp, "butter");
779 size_t replaceAll(const_range_type source, const_range_type dest) {
780 if (source.size() != dest.size()) {
781 throw std::invalid_argument(
782 "replacement must have the same size as source");
790 size_t num_replaced = 0;
791 size_type found = std::string::npos;
792 while ((found = find(source, pos)) != std::string::npos) {
793 replaceAt(found, dest);
794 pos += source.size();
802 * Splits this `Range` `[b, e)` in the position `i` dictated by the next
803 * occurence of `delimiter`.
805 * Returns a new `Range` `[b, i)` and adjusts this range to start right after
806 * the delimiter's position. This range will be empty if the delimiter is not
807 * found. If called on an empty `Range`, both this and the returned `Range`
812 * folly::StringPiece s("sample string for split_next");
813 * auto p = s.split_step(' ');
815 * // prints "string for split_next"
823 * void tokenize(StringPiece s, char delimiter) {
824 * while (!s.empty()) {
825 * cout << s.split_step(delimiter);
829 * @author: Marcelo Juchem <marcelo@fb.com>
831 Range split_step(value_type delimiter) {
832 auto i = std::find(b_, e_, delimiter);
835 b_ = i == e_ ? e_ : std::next(i);
840 Range split_step(Range delimiter) {
841 auto i = find(delimiter);
842 Range result(b_, i == std::string::npos ? size() : i);
844 b_ = result.end() == e_
848 typename std::iterator_traits<Iter>::difference_type(
855 * Convenience method that calls `split_step()` and passes the result to a
856 * functor, returning whatever the functor does. Any additional arguments
857 * `args` passed to this function are perfectly forwarded to the functor.
859 * Say you have a functor with this signature:
861 * Foo fn(Range r) { }
863 * `split_step()`'s return type will be `Foo`. It works just like:
865 * auto result = fn(myRange.split_step(' '));
867 * A functor returning `void` is also supported.
871 * void do_some_parsing(folly::StringPiece s) {
872 * auto version = s.split_step(' ', [&](folly::StringPiece x) {
874 * throw std::invalid_argument("empty string");
876 * return std::strtoull(x.begin(), x.end(), 16);
883 * void parse(folly::StringPiece s) {
884 * s.split_step(' ', parse_field, bar, 10);
885 * s.split_step('\t', parse_field, baz, 20);
887 * auto const kludge = [](folly::StringPiece x, int &out, int def) {
891 * parse_field(x, out, def);
895 * s.split_step('\t', kludge, gaz);
896 * s.split_step(' ', kludge, foo);
905 * static parse_field(folly::StringPiece s, int &out, int def) {
907 * out = folly::to<int>(s);
908 * } catch (std::exception const &) {
914 * @author: Marcelo Juchem <marcelo@fb.com>
916 template <typename TProcess, typename... Args>
917 auto split_step(value_type delimiter, TProcess &&process, Args &&...args)
918 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
919 { return process(split_step(delimiter), std::forward<Args>(args)...); }
921 template <typename TProcess, typename... Args>
922 auto split_step(Range delimiter, TProcess &&process, Args &&...args)
923 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
924 { return process(split_step(delimiter), std::forward<Args>(args)...); }
930 template <class Iter>
931 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
933 template <class Iter>
934 void swap(Range<Iter>& lhs, Range<Iter>& rhs) {
939 * Create a range from two iterators, with type deduction.
941 template <class Iter>
942 constexpr Range<Iter> range(Iter first, Iter last) {
943 return Range<Iter>(first, last);
947 * Creates a range to reference the contents of a contiguous-storage container.
949 // Use pointers for types with '.data()' member
952 class T = typename std::remove_pointer<
953 decltype(std::declval<Collection>().data())>::type>
954 constexpr Range<T*> range(Collection&& v) {
955 return Range<T*>(v.data(), v.data() + v.size());
958 template <class T, size_t n>
959 constexpr Range<T*> range(T (&array)[n]) {
960 return Range<T*>(array, array + n);
963 template <class T, size_t n>
964 constexpr Range<const T*> range(const std::array<T, n>& array) {
965 return Range<const T*>{array};
968 typedef Range<const char*> StringPiece;
969 typedef Range<char*> MutableStringPiece;
970 typedef Range<const unsigned char*> ByteRange;
971 typedef Range<unsigned char*> MutableByteRange;
974 std::basic_ostream<C>& operator<<(
975 std::basic_ostream<C>& os,
976 Range<C const*> piece) {
977 using StreamSize = decltype(os.width());
978 os.write(piece.start(), static_cast<StreamSize>(piece.size()));
983 std::basic_ostream<C>& operator<<(std::basic_ostream<C>& os, Range<C*> piece) {
984 using StreamSize = decltype(os.width());
985 os.write(piece.start(), static_cast<StreamSize>(piece.size()));
990 * Templated comparison operators
993 template <class Iter>
994 inline bool operator==(const Range<Iter>& lhs, const Range<Iter>& rhs) {
995 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
998 template <class Iter>
999 inline bool operator<(const Range<Iter>& lhs, const Range<Iter>& rhs) {
1000 return lhs.compare(rhs) < 0;
1004 * Specializations of comparison operators for StringPiece
1009 template <class A, class B>
1010 struct ComparableAsStringPiece {
1013 (std::is_convertible<A, StringPiece>::value
1014 && std::is_same<B, StringPiece>::value)
1016 (std::is_convertible<B, StringPiece>::value
1017 && std::is_same<A, StringPiece>::value)
1021 } // namespace detail
1024 * operator== through conversion for Range<const char*>
1026 template <class T, class U>
1028 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
1029 operator==(const T& lhs, const U& rhs) {
1030 return StringPiece(lhs) == StringPiece(rhs);
1034 * operator< through conversion for Range<const char*>
1036 template <class T, class U>
1038 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
1039 operator<(const T& lhs, const U& rhs) {
1040 return StringPiece(lhs) < StringPiece(rhs);
1044 * operator> through conversion for Range<const char*>
1046 template <class T, class U>
1048 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
1049 operator>(const T& lhs, const U& rhs) {
1050 return StringPiece(lhs) > StringPiece(rhs);
1054 * operator< through conversion for Range<const char*>
1056 template <class T, class U>
1058 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
1059 operator<=(const T& lhs, const U& rhs) {
1060 return StringPiece(lhs) <= StringPiece(rhs);
1064 * operator> through conversion for Range<const char*>
1066 template <class T, class U>
1068 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
1069 operator>=(const T& lhs, const U& rhs) {
1070 return StringPiece(lhs) >= StringPiece(rhs);
1074 * Finds substrings faster than brute force by borrowing from Boyer-Moore
1076 template <class Iter, class Comp>
1077 size_t qfind(const Range<Iter>& haystack,
1078 const Range<Iter>& needle,
1080 // Don't use std::search, use a Boyer-Moore-like trick by comparing
1081 // the last characters first
1082 auto const nsize = needle.size();
1083 if (haystack.size() < nsize) {
1084 return std::string::npos;
1086 if (!nsize) return 0;
1087 auto const nsize_1 = nsize - 1;
1088 auto const lastNeedle = needle[nsize_1];
1090 // Boyer-Moore skip value for the last char in the needle. Zero is
1091 // not a valid value; skip will be computed the first time it's
1093 std::string::size_type skip = 0;
1095 auto i = haystack.begin();
1096 auto iEnd = haystack.end() - nsize_1;
1099 // Boyer-Moore: match the last element in the needle
1100 while (!eq(i[nsize_1], lastNeedle)) {
1103 return std::string::npos;
1106 // Here we know that the last char matches
1107 // Continue in pedestrian mode
1108 for (size_t j = 0; ; ) {
1110 if (!eq(i[j], needle[j])) {
1111 // Not found, we can skip
1112 // Compute the skip value lazily
1115 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
1122 // Check if done searching
1125 return size_t(i - haystack.begin());
1129 return std::string::npos;
1134 inline size_t qfind_first_byte_of(const StringPiece haystack,
1135 const StringPiece needles) {
1136 static auto const qfind_first_byte_of_fn =
1137 folly::CpuId().sse42() ? qfind_first_byte_of_sse42
1138 : qfind_first_byte_of_nosse;
1139 return qfind_first_byte_of_fn(haystack, needles);
1142 } // namespace detail
1144 template <class Iter, class Comp>
1145 size_t qfind_first_of(const Range<Iter> & haystack,
1146 const Range<Iter> & needles,
1148 auto ret = std::find_first_of(haystack.begin(), haystack.end(),
1149 needles.begin(), needles.end(),
1151 return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
1154 struct AsciiCaseSensitive {
1155 bool operator()(char lhs, char rhs) const {
1161 * Check if two ascii characters are case insensitive equal.
1162 * The difference between the lower/upper case characters are the 6-th bit.
1163 * We also check they are alpha chars, in case of xor = 32.
1165 struct AsciiCaseInsensitive {
1166 bool operator()(char lhs, char rhs) const {
1168 if (k == 0) return true;
1169 if (k != 32) return false;
1171 return (k >= 'a' && k <= 'z');
1175 template <class Iter>
1176 size_t qfind(const Range<Iter>& haystack,
1177 const typename Range<Iter>::value_type& needle) {
1178 auto pos = std::find(haystack.begin(), haystack.end(), needle);
1179 return pos == haystack.end() ? std::string::npos : pos - haystack.data();
1182 template <class Iter>
1183 size_t rfind(const Range<Iter>& haystack,
1184 const typename Range<Iter>::value_type& needle) {
1185 for (auto i = haystack.size(); i-- > 0; ) {
1186 if (haystack[i] == needle) {
1190 return std::string::npos;
1193 // specialization for StringPiece
1195 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
1196 // memchr expects a not-null pointer, early return if the range is empty.
1197 if (haystack.empty()) {
1198 return std::string::npos;
1200 auto pos = static_cast<const char*>(
1201 ::memchr(haystack.data(), needle, haystack.size()));
1202 return pos == nullptr ? std::string::npos : pos - haystack.data();
1206 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
1207 // memchr expects a not-null pointer, early return if the range is empty.
1208 if (haystack.empty()) {
1209 return std::string::npos;
1211 auto pos = static_cast<const char*>(
1212 ::memrchr(haystack.data(), needle, haystack.size()));
1213 return pos == nullptr ? std::string::npos : pos - haystack.data();
1216 // specialization for ByteRange
1218 inline size_t qfind(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 ::memchr(haystack.data(), needle, haystack.size()));
1226 return pos == nullptr ? std::string::npos : pos - haystack.data();
1230 inline size_t rfind(const Range<const unsigned char*>& haystack,
1231 const unsigned char& needle) {
1232 // memchr expects a not-null pointer, early return if the range is empty.
1233 if (haystack.empty()) {
1234 return std::string::npos;
1236 auto pos = static_cast<const unsigned char*>(
1237 ::memrchr(haystack.data(), needle, haystack.size()));
1238 return pos == nullptr ? std::string::npos : pos - haystack.data();
1241 template <class Iter>
1242 size_t qfind_first_of(const Range<Iter>& haystack,
1243 const Range<Iter>& needles) {
1244 return qfind_first_of(haystack, needles, AsciiCaseSensitive());
1247 // specialization for StringPiece
1249 inline size_t qfind_first_of(const Range<const char*>& haystack,
1250 const Range<const char*>& needles) {
1251 return detail::qfind_first_byte_of(haystack, needles);
1254 // specialization for ByteRange
1256 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
1257 const Range<const unsigned char*>& needles) {
1258 return detail::qfind_first_byte_of(StringPiece(haystack),
1259 StringPiece(needles));
1262 template<class Key, class Enable>
1266 struct hasher<folly::Range<T*>,
1267 typename std::enable_if<std::is_pod<T>::value, void>::type> {
1268 size_t operator()(folly::Range<T*> r) const {
1269 return hash::SpookyHashV2::Hash64(r.begin(), r.size() * sizeof(T), 0);
1274 * Ubiquitous helper template for knowing what's a string
1276 template <class T> struct IsSomeString {
1277 enum { value = std::is_same<T, std::string>::value
1278 || std::is_same<T, fbstring>::value };
1281 } // !namespace folly
1285 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);