2 * Copyright 2016 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 typedef typename std::iterator_traits<Iter>::reference reference;
174 * For MutableStringPiece and MutableByteRange we define StringPiece
175 * and ByteRange as const_range_type (for everything else its just
176 * identity). We do that to enable operations such as find with
177 * args which are const.
179 typedef typename std::conditional<
180 std::is_same<Iter, char*>::value
181 || std::is_same<Iter, unsigned char*>::value,
182 Range<const value_type*>,
183 Range<Iter>>::type const_range_type;
185 typedef std::char_traits<typename std::remove_const<value_type>::type>
188 static const size_type npos;
190 // Works for all iterators
191 constexpr Range() : b_(), e_() {
194 constexpr Range(const Range&) = default;
195 constexpr Range(Range&&) = default;
198 // Works for all iterators
199 constexpr Range(Iter start, Iter end) : b_(start), e_(end) {
202 // Works only for random-access iterators
203 constexpr Range(Iter start, size_t size)
204 : b_(start), e_(start + size) { }
206 # if !__clang__ || __CLANG_PREREQ(3, 7) // Clang 3.6 crashes on this line
207 /* implicit */ Range(std::nullptr_t) = delete;
210 template <class T = Iter, typename detail::IsCharPointer<T>::type = 0>
211 constexpr /* implicit */ Range(Iter str)
212 : b_(str), e_(str + constexpr_strlen(str)) {}
214 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
215 /* implicit */ Range(const std::string& str)
216 : b_(str.data()), e_(b_ + str.size()) {}
218 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
219 Range(const std::string& str, std::string::size_type startFrom) {
220 if (UNLIKELY(startFrom > str.size())) {
221 std::__throw_out_of_range("index out of range");
223 b_ = str.data() + startFrom;
224 e_ = str.data() + str.size();
227 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
228 Range(const std::string& str,
229 std::string::size_type startFrom,
230 std::string::size_type size) {
231 if (UNLIKELY(startFrom > str.size())) {
232 std::__throw_out_of_range("index out of range");
234 b_ = str.data() + startFrom;
235 if (str.size() - startFrom < size) {
236 e_ = str.data() + str.size();
242 Range(const Range& other,
244 size_type length = npos)
245 : Range(other.subpiece(first, length))
248 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
249 /* implicit */ Range(const fbstring& str)
250 : b_(str.data()), e_(b_ + str.size()) { }
252 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
253 Range(const fbstring& str, fbstring::size_type startFrom) {
254 if (UNLIKELY(startFrom > str.size())) {
255 std::__throw_out_of_range("index out of range");
257 b_ = str.data() + startFrom;
258 e_ = str.data() + str.size();
261 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
262 Range(const fbstring& str, fbstring::size_type startFrom,
263 fbstring::size_type size) {
264 if (UNLIKELY(startFrom > str.size())) {
265 std::__throw_out_of_range("index out of range");
267 b_ = str.data() + startFrom;
268 if (str.size() - startFrom < size) {
269 e_ = str.data() + str.size();
275 // Allow implicit conversion from Range<const char*> (aka StringPiece) to
276 // Range<const unsigned char*> (aka ByteRange), as they're both frequently
277 // used to represent ranges of bytes. Allow explicit conversion in the other
279 template <class OtherIter, typename std::enable_if<
280 (std::is_same<Iter, const unsigned char*>::value &&
281 (std::is_same<OtherIter, const char*>::value ||
282 std::is_same<OtherIter, char*>::value)), int>::type = 0>
283 /* implicit */ Range(const Range<OtherIter>& other)
284 : b_(reinterpret_cast<const unsigned char*>(other.begin())),
285 e_(reinterpret_cast<const unsigned char*>(other.end())) {
288 template <class OtherIter, typename std::enable_if<
289 (std::is_same<Iter, unsigned char*>::value &&
290 std::is_same<OtherIter, char*>::value), int>::type = 0>
291 /* implicit */ Range(const Range<OtherIter>& other)
292 : b_(reinterpret_cast<unsigned char*>(other.begin())),
293 e_(reinterpret_cast<unsigned char*>(other.end())) {
296 template <class OtherIter, typename std::enable_if<
297 (std::is_same<Iter, const char*>::value &&
298 (std::is_same<OtherIter, const unsigned char*>::value ||
299 std::is_same<OtherIter, unsigned char*>::value)), int>::type = 0>
300 explicit Range(const Range<OtherIter>& other)
301 : b_(reinterpret_cast<const char*>(other.begin())),
302 e_(reinterpret_cast<const char*>(other.end())) {
305 template <class OtherIter, typename std::enable_if<
306 (std::is_same<Iter, char*>::value &&
307 std::is_same<OtherIter, unsigned char*>::value), int>::type = 0>
308 explicit Range(const Range<OtherIter>& other)
309 : b_(reinterpret_cast<char*>(other.begin())),
310 e_(reinterpret_cast<char*>(other.end())) {
313 // Allow implicit conversion from Range<From> to Range<To> if From is
314 // implicitly convertible to To.
315 template <class OtherIter, typename std::enable_if<
316 (!std::is_same<Iter, OtherIter>::value &&
317 std::is_convertible<OtherIter, Iter>::value), int>::type = 0>
318 constexpr /* implicit */ Range(const Range<OtherIter>& other)
323 // Allow explicit conversion from Range<From> to Range<To> if From is
324 // explicitly convertible to To.
325 template <class OtherIter, typename std::enable_if<
326 (!std::is_same<Iter, OtherIter>::value &&
327 !std::is_convertible<OtherIter, Iter>::value &&
328 std::is_constructible<Iter, const OtherIter&>::value), int>::type = 0>
329 constexpr explicit Range(const Range<OtherIter>& other)
334 Range& operator=(const Range& rhs) & = default;
335 Range& operator=(Range&& rhs) & = default;
342 void assign(Iter start, Iter end) {
347 void reset(Iter start, size_type size) {
352 // Works only for Range<const char*>
353 void reset(const std::string& str) {
354 reset(str.data(), str.size());
357 constexpr size_type size() const {
358 // It would be nice to assert(b_ <= e_) here. This can be achieved even
359 // in a C++11 compatible constexpr function:
360 // http://ericniebler.com/2014/09/27/assert-and-constexpr-in-cxx11/
361 // Unfortunately current gcc versions have a bug causing it to reject
362 // this check in a constexpr function:
363 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=71448
366 constexpr size_type walk_size() const {
367 return std::distance(b_, e_);
369 constexpr bool empty() const {
372 constexpr Iter data() const {
375 constexpr Iter start() const {
378 constexpr Iter begin() const {
381 constexpr Iter end() const {
384 constexpr Iter cbegin() const {
387 constexpr Iter cend() const {
390 value_type& front() {
396 return detail::value_before(e_);
398 const value_type& front() const {
402 const value_type& back() const {
404 return detail::value_before(e_);
406 // Works only for Range<const char*> and Range<char*>
407 std::string str() const { return std::string(b_, size()); }
408 std::string toString() const { return str(); }
409 // Works only for Range<const char*> and Range<char*>
410 fbstring fbstr() const { return fbstring(b_, size()); }
411 fbstring toFbstring() const { return fbstr(); }
413 const_range_type castToConst() const {
414 return const_range_type(*this);
417 // Works only for Range<const char*> and Range<char*>
418 int compare(const const_range_type& o) const {
419 const size_type tsize = this->size();
420 const size_type osize = o.size();
421 const size_type msize = std::min(tsize, osize);
422 int r = traits_type::compare(data(), o.data(), msize);
423 if (r == 0 && tsize != osize) {
424 // We check the signed bit of the subtraction and bit shift it
425 // to produce either 0 or 2. The subtraction yields the
426 // comparison values of either -1 or 1.
427 r = (static_cast<int>(
428 (osize - tsize) >> (CHAR_BIT * sizeof(size_t) - 1)) << 1) - 1;
433 value_type& operator[](size_t i) {
434 DCHECK_GT(size(), i);
438 const value_type& operator[](size_t i) const {
439 DCHECK_GT(size(), i);
443 value_type& at(size_t i) {
444 if (i >= size()) std::__throw_out_of_range("index out of range");
448 const value_type& at(size_t i) const {
449 if (i >= size()) std::__throw_out_of_range("index out of range");
453 // Do NOT use this function, which was left behind for backwards
454 // compatibility. Use SpookyHashV2 instead -- it is faster, and produces
455 // a 64-bit hash, which means dramatically fewer collisions in large maps.
456 // (The above advice does not apply if you are targeting a 32-bit system.)
458 // Works only for Range<const char*> and Range<char*>
461 // ** WANT TO GET RID OF THIS LINT? **
463 // A) Use a better hash function (*cough*folly::Hash*cough*), but
464 // only if you don't serialize data in a format that depends on
465 // this formula (ie the writer and reader assume this exact hash
466 // function is used).
468 // B) If you have to use this exact function then make your own hasher
469 // object and copy the body over (see thrift example: D3972362).
470 // https://github.com/facebook/fbthrift/commit/f8ed502e24ab4a32a9d5f266580
471 FOLLY_DEPRECATED("Replace with folly::Hash if the hash is not serialized")
472 uint32_t hash() const {
473 // Taken from fbi/nstring.h:
474 // Quick and dirty bernstein hash...fine for short ascii strings
475 uint32_t hash = 5381;
476 for (size_t ix = 0; ix < size(); ix++) {
477 hash = ((hash << 5) + hash) + b_[ix];
482 void advance(size_type n) {
483 if (UNLIKELY(n > size())) {
484 std::__throw_out_of_range("index out of range");
489 void subtract(size_type n) {
490 if (UNLIKELY(n > size())) {
491 std::__throw_out_of_range("index out of range");
496 Range subpiece(size_type first, size_type length = npos) const {
497 if (UNLIKELY(first > size())) {
498 std::__throw_out_of_range("index out of range");
501 return Range(b_ + first, std::min(length, size() - first));
504 // unchecked versions
505 void uncheckedAdvance(size_type n) {
506 DCHECK_LE(n, size());
510 void uncheckedSubtract(size_type n) {
511 DCHECK_LE(n, size());
515 Range uncheckedSubpiece(size_type first, size_type length = npos) const {
516 DCHECK_LE(first, size());
517 return Range(b_ + first, std::min(length, size() - first));
530 // string work-alike functions
531 size_type find(const_range_type str) const {
532 return qfind(castToConst(), str);
535 size_type find(const_range_type str, size_t pos) const {
536 if (pos > size()) return std::string::npos;
537 size_t ret = qfind(castToConst().subpiece(pos), str);
538 return ret == npos ? ret : ret + pos;
541 size_type find(Iter s, size_t pos, size_t n) const {
542 if (pos > size()) return std::string::npos;
543 auto forFinding = castToConst();
545 pos ? forFinding.subpiece(pos) : forFinding, const_range_type(s, n));
546 return ret == npos ? ret : ret + pos;
549 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
550 size_type find(const Iter s) const {
551 return qfind(castToConst(), const_range_type(s));
554 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
555 size_type find(const Iter s, size_t pos) const {
556 if (pos > size()) return std::string::npos;
557 size_type ret = qfind(castToConst().subpiece(pos), const_range_type(s));
558 return ret == npos ? ret : ret + pos;
561 size_type find(value_type c) const {
562 return qfind(castToConst(), c);
565 size_type rfind(value_type c) const {
566 return folly::rfind(castToConst(), c);
569 size_type find(value_type c, size_t pos) const {
570 if (pos > size()) return std::string::npos;
571 size_type ret = qfind(castToConst().subpiece(pos), c);
572 return ret == npos ? ret : ret + pos;
575 size_type find_first_of(const_range_type needles) const {
576 return qfind_first_of(castToConst(), needles);
579 size_type find_first_of(const_range_type needles, size_t pos) const {
580 if (pos > size()) return std::string::npos;
581 size_type ret = qfind_first_of(castToConst().subpiece(pos), needles);
582 return ret == npos ? ret : ret + pos;
585 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
586 size_type find_first_of(Iter needles) const {
587 return find_first_of(const_range_type(needles));
590 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
591 size_type find_first_of(Iter needles, size_t pos) const {
592 return find_first_of(const_range_type(needles), pos);
595 size_type find_first_of(Iter needles, size_t pos, size_t n) const {
596 return find_first_of(const_range_type(needles, n), pos);
599 size_type find_first_of(value_type c) const {
603 size_type find_first_of(value_type c, size_t pos) const {
608 * Determine whether the range contains the given subrange or item.
610 * Note: Call find() directly if the index is needed.
612 bool contains(const const_range_type& other) const {
613 return find(other) != std::string::npos;
616 bool contains(const value_type& other) const {
617 return find(other) != std::string::npos;
620 void swap(Range& rhs) {
621 std::swap(b_, rhs.b_);
622 std::swap(e_, rhs.e_);
626 * Does this Range start with another range?
628 bool startsWith(const const_range_type& other) const {
629 return size() >= other.size()
630 && castToConst().subpiece(0, other.size()) == other;
632 bool startsWith(value_type c) const {
633 return !empty() && front() == c;
637 * Does this Range end with another range?
639 bool endsWith(const const_range_type& other) const {
640 return size() >= other.size()
641 && castToConst().subpiece(size() - other.size()) == other;
643 bool endsWith(value_type c) const {
644 return !empty() && back() == c;
648 * Remove the items in [b, e), as long as this subrange is at the beginning
649 * or end of the Range.
651 * Required for boost::algorithm::trim()
653 void erase(Iter b, Iter e) {
656 } else if (e == e_) {
659 std::__throw_out_of_range("index out of range");
664 * Remove the given prefix and return true if the range starts with the given
665 * prefix; return false otherwise.
667 bool removePrefix(const const_range_type& prefix) {
668 return startsWith(prefix) && (b_ += prefix.size(), true);
670 bool removePrefix(value_type prefix) {
671 return startsWith(prefix) && (++b_, true);
675 * Remove the given suffix and return true if the range ends with the given
676 * suffix; return false otherwise.
678 bool removeSuffix(const const_range_type& suffix) {
679 return endsWith(suffix) && (e_ -= suffix.size(), true);
681 bool removeSuffix(value_type suffix) {
682 return endsWith(suffix) && (--e_, true);
686 * Replaces the content of the range, starting at position 'pos', with
687 * contents of 'replacement'. Entire 'replacement' must fit into the
688 * range. Returns false if 'replacements' does not fit. Example use:
690 * char in[] = "buffer";
691 * auto msp = MutablesStringPiece(input);
692 * EXPECT_TRUE(msp.replaceAt(2, "tt"));
693 * EXPECT_EQ(msp, "butter");
695 * // not enough space
696 * EXPECT_FALSE(msp.replace(msp.size() - 1, "rr"));
697 * EXPECT_EQ(msp, "butter"); // unchanged
699 bool replaceAt(size_t pos, const_range_type replacement) {
700 if (size() < pos + replacement.size()) {
704 std::copy(replacement.begin(), replacement.end(), begin() + pos);
710 * Replaces all occurences of 'source' with 'dest'. Returns number
711 * of replacements made. Source and dest have to have the same
712 * length. Throws if the lengths are different. If 'source' is a
713 * pattern that is overlapping with itself, we perform sequential
714 * replacement: "aaaaaaa".replaceAll("aa", "ba") --> "bababaa"
718 * char in[] = "buffer";
719 * auto msp = MutablesStringPiece(input);
720 * EXPECT_EQ(msp.replaceAll("ff","tt"), 1);
721 * EXPECT_EQ(msp, "butter");
723 size_t replaceAll(const_range_type source, const_range_type dest) {
724 if (source.size() != dest.size()) {
725 throw std::invalid_argument(
726 "replacement must have the same size as source");
734 size_t num_replaced = 0;
735 size_type found = std::string::npos;
736 while ((found = find(source, pos)) != std::string::npos) {
737 replaceAt(found, dest);
738 pos += source.size();
746 * Splits this `Range` `[b, e)` in the position `i` dictated by the next
747 * occurence of `delimiter`.
749 * Returns a new `Range` `[b, i)` and adjusts this range to start right after
750 * the delimiter's position. This range will be empty if the delimiter is not
751 * found. If called on an empty `Range`, both this and the returned `Range`
756 * folly::StringPiece s("sample string for split_next");
757 * auto p = s.split_step(' ');
759 * // prints "string for split_next"
767 * void tokenize(StringPiece s, char delimiter) {
768 * while (!s.empty()) {
769 * cout << s.split_step(delimiter);
773 * @author: Marcelo Juchem <marcelo@fb.com>
775 Range split_step(value_type delimiter) {
776 auto i = std::find(b_, e_, delimiter);
779 b_ = i == e_ ? e_ : std::next(i);
784 Range split_step(Range delimiter) {
785 auto i = find(delimiter);
786 Range result(b_, i == std::string::npos ? size() : i);
788 b_ = result.end() == e_ ? e_ : std::next(result.end(), delimiter.size());
794 * Convenience method that calls `split_step()` and passes the result to a
795 * functor, returning whatever the functor does. Any additional arguments
796 * `args` passed to this function are perfectly forwarded to the functor.
798 * Say you have a functor with this signature:
800 * Foo fn(Range r) { }
802 * `split_step()`'s return type will be `Foo`. It works just like:
804 * auto result = fn(myRange.split_step(' '));
806 * A functor returning `void` is also supported.
810 * void do_some_parsing(folly::StringPiece s) {
811 * auto version = s.split_step(' ', [&](folly::StringPiece x) {
813 * throw std::invalid_argument("empty string");
815 * return std::strtoull(x.begin(), x.end(), 16);
822 * void parse(folly::StringPiece s) {
823 * s.split_step(' ', parse_field, bar, 10);
824 * s.split_step('\t', parse_field, baz, 20);
826 * auto const kludge = [](folly::StringPiece x, int &out, int def) {
830 * parse_field(x, out, def);
834 * s.split_step('\t', kludge, gaz);
835 * s.split_step(' ', kludge, foo);
844 * static parse_field(folly::StringPiece s, int &out, int def) {
846 * out = folly::to<int>(s);
847 * } catch (std::exception const &) {
853 * @author: Marcelo Juchem <marcelo@fb.com>
855 template <typename TProcess, typename... Args>
856 auto split_step(value_type delimiter, TProcess &&process, Args &&...args)
857 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
858 { return process(split_step(delimiter), std::forward<Args>(args)...); }
860 template <typename TProcess, typename... Args>
861 auto split_step(Range delimiter, TProcess &&process, Args &&...args)
862 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
863 { return process(split_step(delimiter), std::forward<Args>(args)...); }
869 template <class Iter>
870 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
873 void swap(Range<T>& lhs, Range<T>& rhs) {
878 * Create a range from two iterators, with type deduction.
880 template <class Iter>
881 constexpr Range<Iter> range(Iter first, Iter last) {
882 return Range<Iter>(first, last);
886 * Creates a range to reference the contents of a contiguous-storage container.
888 // Use pointers for types with '.data()' member
891 class T = typename std::remove_pointer<
892 decltype(std::declval<Collection>().data())>::type>
893 constexpr Range<T*> range(Collection&& v) {
894 return Range<T*>(v.data(), v.data() + v.size());
897 template <class T, size_t n>
898 constexpr Range<T*> range(T (&array)[n]) {
899 return Range<T*>(array, array + n);
902 template <class T, size_t n>
903 constexpr Range<const T*> range(const std::array<T, n>& array) {
904 using r = Range<const T*>;
905 return array.empty() ? r{} : r(&array.at(0), &array.at(0) + n);
908 typedef Range<const char*> StringPiece;
909 typedef Range<char*> MutableStringPiece;
910 typedef Range<const unsigned char*> ByteRange;
911 typedef Range<unsigned char*> MutableByteRange;
913 inline std::ostream& operator<<(std::ostream& os,
914 const StringPiece piece) {
915 os.write(piece.start(), piece.size());
919 inline std::ostream& operator<<(std::ostream& os,
920 const MutableStringPiece piece) {
921 os.write(piece.start(), piece.size());
926 * Templated comparison operators
930 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
931 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
935 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
936 return lhs.compare(rhs) < 0;
940 * Specializations of comparison operators for StringPiece
945 template <class A, class B>
946 struct ComparableAsStringPiece {
949 (std::is_convertible<A, StringPiece>::value
950 && std::is_same<B, StringPiece>::value)
952 (std::is_convertible<B, StringPiece>::value
953 && std::is_same<A, StringPiece>::value)
957 } // namespace detail
960 * operator== through conversion for Range<const char*>
962 template <class T, class U>
964 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
965 operator==(const T& lhs, const U& rhs) {
966 return StringPiece(lhs) == StringPiece(rhs);
970 * operator< through conversion for Range<const char*>
972 template <class T, class U>
974 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
975 operator<(const T& lhs, const U& rhs) {
976 return StringPiece(lhs) < StringPiece(rhs);
980 * operator> through conversion for Range<const char*>
982 template <class T, class U>
984 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
985 operator>(const T& lhs, const U& rhs) {
986 return StringPiece(lhs) > StringPiece(rhs);
990 * operator< through conversion for Range<const char*>
992 template <class T, class U>
994 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
995 operator<=(const T& lhs, const U& rhs) {
996 return StringPiece(lhs) <= StringPiece(rhs);
1000 * operator> through conversion for Range<const char*>
1002 template <class T, class U>
1004 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
1005 operator>=(const T& lhs, const U& rhs) {
1006 return StringPiece(lhs) >= StringPiece(rhs);
1010 * Finds substrings faster than brute force by borrowing from Boyer-Moore
1012 template <class T, class Comp>
1013 size_t qfind(const Range<T>& haystack,
1014 const Range<T>& needle,
1016 // Don't use std::search, use a Boyer-Moore-like trick by comparing
1017 // the last characters first
1018 auto const nsize = needle.size();
1019 if (haystack.size() < nsize) {
1020 return std::string::npos;
1022 if (!nsize) return 0;
1023 auto const nsize_1 = nsize - 1;
1024 auto const lastNeedle = needle[nsize_1];
1026 // Boyer-Moore skip value for the last char in the needle. Zero is
1027 // not a valid value; skip will be computed the first time it's
1029 std::string::size_type skip = 0;
1031 auto i = haystack.begin();
1032 auto iEnd = haystack.end() - nsize_1;
1035 // Boyer-Moore: match the last element in the needle
1036 while (!eq(i[nsize_1], lastNeedle)) {
1039 return std::string::npos;
1042 // Here we know that the last char matches
1043 // Continue in pedestrian mode
1044 for (size_t j = 0; ; ) {
1046 if (!eq(i[j], needle[j])) {
1047 // Not found, we can skip
1048 // Compute the skip value lazily
1051 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
1058 // Check if done searching
1061 return i - haystack.begin();
1065 return std::string::npos;
1070 inline size_t qfind_first_byte_of(const StringPiece haystack,
1071 const StringPiece needles) {
1072 static auto const qfind_first_byte_of_fn =
1073 folly::CpuId().sse42() ? qfind_first_byte_of_sse42
1074 : qfind_first_byte_of_nosse;
1075 return qfind_first_byte_of_fn(haystack, needles);
1078 } // namespace detail
1080 template <class T, class Comp>
1081 size_t qfind_first_of(const Range<T> & haystack,
1082 const Range<T> & needles,
1084 auto ret = std::find_first_of(haystack.begin(), haystack.end(),
1085 needles.begin(), needles.end(),
1087 return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
1090 struct AsciiCaseSensitive {
1091 bool operator()(char lhs, char rhs) const {
1097 * Check if two ascii characters are case insensitive equal.
1098 * The difference between the lower/upper case characters are the 6-th bit.
1099 * We also check they are alpha chars, in case of xor = 32.
1101 struct AsciiCaseInsensitive {
1102 bool operator()(char lhs, char rhs) const {
1104 if (k == 0) return true;
1105 if (k != 32) return false;
1107 return (k >= 'a' && k <= 'z');
1112 size_t qfind(const Range<T>& haystack,
1113 const typename Range<T>::value_type& needle) {
1114 auto pos = std::find(haystack.begin(), haystack.end(), needle);
1115 return pos == haystack.end() ? std::string::npos : pos - haystack.data();
1119 size_t rfind(const Range<T>& haystack,
1120 const typename Range<T>::value_type& needle) {
1121 for (auto i = haystack.size(); i-- > 0; ) {
1122 if (haystack[i] == needle) {
1126 return std::string::npos;
1129 // specialization for StringPiece
1131 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
1132 // memchr expects a not-null pointer, early return if the range is empty.
1133 if (haystack.empty()) {
1134 return std::string::npos;
1136 auto pos = static_cast<const char*>(
1137 ::memchr(haystack.data(), needle, haystack.size()));
1138 return pos == nullptr ? std::string::npos : pos - haystack.data();
1142 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
1143 // memchr expects a not-null pointer, early return if the range is empty.
1144 if (haystack.empty()) {
1145 return std::string::npos;
1147 auto pos = static_cast<const char*>(
1148 ::memrchr(haystack.data(), needle, haystack.size()));
1149 return pos == nullptr ? std::string::npos : pos - haystack.data();
1152 // specialization for ByteRange
1154 inline size_t qfind(const Range<const unsigned char*>& haystack,
1155 const unsigned char& needle) {
1156 // memchr expects a not-null pointer, early return if the range is empty.
1157 if (haystack.empty()) {
1158 return std::string::npos;
1160 auto pos = static_cast<const unsigned char*>(
1161 ::memchr(haystack.data(), needle, haystack.size()));
1162 return pos == nullptr ? std::string::npos : pos - haystack.data();
1166 inline size_t rfind(const Range<const unsigned char*>& haystack,
1167 const unsigned char& needle) {
1168 // memchr expects a not-null pointer, early return if the range is empty.
1169 if (haystack.empty()) {
1170 return std::string::npos;
1172 auto pos = static_cast<const unsigned char*>(
1173 ::memrchr(haystack.data(), needle, haystack.size()));
1174 return pos == nullptr ? std::string::npos : pos - haystack.data();
1178 size_t qfind_first_of(const Range<T>& haystack,
1179 const Range<T>& needles) {
1180 return qfind_first_of(haystack, needles, AsciiCaseSensitive());
1183 // specialization for StringPiece
1185 inline size_t qfind_first_of(const Range<const char*>& haystack,
1186 const Range<const char*>& needles) {
1187 return detail::qfind_first_byte_of(haystack, needles);
1190 // specialization for ByteRange
1192 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
1193 const Range<const unsigned char*>& needles) {
1194 return detail::qfind_first_byte_of(StringPiece(haystack),
1195 StringPiece(needles));
1198 template<class Key, class Enable>
1202 struct hasher<folly::Range<T*>,
1203 typename std::enable_if<std::is_pod<T>::value, void>::type> {
1204 size_t operator()(folly::Range<T*> r) const {
1205 return hash::SpookyHashV2::Hash64(r.begin(), r.size() * sizeof(T), 0);
1210 * Ubiquitous helper template for knowing what's a string
1212 template <class T> struct IsSomeString {
1213 enum { value = std::is_same<T, std::string>::value
1214 || std::is_same<T, fbstring>::value };
1217 } // !namespace folly
1219 #pragma GCC diagnostic pop
1221 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);