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>
30 #include <boost/operators.hpp>
34 #include <glog/logging.h>
38 #include <type_traits>
40 // libc++ doesn't provide this header, nor does msvc
41 #ifdef FOLLY_HAVE_BITS_CXXCONFIG_H
42 // This file appears in two locations: inside fbcode and in the
43 // libstdc++ source code (when embedding fbstring as std::string).
44 // To aid in this schizophrenic use, two macros are defined in
46 // _LIBSTDCXX_FBSTRING - Set inside libstdc++. This is useful to
47 // gate use inside fbcode v. libstdc++
48 #include <bits/c++config.h>
51 #include <folly/CpuId.h>
52 #include <folly/Traits.h>
53 #include <folly/Likely.h>
54 #include <folly/detail/RangeCommon.h>
55 #include <folly/detail/RangeSse42.h>
57 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
58 #pragma GCC diagnostic push
59 #pragma GCC diagnostic ignored "-Wshadow"
63 template <class T> class Range;
66 * Finds the first occurrence of needle in haystack. The algorithm is on
67 * average faster than O(haystack.size() * needle.size()) but not as fast
68 * as Boyer-Moore. On the upside, it does not do any upfront
69 * preprocessing and does not allocate memory.
71 template <class T, class Comp = std::equal_to<typename Range<T>::value_type>>
72 inline size_t qfind(const Range<T> & haystack,
73 const Range<T> & needle,
77 * Finds the first occurrence of needle in haystack. The result is the
78 * offset reported to the beginning of haystack, or string::npos if
79 * needle wasn't found.
82 size_t qfind(const Range<T> & haystack,
83 const typename Range<T>::value_type& needle);
86 * Finds the last occurrence of needle in haystack. The result is the
87 * offset reported to the beginning of haystack, or string::npos if
88 * needle wasn't found.
91 size_t rfind(const Range<T> & haystack,
92 const typename Range<T>::value_type& needle);
96 * Finds the first occurrence of any element of needle in
97 * haystack. The algorithm is O(haystack.size() * needle.size()).
100 inline size_t qfind_first_of(const Range<T> & haystack,
101 const Range<T> & needle);
104 * Small internal helper - returns the value just before an iterator.
109 * For random-access iterators, the value before is simply i[-1].
111 template <class Iter>
112 typename std::enable_if<
113 std::is_same<typename std::iterator_traits<Iter>::iterator_category,
114 std::random_access_iterator_tag>::value,
115 typename std::iterator_traits<Iter>::reference>::type
116 value_before(Iter i) {
121 * For all other iterators, we need to use the decrement operator.
123 template <class Iter>
124 typename std::enable_if<
125 !std::is_same<typename std::iterator_traits<Iter>::iterator_category,
126 std::random_access_iterator_tag>::value,
127 typename std::iterator_traits<Iter>::reference>::type
128 value_before(Iter i) {
133 * Use IsCharPointer<T>::type to enable const char* or char*.
134 * Use IsCharPointer<T>::const_type to enable only const char*.
136 template <class T> struct IsCharPointer {};
139 struct IsCharPointer<char*> {
144 struct IsCharPointer<const char*> {
145 typedef int const_type;
149 } // namespace detail
152 * Range abstraction keeping a pair of iterators. We couldn't use
153 * boost's similar range abstraction because we need an API identical
154 * with the former StringPiece class, which is used by a lot of other
155 * code. This abstraction does fulfill the needs of boost's
156 * range-oriented algorithms though.
158 * (Keep memory lifetime in mind when using this class, since it
159 * doesn't manage the data it refers to - just like an iterator
162 template <class Iter>
163 class Range : private boost::totally_ordered<Range<Iter> > {
165 typedef std::size_t size_type;
166 typedef Iter iterator;
167 typedef Iter const_iterator;
168 typedef typename std::remove_reference<
169 typename std::iterator_traits<Iter>::reference>::type
171 using difference_type = typename std::iterator_traits<Iter>::difference_type;
172 typedef typename std::iterator_traits<Iter>::reference reference;
175 * For MutableStringPiece and MutableByteRange we define StringPiece
176 * and ByteRange as const_range_type (for everything else its just
177 * identity). We do that to enable operations such as find with
178 * args which are const.
180 typedef typename std::conditional<
181 std::is_same<Iter, char*>::value
182 || std::is_same<Iter, unsigned char*>::value,
183 Range<const value_type*>,
184 Range<Iter>>::type const_range_type;
186 typedef std::char_traits<typename std::remove_const<value_type>::type>
189 static const size_type npos;
191 // Works for all iterators
192 constexpr Range() : b_(), e_() {
195 constexpr Range(const Range&) = default;
196 constexpr Range(Range&&) = default;
199 // Works for all iterators
200 constexpr Range(Iter start, Iter end) : b_(start), e_(end) {
203 // Works only for random-access iterators
204 constexpr Range(Iter start, size_t size)
205 : b_(start), e_(start + size) { }
207 # if !__clang__ || __CLANG_PREREQ(3, 7) // Clang 3.6 crashes on this line
208 /* 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)
335 Range& operator=(const Range& rhs) & = default;
336 Range& operator=(Range&& rhs) & = default;
343 void assign(Iter start, Iter end) {
348 void reset(Iter start, size_type size) {
353 // Works only for Range<const char*>
354 void reset(const std::string& str) {
355 reset(str.data(), str.size());
358 constexpr size_type size() const {
359 // It would be nice to assert(b_ <= e_) here. This can be achieved even
360 // in a C++11 compatible constexpr function:
361 // http://ericniebler.com/2014/09/27/assert-and-constexpr-in-cxx11/
362 // Unfortunately current gcc versions have a bug causing it to reject
363 // this check in a constexpr function:
364 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=71448
365 return size_type(e_ - b_);
367 constexpr size_type walk_size() const {
368 return size_type(std::distance(b_, e_));
370 constexpr bool empty() const {
373 constexpr Iter data() const {
376 constexpr Iter start() const {
379 constexpr Iter begin() const {
382 constexpr Iter end() const {
385 constexpr Iter cbegin() const {
388 constexpr Iter cend() const {
391 value_type& front() {
397 return detail::value_before(e_);
399 const value_type& front() const {
403 const value_type& back() const {
405 return detail::value_before(e_);
407 // Works only for Range<const char*> and Range<char*>
408 std::string str() const { return std::string(b_, size()); }
409 std::string toString() const { return str(); }
410 // Works only for Range<const char*> and Range<char*>
411 fbstring fbstr() const { return fbstring(b_, size()); }
412 fbstring toFbstring() const { return fbstr(); }
414 const_range_type castToConst() const {
415 return const_range_type(*this);
418 // Works only for Range<const char*> and Range<char*>
419 int compare(const const_range_type& o) const {
420 const size_type tsize = this->size();
421 const size_type osize = o.size();
422 const size_type msize = std::min(tsize, osize);
423 int r = traits_type::compare(data(), o.data(), msize);
424 if (r == 0 && tsize != osize) {
425 // We check the signed bit of the subtraction and bit shift it
426 // to produce either 0 or 2. The subtraction yields the
427 // comparison values of either -1 or 1.
428 r = (static_cast<int>(
429 (osize - tsize) >> (CHAR_BIT * sizeof(size_t) - 1)) << 1) - 1;
434 value_type& operator[](size_t i) {
435 DCHECK_GT(size(), i);
439 const value_type& operator[](size_t i) const {
440 DCHECK_GT(size(), i);
444 value_type& at(size_t i) {
445 if (i >= size()) std::__throw_out_of_range("index out of range");
449 const value_type& at(size_t i) const {
450 if (i >= size()) std::__throw_out_of_range("index out of range");
454 // Do NOT use this function, which was left behind for backwards
455 // compatibility. Use SpookyHashV2 instead -- it is faster, and produces
456 // a 64-bit hash, which means dramatically fewer collisions in large maps.
457 // (The above advice does not apply if you are targeting a 32-bit system.)
459 // Works only for Range<const char*> and Range<char*>
462 // ** WANT TO GET RID OF THIS LINT? **
464 // A) Use a better hash function (*cough*folly::Hash*cough*), but
465 // only if you don't serialize data in a format that depends on
466 // this formula (ie the writer and reader assume this exact hash
467 // function is used).
469 // B) If you have to use this exact function then make your own hasher
470 // object and copy the body over (see thrift example: D3972362).
471 // https://github.com/facebook/fbthrift/commit/f8ed502e24ab4a32a9d5f266580
472 FOLLY_DEPRECATED("Replace with folly::Hash if the hash is not serialized")
473 uint32_t hash() const {
474 // Taken from fbi/nstring.h:
475 // Quick and dirty bernstein hash...fine for short ascii strings
476 uint32_t hash = 5381;
477 for (size_t ix = 0; ix < size(); ix++) {
478 hash = ((hash << 5) + hash) + b_[ix];
483 void advance(size_type n) {
484 if (UNLIKELY(n > size())) {
485 std::__throw_out_of_range("index out of range");
490 void subtract(size_type n) {
491 if (UNLIKELY(n > size())) {
492 std::__throw_out_of_range("index out of range");
497 Range subpiece(size_type first, size_type length = npos) const {
498 if (UNLIKELY(first > size())) {
499 std::__throw_out_of_range("index out of range");
502 return Range(b_ + first, std::min(length, size() - first));
505 // unchecked versions
506 void uncheckedAdvance(size_type n) {
507 DCHECK_LE(n, size());
511 void uncheckedSubtract(size_type n) {
512 DCHECK_LE(n, size());
516 Range uncheckedSubpiece(size_type first, size_type length = npos) const {
517 DCHECK_LE(first, size());
518 return Range(b_ + first, std::min(length, size() - first));
531 // string work-alike functions
532 size_type find(const_range_type str) const {
533 return qfind(castToConst(), str);
536 size_type find(const_range_type str, size_t pos) const {
537 if (pos > size()) return std::string::npos;
538 size_t ret = qfind(castToConst().subpiece(pos), str);
539 return ret == npos ? ret : ret + pos;
542 size_type find(Iter s, size_t pos, size_t n) const {
543 if (pos > size()) return std::string::npos;
544 auto forFinding = castToConst();
546 pos ? forFinding.subpiece(pos) : forFinding, const_range_type(s, n));
547 return ret == npos ? ret : ret + pos;
550 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
551 size_type find(const Iter s) const {
552 return qfind(castToConst(), const_range_type(s));
555 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
556 size_type find(const Iter s, size_t pos) const {
557 if (pos > size()) return std::string::npos;
558 size_type ret = qfind(castToConst().subpiece(pos), const_range_type(s));
559 return ret == npos ? ret : ret + pos;
562 size_type find(value_type c) const {
563 return qfind(castToConst(), c);
566 size_type rfind(value_type c) const {
567 return folly::rfind(castToConst(), c);
570 size_type find(value_type c, size_t pos) const {
571 if (pos > size()) return std::string::npos;
572 size_type ret = qfind(castToConst().subpiece(pos), c);
573 return ret == npos ? ret : ret + pos;
576 size_type find_first_of(const_range_type needles) const {
577 return qfind_first_of(castToConst(), needles);
580 size_type find_first_of(const_range_type needles, size_t pos) const {
581 if (pos > size()) return std::string::npos;
582 size_type ret = qfind_first_of(castToConst().subpiece(pos), needles);
583 return ret == npos ? ret : ret + pos;
586 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
587 size_type find_first_of(Iter needles) const {
588 return find_first_of(const_range_type(needles));
591 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
592 size_type find_first_of(Iter needles, size_t pos) const {
593 return find_first_of(const_range_type(needles), pos);
596 size_type find_first_of(Iter needles, size_t pos, size_t n) const {
597 return find_first_of(const_range_type(needles, n), pos);
600 size_type find_first_of(value_type c) const {
604 size_type find_first_of(value_type c, size_t pos) const {
609 * Determine whether the range contains the given subrange or item.
611 * Note: Call find() directly if the index is needed.
613 bool contains(const const_range_type& other) const {
614 return find(other) != std::string::npos;
617 bool contains(const value_type& other) const {
618 return find(other) != std::string::npos;
621 void swap(Range& rhs) {
622 std::swap(b_, rhs.b_);
623 std::swap(e_, rhs.e_);
627 * Does this Range start with another range?
629 bool startsWith(const const_range_type& other) const {
630 return size() >= other.size()
631 && castToConst().subpiece(0, other.size()) == other;
633 bool startsWith(value_type c) const {
634 return !empty() && front() == c;
638 * Does this Range end with another range?
640 bool endsWith(const const_range_type& other) const {
641 return size() >= other.size()
642 && castToConst().subpiece(size() - other.size()) == other;
644 bool endsWith(value_type c) const {
645 return !empty() && back() == c;
649 * Remove the items in [b, e), as long as this subrange is at the beginning
650 * or end of the Range.
652 * Required for boost::algorithm::trim()
654 void erase(Iter b, Iter e) {
657 } else if (e == e_) {
660 std::__throw_out_of_range("index out of range");
665 * Remove the given prefix and return true if the range starts with the given
666 * prefix; return false otherwise.
668 bool removePrefix(const const_range_type& prefix) {
669 return startsWith(prefix) && (b_ += prefix.size(), true);
671 bool removePrefix(value_type prefix) {
672 return startsWith(prefix) && (++b_, true);
676 * Remove the given suffix and return true if the range ends with the given
677 * suffix; return false otherwise.
679 bool removeSuffix(const const_range_type& suffix) {
680 return endsWith(suffix) && (e_ -= suffix.size(), true);
682 bool removeSuffix(value_type suffix) {
683 return endsWith(suffix) && (--e_, true);
687 * Replaces the content of the range, starting at position 'pos', with
688 * contents of 'replacement'. Entire 'replacement' must fit into the
689 * range. Returns false if 'replacements' does not fit. Example use:
691 * char in[] = "buffer";
692 * auto msp = MutablesStringPiece(input);
693 * EXPECT_TRUE(msp.replaceAt(2, "tt"));
694 * EXPECT_EQ(msp, "butter");
696 * // not enough space
697 * EXPECT_FALSE(msp.replace(msp.size() - 1, "rr"));
698 * EXPECT_EQ(msp, "butter"); // unchanged
700 bool replaceAt(size_t pos, const_range_type replacement) {
701 if (size() < pos + replacement.size()) {
705 std::copy(replacement.begin(), replacement.end(), begin() + pos);
711 * Replaces all occurences of 'source' with 'dest'. Returns number
712 * of replacements made. Source and dest have to have the same
713 * length. Throws if the lengths are different. If 'source' is a
714 * pattern that is overlapping with itself, we perform sequential
715 * replacement: "aaaaaaa".replaceAll("aa", "ba") --> "bababaa"
719 * char in[] = "buffer";
720 * auto msp = MutablesStringPiece(input);
721 * EXPECT_EQ(msp.replaceAll("ff","tt"), 1);
722 * EXPECT_EQ(msp, "butter");
724 size_t replaceAll(const_range_type source, const_range_type dest) {
725 if (source.size() != dest.size()) {
726 throw std::invalid_argument(
727 "replacement must have the same size as source");
735 size_t num_replaced = 0;
736 size_type found = std::string::npos;
737 while ((found = find(source, pos)) != std::string::npos) {
738 replaceAt(found, dest);
739 pos += source.size();
747 * Splits this `Range` `[b, e)` in the position `i` dictated by the next
748 * occurence of `delimiter`.
750 * Returns a new `Range` `[b, i)` and adjusts this range to start right after
751 * the delimiter's position. This range will be empty if the delimiter is not
752 * found. If called on an empty `Range`, both this and the returned `Range`
757 * folly::StringPiece s("sample string for split_next");
758 * auto p = s.split_step(' ');
760 * // prints "string for split_next"
768 * void tokenize(StringPiece s, char delimiter) {
769 * while (!s.empty()) {
770 * cout << s.split_step(delimiter);
774 * @author: Marcelo Juchem <marcelo@fb.com>
776 Range split_step(value_type delimiter) {
777 auto i = std::find(b_, e_, delimiter);
780 b_ = i == e_ ? e_ : std::next(i);
785 Range split_step(Range delimiter) {
786 auto i = find(delimiter);
787 Range result(b_, i == std::string::npos ? size() : i);
789 b_ = result.end() == e_
793 typename std::iterator_traits<Iter>::difference_type(
800 * Convenience method that calls `split_step()` and passes the result to a
801 * functor, returning whatever the functor does. Any additional arguments
802 * `args` passed to this function are perfectly forwarded to the functor.
804 * Say you have a functor with this signature:
806 * Foo fn(Range r) { }
808 * `split_step()`'s return type will be `Foo`. It works just like:
810 * auto result = fn(myRange.split_step(' '));
812 * A functor returning `void` is also supported.
816 * void do_some_parsing(folly::StringPiece s) {
817 * auto version = s.split_step(' ', [&](folly::StringPiece x) {
819 * throw std::invalid_argument("empty string");
821 * return std::strtoull(x.begin(), x.end(), 16);
828 * void parse(folly::StringPiece s) {
829 * s.split_step(' ', parse_field, bar, 10);
830 * s.split_step('\t', parse_field, baz, 20);
832 * auto const kludge = [](folly::StringPiece x, int &out, int def) {
836 * parse_field(x, out, def);
840 * s.split_step('\t', kludge, gaz);
841 * s.split_step(' ', kludge, foo);
850 * static parse_field(folly::StringPiece s, int &out, int def) {
852 * out = folly::to<int>(s);
853 * } catch (std::exception const &) {
859 * @author: Marcelo Juchem <marcelo@fb.com>
861 template <typename TProcess, typename... Args>
862 auto split_step(value_type delimiter, TProcess &&process, Args &&...args)
863 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
864 { return process(split_step(delimiter), std::forward<Args>(args)...); }
866 template <typename TProcess, typename... Args>
867 auto split_step(Range delimiter, TProcess &&process, Args &&...args)
868 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
869 { return process(split_step(delimiter), std::forward<Args>(args)...); }
875 template <class Iter>
876 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
879 void swap(Range<T>& lhs, Range<T>& rhs) {
884 * Create a range from two iterators, with type deduction.
886 template <class Iter>
887 constexpr Range<Iter> range(Iter first, Iter last) {
888 return Range<Iter>(first, last);
892 * Creates a range to reference the contents of a contiguous-storage container.
894 // Use pointers for types with '.data()' member
897 class T = typename std::remove_pointer<
898 decltype(std::declval<Collection>().data())>::type>
899 constexpr Range<T*> range(Collection&& v) {
900 return Range<T*>(v.data(), v.data() + v.size());
903 template <class T, size_t n>
904 constexpr Range<T*> range(T (&array)[n]) {
905 return Range<T*>(array, array + n);
908 template <class T, size_t n>
909 constexpr Range<const T*> range(const std::array<T, n>& array) {
910 using r = Range<const T*>;
911 return array.empty() ? r{} : r(&array.at(0), &array.at(0) + n);
914 typedef Range<const char*> StringPiece;
915 typedef Range<char*> MutableStringPiece;
916 typedef Range<const unsigned char*> ByteRange;
917 typedef Range<unsigned char*> MutableByteRange;
919 inline std::ostream& operator<<(std::ostream& os,
920 const StringPiece piece) {
921 os.write(piece.start(), std::streamsize(piece.size()));
925 inline std::ostream& operator<<(std::ostream& os,
926 const MutableStringPiece piece) {
927 os.write(piece.start(), std::streamsize(piece.size()));
932 * Templated comparison operators
936 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
937 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
941 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
942 return lhs.compare(rhs) < 0;
946 * Specializations of comparison operators for StringPiece
951 template <class A, class B>
952 struct ComparableAsStringPiece {
955 (std::is_convertible<A, StringPiece>::value
956 && std::is_same<B, StringPiece>::value)
958 (std::is_convertible<B, StringPiece>::value
959 && std::is_same<A, StringPiece>::value)
963 } // namespace detail
966 * operator== through conversion for Range<const char*>
968 template <class T, class U>
970 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
971 operator==(const T& lhs, const U& rhs) {
972 return StringPiece(lhs) == StringPiece(rhs);
976 * operator< through conversion for Range<const char*>
978 template <class T, class U>
980 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
981 operator<(const T& lhs, const U& rhs) {
982 return StringPiece(lhs) < StringPiece(rhs);
986 * operator> through conversion for Range<const char*>
988 template <class T, class U>
990 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
991 operator>(const T& lhs, const U& rhs) {
992 return StringPiece(lhs) > StringPiece(rhs);
996 * operator< through conversion for Range<const char*>
998 template <class T, class U>
1000 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
1001 operator<=(const T& lhs, const U& rhs) {
1002 return StringPiece(lhs) <= StringPiece(rhs);
1006 * operator> through conversion for Range<const char*>
1008 template <class T, class U>
1010 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
1011 operator>=(const T& lhs, const U& rhs) {
1012 return StringPiece(lhs) >= StringPiece(rhs);
1016 * Finds substrings faster than brute force by borrowing from Boyer-Moore
1018 template <class T, class Comp>
1019 size_t qfind(const Range<T>& haystack,
1020 const Range<T>& needle,
1022 // Don't use std::search, use a Boyer-Moore-like trick by comparing
1023 // the last characters first
1024 auto const nsize = needle.size();
1025 if (haystack.size() < nsize) {
1026 return std::string::npos;
1028 if (!nsize) return 0;
1029 auto const nsize_1 = nsize - 1;
1030 auto const lastNeedle = needle[nsize_1];
1032 // Boyer-Moore skip value for the last char in the needle. Zero is
1033 // not a valid value; skip will be computed the first time it's
1035 std::string::size_type skip = 0;
1037 auto i = haystack.begin();
1038 auto iEnd = haystack.end() - nsize_1;
1041 // Boyer-Moore: match the last element in the needle
1042 while (!eq(i[nsize_1], lastNeedle)) {
1045 return std::string::npos;
1048 // Here we know that the last char matches
1049 // Continue in pedestrian mode
1050 for (size_t j = 0; ; ) {
1052 if (!eq(i[j], needle[j])) {
1053 // Not found, we can skip
1054 // Compute the skip value lazily
1057 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
1064 // Check if done searching
1067 return size_t(i - haystack.begin());
1071 return std::string::npos;
1076 inline size_t qfind_first_byte_of(const StringPiece haystack,
1077 const StringPiece needles) {
1078 static auto const qfind_first_byte_of_fn =
1079 folly::CpuId().sse42() ? qfind_first_byte_of_sse42
1080 : qfind_first_byte_of_nosse;
1081 return qfind_first_byte_of_fn(haystack, needles);
1084 } // namespace detail
1086 template <class T, class Comp>
1087 size_t qfind_first_of(const Range<T> & haystack,
1088 const Range<T> & needles,
1090 auto ret = std::find_first_of(haystack.begin(), haystack.end(),
1091 needles.begin(), needles.end(),
1093 return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
1096 struct AsciiCaseSensitive {
1097 bool operator()(char lhs, char rhs) const {
1103 * Check if two ascii characters are case insensitive equal.
1104 * The difference between the lower/upper case characters are the 6-th bit.
1105 * We also check they are alpha chars, in case of xor = 32.
1107 struct AsciiCaseInsensitive {
1108 bool operator()(char lhs, char rhs) const {
1110 if (k == 0) return true;
1111 if (k != 32) return false;
1113 return (k >= 'a' && k <= 'z');
1118 size_t qfind(const Range<T>& haystack,
1119 const typename Range<T>::value_type& needle) {
1120 auto pos = std::find(haystack.begin(), haystack.end(), needle);
1121 return pos == haystack.end() ? std::string::npos : pos - haystack.data();
1125 size_t rfind(const Range<T>& haystack,
1126 const typename Range<T>::value_type& needle) {
1127 for (auto i = haystack.size(); i-- > 0; ) {
1128 if (haystack[i] == needle) {
1132 return std::string::npos;
1135 // specialization for StringPiece
1137 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
1138 // memchr expects a not-null pointer, early return if the range is empty.
1139 if (haystack.empty()) {
1140 return std::string::npos;
1142 auto pos = static_cast<const char*>(
1143 ::memchr(haystack.data(), needle, haystack.size()));
1144 return pos == nullptr ? std::string::npos : pos - haystack.data();
1148 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
1149 // memchr expects a not-null pointer, early return if the range is empty.
1150 if (haystack.empty()) {
1151 return std::string::npos;
1153 auto pos = static_cast<const char*>(
1154 ::memrchr(haystack.data(), needle, haystack.size()));
1155 return pos == nullptr ? std::string::npos : pos - haystack.data();
1158 // specialization for ByteRange
1160 inline size_t qfind(const Range<const unsigned char*>& haystack,
1161 const unsigned char& needle) {
1162 // memchr expects a not-null pointer, early return if the range is empty.
1163 if (haystack.empty()) {
1164 return std::string::npos;
1166 auto pos = static_cast<const unsigned char*>(
1167 ::memchr(haystack.data(), needle, haystack.size()));
1168 return pos == nullptr ? std::string::npos : pos - haystack.data();
1172 inline size_t rfind(const Range<const unsigned char*>& haystack,
1173 const unsigned char& needle) {
1174 // memchr expects a not-null pointer, early return if the range is empty.
1175 if (haystack.empty()) {
1176 return std::string::npos;
1178 auto pos = static_cast<const unsigned char*>(
1179 ::memrchr(haystack.data(), needle, haystack.size()));
1180 return pos == nullptr ? std::string::npos : pos - haystack.data();
1184 size_t qfind_first_of(const Range<T>& haystack,
1185 const Range<T>& needles) {
1186 return qfind_first_of(haystack, needles, AsciiCaseSensitive());
1189 // specialization for StringPiece
1191 inline size_t qfind_first_of(const Range<const char*>& haystack,
1192 const Range<const char*>& needles) {
1193 return detail::qfind_first_byte_of(haystack, needles);
1196 // specialization for ByteRange
1198 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
1199 const Range<const unsigned char*>& needles) {
1200 return detail::qfind_first_byte_of(StringPiece(haystack),
1201 StringPiece(needles));
1204 template<class Key, class Enable>
1208 struct hasher<folly::Range<T*>,
1209 typename std::enable_if<std::is_pod<T>::value, void>::type> {
1210 size_t operator()(folly::Range<T*> r) const {
1211 return hash::SpookyHashV2::Hash64(r.begin(), r.size() * sizeof(T), 0);
1216 * Ubiquitous helper template for knowing what's a string
1218 template <class T> struct IsSomeString {
1219 enum { value = std::is_same<T, std::string>::value
1220 || std::is_same<T, fbstring>::value };
1223 } // !namespace folly
1225 #pragma GCC diagnostic pop
1227 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);