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.
59 #pragma GCC diagnostic push
60 #pragma GCC diagnostic ignored "-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;
367 void assign(Iter start, Iter end) {
372 void reset(Iter start, size_type size) {
377 // Works only for Range<const char*>
378 void reset(const std::string& str) {
379 reset(str.data(), str.size());
382 constexpr size_type size() const {
383 // It would be nice to assert(b_ <= e_) here. This can be achieved even
384 // in a C++11 compatible constexpr function:
385 // http://ericniebler.com/2014/09/27/assert-and-constexpr-in-cxx11/
386 // Unfortunately current gcc versions have a bug causing it to reject
387 // this check in a constexpr function:
388 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=71448
389 return size_type(e_ - b_);
391 constexpr size_type walk_size() const {
392 return size_type(std::distance(b_, e_));
394 constexpr bool empty() const {
397 constexpr Iter data() const {
400 constexpr Iter start() const {
403 constexpr Iter begin() const {
406 constexpr Iter end() const {
409 constexpr Iter cbegin() const {
412 constexpr Iter cend() const {
415 value_type& front() {
421 return detail::value_before(e_);
423 const value_type& front() const {
427 const value_type& back() const {
429 return detail::value_before(e_);
431 // Works only for Range<const char*> and Range<char*>
432 std::string str() const { return std::string(b_, size()); }
433 std::string toString() const { return str(); }
434 // Works only for Range<const char*> and Range<char*>
435 fbstring fbstr() const { return fbstring(b_, size()); }
436 fbstring toFbstring() const { return fbstr(); }
438 const_range_type castToConst() const {
439 return const_range_type(*this);
442 // Works only for Range<const char*> and Range<char*>
443 int compare(const const_range_type& o) const {
444 const size_type tsize = this->size();
445 const size_type osize = o.size();
446 const size_type msize = std::min(tsize, osize);
447 int r = traits_type::compare(data(), o.data(), msize);
448 if (r == 0 && tsize != osize) {
449 // We check the signed bit of the subtraction and bit shift it
450 // to produce either 0 or 2. The subtraction yields the
451 // comparison values of either -1 or 1.
452 r = (static_cast<int>(
453 (osize - tsize) >> (CHAR_BIT * sizeof(size_t) - 1)) << 1) - 1;
458 value_type& operator[](size_t i) {
459 DCHECK_GT(size(), i);
463 const value_type& operator[](size_t i) const {
464 DCHECK_GT(size(), i);
468 value_type& at(size_t i) {
469 if (i >= size()) std::__throw_out_of_range("index out of range");
473 const value_type& at(size_t i) const {
474 if (i >= size()) std::__throw_out_of_range("index out of range");
478 // Do NOT use this function, which was left behind for backwards
479 // compatibility. Use SpookyHashV2 instead -- it is faster, and produces
480 // a 64-bit hash, which means dramatically fewer collisions in large maps.
481 // (The above advice does not apply if you are targeting a 32-bit system.)
483 // Works only for Range<const char*> and Range<char*>
486 // ** WANT TO GET RID OF THIS LINT? **
488 // A) Use a better hash function (*cough*folly::Hash*cough*), but
489 // only if you don't serialize data in a format that depends on
490 // this formula (ie the writer and reader assume this exact hash
491 // function is used).
493 // B) If you have to use this exact function then make your own hasher
494 // object and copy the body over (see thrift example: D3972362).
495 // https://github.com/facebook/fbthrift/commit/f8ed502e24ab4a32a9d5f266580
496 FOLLY_DEPRECATED("Replace with folly::Hash if the hash is not serialized")
497 uint32_t hash() const {
498 // Taken from fbi/nstring.h:
499 // Quick and dirty bernstein hash...fine for short ascii strings
500 uint32_t hash = 5381;
501 for (size_t ix = 0; ix < size(); ix++) {
502 hash = ((hash << 5) + hash) + b_[ix];
507 void advance(size_type n) {
508 if (UNLIKELY(n > size())) {
509 std::__throw_out_of_range("index out of range");
514 void subtract(size_type n) {
515 if (UNLIKELY(n > size())) {
516 std::__throw_out_of_range("index out of range");
521 Range subpiece(size_type first, size_type length = npos) const {
522 if (UNLIKELY(first > size())) {
523 std::__throw_out_of_range("index out of range");
526 return Range(b_ + first, std::min(length, size() - first));
529 // unchecked versions
530 void uncheckedAdvance(size_type n) {
531 DCHECK_LE(n, size());
535 void uncheckedSubtract(size_type n) {
536 DCHECK_LE(n, size());
540 Range uncheckedSubpiece(size_type first, size_type length = npos) const {
541 DCHECK_LE(first, size());
542 return Range(b_ + first, std::min(length, size() - first));
555 // string work-alike functions
556 size_type find(const_range_type str) const {
557 return qfind(castToConst(), str);
560 size_type find(const_range_type str, size_t pos) const {
561 if (pos > size()) return std::string::npos;
562 size_t ret = qfind(castToConst().subpiece(pos), str);
563 return ret == npos ? ret : ret + pos;
566 size_type find(Iter s, size_t pos, size_t n) const {
567 if (pos > size()) return std::string::npos;
568 auto forFinding = castToConst();
570 pos ? forFinding.subpiece(pos) : forFinding, const_range_type(s, n));
571 return ret == npos ? ret : ret + pos;
574 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
575 size_type find(const Iter s) const {
576 return qfind(castToConst(), const_range_type(s));
579 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
580 size_type find(const Iter s, size_t pos) const {
581 if (pos > size()) return std::string::npos;
582 size_type ret = qfind(castToConst().subpiece(pos), const_range_type(s));
583 return ret == npos ? ret : ret + pos;
586 size_type find(value_type c) const {
587 return qfind(castToConst(), c);
590 size_type rfind(value_type c) const {
591 return folly::rfind(castToConst(), c);
594 size_type find(value_type c, size_t pos) const {
595 if (pos > size()) return std::string::npos;
596 size_type ret = qfind(castToConst().subpiece(pos), c);
597 return ret == npos ? ret : ret + pos;
600 size_type find_first_of(const_range_type needles) const {
601 return qfind_first_of(castToConst(), needles);
604 size_type find_first_of(const_range_type needles, size_t pos) const {
605 if (pos > size()) return std::string::npos;
606 size_type ret = qfind_first_of(castToConst().subpiece(pos), needles);
607 return ret == npos ? ret : ret + pos;
610 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
611 size_type find_first_of(Iter needles) const {
612 return find_first_of(const_range_type(needles));
615 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
616 size_type find_first_of(Iter needles, size_t pos) const {
617 return find_first_of(const_range_type(needles), pos);
620 size_type find_first_of(Iter needles, size_t pos, size_t n) const {
621 return find_first_of(const_range_type(needles, n), pos);
624 size_type find_first_of(value_type c) const {
628 size_type find_first_of(value_type c, size_t pos) const {
633 * Determine whether the range contains the given subrange or item.
635 * Note: Call find() directly if the index is needed.
637 bool contains(const const_range_type& other) const {
638 return find(other) != std::string::npos;
641 bool contains(const value_type& other) const {
642 return find(other) != std::string::npos;
645 void swap(Range& rhs) {
646 std::swap(b_, rhs.b_);
647 std::swap(e_, rhs.e_);
651 * Does this Range start with another range?
653 bool startsWith(const const_range_type& other) const {
654 return size() >= other.size()
655 && castToConst().subpiece(0, other.size()) == other;
657 bool startsWith(value_type c) const {
658 return !empty() && front() == c;
661 template <class Comp>
662 bool startsWith(const const_range_type& other, Comp&& eq) const {
663 if (size() < other.size()) {
666 auto const trunc = subpiece(0, other.size());
668 trunc.begin(), trunc.end(), other.begin(), std::forward<Comp>(eq));
672 * Does this Range end with another range?
674 bool endsWith(const const_range_type& other) const {
675 return size() >= other.size()
676 && castToConst().subpiece(size() - other.size()) == other;
678 bool endsWith(value_type c) const {
679 return !empty() && back() == c;
682 template <class Comp>
683 bool endsWith(const const_range_type& other, Comp&& eq) const {
684 if (size() < other.size()) {
687 auto const trunc = subpiece(size() - other.size());
689 trunc.begin(), trunc.end(), other.begin(), std::forward<Comp>(eq));
693 * Remove the items in [b, e), as long as this subrange is at the beginning
694 * or end of the Range.
696 * Required for boost::algorithm::trim()
698 void erase(Iter b, Iter e) {
701 } else if (e == e_) {
704 std::__throw_out_of_range("index out of range");
709 * Remove the given prefix and return true if the range starts with the given
710 * prefix; return false otherwise.
712 bool removePrefix(const const_range_type& prefix) {
713 return startsWith(prefix) && (b_ += prefix.size(), true);
715 bool removePrefix(value_type prefix) {
716 return startsWith(prefix) && (++b_, true);
720 * Remove the given suffix and return true if the range ends with the given
721 * suffix; return false otherwise.
723 bool removeSuffix(const const_range_type& suffix) {
724 return endsWith(suffix) && (e_ -= suffix.size(), true);
726 bool removeSuffix(value_type suffix) {
727 return endsWith(suffix) && (--e_, true);
731 * Replaces the content of the range, starting at position 'pos', with
732 * contents of 'replacement'. Entire 'replacement' must fit into the
733 * range. Returns false if 'replacements' does not fit. Example use:
735 * char in[] = "buffer";
736 * auto msp = MutablesStringPiece(input);
737 * EXPECT_TRUE(msp.replaceAt(2, "tt"));
738 * EXPECT_EQ(msp, "butter");
740 * // not enough space
741 * EXPECT_FALSE(msp.replace(msp.size() - 1, "rr"));
742 * EXPECT_EQ(msp, "butter"); // unchanged
744 bool replaceAt(size_t pos, const_range_type replacement) {
745 if (size() < pos + replacement.size()) {
749 std::copy(replacement.begin(), replacement.end(), begin() + pos);
755 * Replaces all occurences of 'source' with 'dest'. Returns number
756 * of replacements made. Source and dest have to have the same
757 * length. Throws if the lengths are different. If 'source' is a
758 * pattern that is overlapping with itself, we perform sequential
759 * replacement: "aaaaaaa".replaceAll("aa", "ba") --> "bababaa"
763 * char in[] = "buffer";
764 * auto msp = MutablesStringPiece(input);
765 * EXPECT_EQ(msp.replaceAll("ff","tt"), 1);
766 * EXPECT_EQ(msp, "butter");
768 size_t replaceAll(const_range_type source, const_range_type dest) {
769 if (source.size() != dest.size()) {
770 throw std::invalid_argument(
771 "replacement must have the same size as source");
779 size_t num_replaced = 0;
780 size_type found = std::string::npos;
781 while ((found = find(source, pos)) != std::string::npos) {
782 replaceAt(found, dest);
783 pos += source.size();
791 * Splits this `Range` `[b, e)` in the position `i` dictated by the next
792 * occurence of `delimiter`.
794 * Returns a new `Range` `[b, i)` and adjusts this range to start right after
795 * the delimiter's position. This range will be empty if the delimiter is not
796 * found. If called on an empty `Range`, both this and the returned `Range`
801 * folly::StringPiece s("sample string for split_next");
802 * auto p = s.split_step(' ');
804 * // prints "string for split_next"
812 * void tokenize(StringPiece s, char delimiter) {
813 * while (!s.empty()) {
814 * cout << s.split_step(delimiter);
818 * @author: Marcelo Juchem <marcelo@fb.com>
820 Range split_step(value_type delimiter) {
821 auto i = std::find(b_, e_, delimiter);
824 b_ = i == e_ ? e_ : std::next(i);
829 Range split_step(Range delimiter) {
830 auto i = find(delimiter);
831 Range result(b_, i == std::string::npos ? size() : i);
833 b_ = result.end() == e_
837 typename std::iterator_traits<Iter>::difference_type(
844 * Convenience method that calls `split_step()` and passes the result to a
845 * functor, returning whatever the functor does. Any additional arguments
846 * `args` passed to this function are perfectly forwarded to the functor.
848 * Say you have a functor with this signature:
850 * Foo fn(Range r) { }
852 * `split_step()`'s return type will be `Foo`. It works just like:
854 * auto result = fn(myRange.split_step(' '));
856 * A functor returning `void` is also supported.
860 * void do_some_parsing(folly::StringPiece s) {
861 * auto version = s.split_step(' ', [&](folly::StringPiece x) {
863 * throw std::invalid_argument("empty string");
865 * return std::strtoull(x.begin(), x.end(), 16);
872 * void parse(folly::StringPiece s) {
873 * s.split_step(' ', parse_field, bar, 10);
874 * s.split_step('\t', parse_field, baz, 20);
876 * auto const kludge = [](folly::StringPiece x, int &out, int def) {
880 * parse_field(x, out, def);
884 * s.split_step('\t', kludge, gaz);
885 * s.split_step(' ', kludge, foo);
894 * static parse_field(folly::StringPiece s, int &out, int def) {
896 * out = folly::to<int>(s);
897 * } catch (std::exception const &) {
903 * @author: Marcelo Juchem <marcelo@fb.com>
905 template <typename TProcess, typename... Args>
906 auto split_step(value_type delimiter, TProcess &&process, Args &&...args)
907 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
908 { return process(split_step(delimiter), std::forward<Args>(args)...); }
910 template <typename TProcess, typename... Args>
911 auto split_step(Range delimiter, TProcess &&process, Args &&...args)
912 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
913 { return process(split_step(delimiter), std::forward<Args>(args)...); }
919 template <class Iter>
920 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
922 template <class Iter>
923 void swap(Range<Iter>& lhs, Range<Iter>& rhs) {
928 * Create a range from two iterators, with type deduction.
930 template <class Iter>
931 constexpr Range<Iter> range(Iter first, Iter last) {
932 return Range<Iter>(first, last);
936 * Creates a range to reference the contents of a contiguous-storage container.
938 // Use pointers for types with '.data()' member
941 class T = typename std::remove_pointer<
942 decltype(std::declval<Collection>().data())>::type>
943 constexpr Range<T*> range(Collection&& v) {
944 return Range<T*>(v.data(), v.data() + v.size());
947 template <class T, size_t n>
948 constexpr Range<T*> range(T (&array)[n]) {
949 return Range<T*>(array, array + n);
952 template <class T, size_t n>
953 constexpr Range<const T*> range(const std::array<T, n>& array) {
954 return Range<const T*>{array};
957 typedef Range<const char*> StringPiece;
958 typedef Range<char*> MutableStringPiece;
959 typedef Range<const unsigned char*> ByteRange;
960 typedef Range<unsigned char*> MutableByteRange;
962 inline std::ostream& operator<<(std::ostream& os,
963 const StringPiece piece) {
964 os.write(piece.start(), std::streamsize(piece.size()));
968 inline std::ostream& operator<<(std::ostream& os,
969 const MutableStringPiece piece) {
970 os.write(piece.start(), std::streamsize(piece.size()));
975 * Templated comparison operators
978 template <class Iter>
979 inline bool operator==(const Range<Iter>& lhs, const Range<Iter>& rhs) {
980 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
983 template <class Iter>
984 inline bool operator<(const Range<Iter>& lhs, const Range<Iter>& rhs) {
985 return lhs.compare(rhs) < 0;
989 * Specializations of comparison operators for StringPiece
994 template <class A, class B>
995 struct ComparableAsStringPiece {
998 (std::is_convertible<A, StringPiece>::value
999 && std::is_same<B, StringPiece>::value)
1001 (std::is_convertible<B, StringPiece>::value
1002 && std::is_same<A, StringPiece>::value)
1006 } // namespace detail
1009 * operator== through conversion for Range<const char*>
1011 template <class T, class U>
1013 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
1014 operator==(const T& lhs, const U& rhs) {
1015 return StringPiece(lhs) == StringPiece(rhs);
1019 * operator< through conversion for Range<const char*>
1021 template <class T, class U>
1023 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
1024 operator<(const T& lhs, const U& rhs) {
1025 return StringPiece(lhs) < StringPiece(rhs);
1029 * operator> through conversion for Range<const char*>
1031 template <class T, class U>
1033 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
1034 operator>(const T& lhs, const U& rhs) {
1035 return StringPiece(lhs) > StringPiece(rhs);
1039 * operator< through conversion for Range<const char*>
1041 template <class T, class U>
1043 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
1044 operator<=(const T& lhs, const U& rhs) {
1045 return StringPiece(lhs) <= StringPiece(rhs);
1049 * operator> through conversion for Range<const char*>
1051 template <class T, class U>
1053 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
1054 operator>=(const T& lhs, const U& rhs) {
1055 return StringPiece(lhs) >= StringPiece(rhs);
1059 * Finds substrings faster than brute force by borrowing from Boyer-Moore
1061 template <class Iter, class Comp>
1062 size_t qfind(const Range<Iter>& haystack,
1063 const Range<Iter>& needle,
1065 // Don't use std::search, use a Boyer-Moore-like trick by comparing
1066 // the last characters first
1067 auto const nsize = needle.size();
1068 if (haystack.size() < nsize) {
1069 return std::string::npos;
1071 if (!nsize) return 0;
1072 auto const nsize_1 = nsize - 1;
1073 auto const lastNeedle = needle[nsize_1];
1075 // Boyer-Moore skip value for the last char in the needle. Zero is
1076 // not a valid value; skip will be computed the first time it's
1078 std::string::size_type skip = 0;
1080 auto i = haystack.begin();
1081 auto iEnd = haystack.end() - nsize_1;
1084 // Boyer-Moore: match the last element in the needle
1085 while (!eq(i[nsize_1], lastNeedle)) {
1088 return std::string::npos;
1091 // Here we know that the last char matches
1092 // Continue in pedestrian mode
1093 for (size_t j = 0; ; ) {
1095 if (!eq(i[j], needle[j])) {
1096 // Not found, we can skip
1097 // Compute the skip value lazily
1100 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
1107 // Check if done searching
1110 return size_t(i - haystack.begin());
1114 return std::string::npos;
1119 inline size_t qfind_first_byte_of(const StringPiece haystack,
1120 const StringPiece needles) {
1121 static auto const qfind_first_byte_of_fn =
1122 folly::CpuId().sse42() ? qfind_first_byte_of_sse42
1123 : qfind_first_byte_of_nosse;
1124 return qfind_first_byte_of_fn(haystack, needles);
1127 } // namespace detail
1129 template <class Iter, class Comp>
1130 size_t qfind_first_of(const Range<Iter> & haystack,
1131 const Range<Iter> & needles,
1133 auto ret = std::find_first_of(haystack.begin(), haystack.end(),
1134 needles.begin(), needles.end(),
1136 return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
1139 struct AsciiCaseSensitive {
1140 bool operator()(char lhs, char rhs) const {
1146 * Check if two ascii characters are case insensitive equal.
1147 * The difference between the lower/upper case characters are the 6-th bit.
1148 * We also check they are alpha chars, in case of xor = 32.
1150 struct AsciiCaseInsensitive {
1151 bool operator()(char lhs, char rhs) const {
1153 if (k == 0) return true;
1154 if (k != 32) return false;
1156 return (k >= 'a' && k <= 'z');
1160 template <class Iter>
1161 size_t qfind(const Range<Iter>& haystack,
1162 const typename Range<Iter>::value_type& needle) {
1163 auto pos = std::find(haystack.begin(), haystack.end(), needle);
1164 return pos == haystack.end() ? std::string::npos : pos - haystack.data();
1167 template <class Iter>
1168 size_t rfind(const Range<Iter>& haystack,
1169 const typename Range<Iter>::value_type& needle) {
1170 for (auto i = haystack.size(); i-- > 0; ) {
1171 if (haystack[i] == needle) {
1175 return std::string::npos;
1178 // specialization for StringPiece
1180 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
1181 // memchr expects a not-null pointer, early return if the range is empty.
1182 if (haystack.empty()) {
1183 return std::string::npos;
1185 auto pos = static_cast<const char*>(
1186 ::memchr(haystack.data(), needle, haystack.size()));
1187 return pos == nullptr ? std::string::npos : pos - haystack.data();
1191 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
1192 // memchr expects a not-null pointer, early return if the range is empty.
1193 if (haystack.empty()) {
1194 return std::string::npos;
1196 auto pos = static_cast<const char*>(
1197 ::memrchr(haystack.data(), needle, haystack.size()));
1198 return pos == nullptr ? std::string::npos : pos - haystack.data();
1201 // specialization for ByteRange
1203 inline size_t qfind(const Range<const unsigned char*>& haystack,
1204 const unsigned char& needle) {
1205 // memchr expects a not-null pointer, early return if the range is empty.
1206 if (haystack.empty()) {
1207 return std::string::npos;
1209 auto pos = static_cast<const unsigned char*>(
1210 ::memchr(haystack.data(), needle, haystack.size()));
1211 return pos == nullptr ? std::string::npos : pos - haystack.data();
1215 inline size_t rfind(const Range<const unsigned char*>& haystack,
1216 const unsigned char& needle) {
1217 // memchr expects a not-null pointer, early return if the range is empty.
1218 if (haystack.empty()) {
1219 return std::string::npos;
1221 auto pos = static_cast<const unsigned char*>(
1222 ::memrchr(haystack.data(), needle, haystack.size()));
1223 return pos == nullptr ? std::string::npos : pos - haystack.data();
1226 template <class Iter>
1227 size_t qfind_first_of(const Range<Iter>& haystack,
1228 const Range<Iter>& needles) {
1229 return qfind_first_of(haystack, needles, AsciiCaseSensitive());
1232 // specialization for StringPiece
1234 inline size_t qfind_first_of(const Range<const char*>& haystack,
1235 const Range<const char*>& needles) {
1236 return detail::qfind_first_byte_of(haystack, needles);
1239 // specialization for ByteRange
1241 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
1242 const Range<const unsigned char*>& needles) {
1243 return detail::qfind_first_byte_of(StringPiece(haystack),
1244 StringPiece(needles));
1247 template<class Key, class Enable>
1251 struct hasher<folly::Range<T*>,
1252 typename std::enable_if<std::is_pod<T>::value, void>::type> {
1253 size_t operator()(folly::Range<T*> r) const {
1254 return hash::SpookyHashV2::Hash64(r.begin(), r.size() * sizeof(T), 0);
1259 * Ubiquitous helper template for knowing what's a string
1261 template <class T> struct IsSomeString {
1262 enum { value = std::is_same<T, std::string>::value
1263 || std::is_same<T, fbstring>::value };
1266 } // !namespace folly
1268 #pragma GCC diagnostic pop
1270 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);