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/Constexpr.h>
26 #include <folly/portability/String.h>
29 #include <boost/operators.hpp>
33 #include <glog/logging.h>
37 #include <type_traits>
39 // libc++ doesn't provide this header, nor does msvc
40 #ifdef FOLLY_HAVE_BITS_CXXCONFIG_H
41 // This file appears in two locations: inside fbcode and in the
42 // libstdc++ source code (when embedding fbstring as std::string).
43 // To aid in this schizophrenic use, two macros are defined in
45 // _LIBSTDCXX_FBSTRING - Set inside libstdc++. This is useful to
46 // gate use inside fbcode v. libstdc++
47 #include <bits/c++config.h>
50 #include <folly/CpuId.h>
51 #include <folly/Traits.h>
52 #include <folly/Likely.h>
53 #include <folly/detail/RangeCommon.h>
54 #include <folly/detail/RangeSse42.h>
56 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
57 #pragma GCC diagnostic push
58 #pragma GCC diagnostic ignored "-Wshadow"
62 template <class T> class Range;
65 * Finds the first occurrence of needle in haystack. The algorithm is on
66 * average faster than O(haystack.size() * needle.size()) but not as fast
67 * as Boyer-Moore. On the upside, it does not do any upfront
68 * preprocessing and does not allocate memory.
70 template <class T, class Comp = std::equal_to<typename Range<T>::value_type>>
71 inline size_t qfind(const Range<T> & haystack,
72 const Range<T> & needle,
76 * Finds the first occurrence of needle in haystack. The result is the
77 * offset reported to the beginning of haystack, or string::npos if
78 * needle wasn't found.
81 size_t qfind(const Range<T> & haystack,
82 const typename Range<T>::value_type& needle);
85 * Finds the last occurrence of needle in haystack. The result is the
86 * offset reported to the beginning of haystack, or string::npos if
87 * needle wasn't found.
90 size_t rfind(const Range<T> & haystack,
91 const typename Range<T>::value_type& needle);
95 * Finds the first occurrence of any element of needle in
96 * haystack. The algorithm is O(haystack.size() * needle.size()).
99 inline size_t qfind_first_of(const Range<T> & haystack,
100 const Range<T> & needle);
103 * Small internal helper - returns the value just before an iterator.
108 * For random-access iterators, the value before is simply i[-1].
110 template <class Iter>
111 typename std::enable_if<
112 std::is_same<typename std::iterator_traits<Iter>::iterator_category,
113 std::random_access_iterator_tag>::value,
114 typename std::iterator_traits<Iter>::reference>::type
115 value_before(Iter i) {
120 * For all other iterators, we need to use the decrement operator.
122 template <class Iter>
123 typename std::enable_if<
124 !std::is_same<typename std::iterator_traits<Iter>::iterator_category,
125 std::random_access_iterator_tag>::value,
126 typename std::iterator_traits<Iter>::reference>::type
127 value_before(Iter i) {
132 * Use IsCharPointer<T>::type to enable const char* or char*.
133 * Use IsCharPointer<T>::const_type to enable only const char*.
135 template <class T> struct IsCharPointer {};
138 struct IsCharPointer<char*> {
143 struct IsCharPointer<const char*> {
144 typedef int const_type;
148 // Prevent it from being inlined to reduce instruction bloat.
149 FOLLY_NOINLINE inline void throwOutOfRange() {
150 throw std::out_of_range("index out of range");
153 } // namespace detail
156 * Range abstraction keeping a pair of iterators. We couldn't use
157 * boost's similar range abstraction because we need an API identical
158 * with the former StringPiece class, which is used by a lot of other
159 * code. This abstraction does fulfill the needs of boost's
160 * range-oriented algorithms though.
162 * (Keep memory lifetime in mind when using this class, since it
163 * doesn't manage the data it refers to - just like an iterator
166 template <class Iter>
167 class Range : private boost::totally_ordered<Range<Iter> > {
169 typedef std::size_t size_type;
170 typedef Iter iterator;
171 typedef Iter const_iterator;
172 typedef typename std::remove_reference<
173 typename std::iterator_traits<Iter>::reference>::type
175 typedef typename std::iterator_traits<Iter>::reference reference;
178 * For MutableStringPiece and MutableByteRange we define StringPiece
179 * and ByteRange as const_range_type (for everything else its just
180 * identity). We do that to enable operations such as find with
181 * args which are const.
183 typedef typename std::conditional<
184 std::is_same<Iter, char*>::value
185 || std::is_same<Iter, unsigned char*>::value,
186 Range<const value_type*>,
187 Range<Iter>>::type const_range_type;
189 typedef std::char_traits<typename std::remove_const<value_type>::type>
192 static const size_type npos;
194 // Works for all iterators
195 constexpr Range() : b_(), e_() {
198 constexpr Range(const Range&) = default;
199 constexpr Range(Range&&) = default;
202 // Works for all iterators
203 constexpr Range(Iter start, Iter end) : b_(start), e_(end) {
206 // Works only for random-access iterators
207 constexpr Range(Iter start, size_t size)
208 : b_(start), e_(start + size) { }
210 # if !__clang__ || __CLANG_PREREQ(3, 7) // Clang 3.6 crashes on this line
211 /* implicit */ Range(std::nullptr_t) = delete;
214 template <class T = Iter, typename detail::IsCharPointer<T>::type = 0>
215 constexpr /* implicit */ Range(Iter str)
216 : b_(str), e_(str + constexpr_strlen(str)) {}
218 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
219 /* implicit */ Range(const std::string& str)
220 : b_(str.data()), e_(b_ + str.size()) {}
222 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
223 Range(const std::string& str, std::string::size_type startFrom) {
224 if (UNLIKELY(startFrom > str.size())) {
225 detail::throwOutOfRange();
227 b_ = str.data() + startFrom;
228 e_ = str.data() + str.size();
231 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
232 Range(const std::string& str,
233 std::string::size_type startFrom,
234 std::string::size_type size) {
235 if (UNLIKELY(startFrom > str.size())) {
236 detail::throwOutOfRange();
238 b_ = str.data() + startFrom;
239 if (str.size() - startFrom < size) {
240 e_ = str.data() + str.size();
246 Range(const Range& other,
248 size_type length = npos)
249 : Range(other.subpiece(first, length))
252 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
253 /* implicit */ Range(const fbstring& str)
254 : b_(str.data()), e_(b_ + str.size()) { }
256 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
257 Range(const fbstring& str, fbstring::size_type startFrom) {
258 if (UNLIKELY(startFrom > str.size())) {
259 detail::throwOutOfRange();
261 b_ = str.data() + startFrom;
262 e_ = str.data() + str.size();
265 template <class T = Iter, typename detail::IsCharPointer<T>::const_type = 0>
266 Range(const fbstring& str, fbstring::size_type startFrom,
267 fbstring::size_type size) {
268 if (UNLIKELY(startFrom > str.size())) {
269 detail::throwOutOfRange();
271 b_ = str.data() + startFrom;
272 if (str.size() - startFrom < size) {
273 e_ = str.data() + str.size();
279 // Allow implicit conversion from Range<const char*> (aka StringPiece) to
280 // Range<const unsigned char*> (aka ByteRange), as they're both frequently
281 // used to represent ranges of bytes. Allow explicit conversion in the other
283 template <class OtherIter, typename std::enable_if<
284 (std::is_same<Iter, const unsigned char*>::value &&
285 (std::is_same<OtherIter, const char*>::value ||
286 std::is_same<OtherIter, char*>::value)), int>::type = 0>
287 /* implicit */ Range(const Range<OtherIter>& other)
288 : b_(reinterpret_cast<const unsigned char*>(other.begin())),
289 e_(reinterpret_cast<const unsigned char*>(other.end())) {
292 template <class OtherIter, typename std::enable_if<
293 (std::is_same<Iter, unsigned char*>::value &&
294 std::is_same<OtherIter, char*>::value), int>::type = 0>
295 /* implicit */ Range(const Range<OtherIter>& other)
296 : b_(reinterpret_cast<unsigned char*>(other.begin())),
297 e_(reinterpret_cast<unsigned char*>(other.end())) {
300 template <class OtherIter, typename std::enable_if<
301 (std::is_same<Iter, const char*>::value &&
302 (std::is_same<OtherIter, const unsigned char*>::value ||
303 std::is_same<OtherIter, unsigned char*>::value)), int>::type = 0>
304 explicit Range(const Range<OtherIter>& other)
305 : b_(reinterpret_cast<const char*>(other.begin())),
306 e_(reinterpret_cast<const char*>(other.end())) {
309 template <class OtherIter, typename std::enable_if<
310 (std::is_same<Iter, char*>::value &&
311 std::is_same<OtherIter, unsigned char*>::value), int>::type = 0>
312 explicit Range(const Range<OtherIter>& other)
313 : b_(reinterpret_cast<char*>(other.begin())),
314 e_(reinterpret_cast<char*>(other.end())) {
317 // Allow implicit conversion from Range<From> to Range<To> if From is
318 // implicitly convertible to To.
319 template <class OtherIter, typename std::enable_if<
320 (!std::is_same<Iter, OtherIter>::value &&
321 std::is_convertible<OtherIter, Iter>::value), int>::type = 0>
322 constexpr /* implicit */ Range(const Range<OtherIter>& other)
327 // Allow explicit conversion from Range<From> to Range<To> if From is
328 // explicitly convertible to To.
329 template <class OtherIter, typename std::enable_if<
330 (!std::is_same<Iter, OtherIter>::value &&
331 !std::is_convertible<OtherIter, Iter>::value &&
332 std::is_constructible<Iter, const OtherIter&>::value), int>::type = 0>
333 constexpr explicit Range(const Range<OtherIter>& other)
338 Range& operator=(const Range& rhs) & = default;
339 Range& operator=(Range&& rhs) & = default;
346 void assign(Iter start, Iter end) {
351 void reset(Iter start, size_type size) {
356 // Works only for Range<const char*>
357 void reset(const std::string& str) {
358 reset(str.data(), str.size());
361 constexpr size_type size() const {
362 // It would be nice to assert(b_ <= e_) here. This can be achieved even
363 // in a C++11 compatible constexpr function:
364 // http://ericniebler.com/2014/09/27/assert-and-constexpr-in-cxx11/
365 // Unfortunately current gcc versions have a bug causing it to reject
366 // this check in a constexpr function:
367 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=71448
370 size_type walk_size() const {
371 return std::distance(b_, e_);
373 bool empty() const { return b_ == e_; }
374 Iter data() const { return b_; }
375 Iter start() const { return b_; }
376 Iter begin() const { return b_; }
377 Iter end() const { return e_; }
378 Iter cbegin() const { return b_; }
379 Iter cend() const { return e_; }
380 value_type& front() {
386 return detail::value_before(e_);
388 const value_type& front() const {
392 const value_type& back() const {
394 return detail::value_before(e_);
396 // Works only for Range<const char*> and Range<char*>
397 std::string str() const { return std::string(b_, size()); }
398 std::string toString() const { return str(); }
399 // Works only for Range<const char*> and Range<char*>
400 fbstring fbstr() const { return fbstring(b_, size()); }
401 fbstring toFbstring() const { return fbstr(); }
403 const_range_type castToConst() const {
404 return const_range_type(*this);
407 // Works only for Range<const char*> and Range<char*>
408 int compare(const const_range_type& o) const {
409 const size_type tsize = this->size();
410 const size_type osize = o.size();
411 const size_type msize = std::min(tsize, osize);
412 int r = traits_type::compare(data(), o.data(), msize);
413 if (r == 0 && tsize != osize) {
414 // We check the signed bit of the subtraction and bit shift it
415 // to produce either 0 or 2. The subtraction yields the
416 // comparison values of either -1 or 1.
417 r = (static_cast<int>(
418 (osize - tsize) >> (CHAR_BIT * sizeof(size_t) - 1)) << 1) - 1;
423 value_type& operator[](size_t i) {
424 DCHECK_GT(size(), i);
428 const value_type& operator[](size_t i) const {
429 DCHECK_GT(size(), i);
433 value_type& at(size_t i) {
434 if (i >= size()) detail::throwOutOfRange();
438 const value_type& at(size_t i) const {
439 if (i >= size()) detail::throwOutOfRange();
443 // Do NOT use this function, which was left behind for backwards
444 // compatibility. Use SpookyHashV2 instead -- it is faster, and produces
445 // a 64-bit hash, which means dramatically fewer collisions in large maps.
446 // (The above advice does not apply if you are targeting a 32-bit system.)
448 // Works only for Range<const char*> and Range<char*>
449 uint32_t hash() const {
450 // Taken from fbi/nstring.h:
451 // Quick and dirty bernstein hash...fine for short ascii strings
452 uint32_t hash = 5381;
453 for (size_t ix = 0; ix < size(); ix++) {
454 hash = ((hash << 5) + hash) + b_[ix];
459 void advance(size_type n) {
460 if (UNLIKELY(n > size())) {
461 detail::throwOutOfRange();
466 void subtract(size_type n) {
467 if (UNLIKELY(n > size())) {
468 detail::throwOutOfRange();
473 Range subpiece(size_type first, size_type length = npos) const {
474 if (UNLIKELY(first > size())) {
475 detail::throwOutOfRange();
478 return Range(b_ + first, std::min(length, size() - first));
481 // unchecked versions
482 void uncheckedAdvance(size_type n) {
483 DCHECK_LE(n, size());
487 void uncheckedSubtract(size_type n) {
488 DCHECK_LE(n, size());
492 Range uncheckedSubpiece(size_type first, size_type length = npos) const {
493 DCHECK_LE(first, size());
494 return Range(b_ + first, std::min(length, size() - first));
507 // string work-alike functions
508 size_type find(const_range_type str) const {
509 return qfind(castToConst(), str);
512 size_type find(const_range_type str, size_t pos) const {
513 if (pos > size()) return std::string::npos;
514 size_t ret = qfind(castToConst().subpiece(pos), str);
515 return ret == npos ? ret : ret + pos;
518 size_type find(Iter s, size_t pos, size_t n) const {
519 if (pos > size()) return std::string::npos;
520 auto forFinding = castToConst();
522 pos ? forFinding.subpiece(pos) : forFinding, const_range_type(s, n));
523 return ret == npos ? ret : ret + pos;
526 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
527 size_type find(const Iter s) const {
528 return qfind(castToConst(), const_range_type(s));
531 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
532 size_type find(const Iter s, size_t pos) const {
533 if (pos > size()) return std::string::npos;
534 size_type ret = qfind(castToConst().subpiece(pos), const_range_type(s));
535 return ret == npos ? ret : ret + pos;
538 size_type find(value_type c) const {
539 return qfind(castToConst(), c);
542 size_type rfind(value_type c) const {
543 return folly::rfind(castToConst(), c);
546 size_type find(value_type c, size_t pos) const {
547 if (pos > size()) return std::string::npos;
548 size_type ret = qfind(castToConst().subpiece(pos), c);
549 return ret == npos ? ret : ret + pos;
552 size_type find_first_of(const_range_type needles) const {
553 return qfind_first_of(castToConst(), needles);
556 size_type find_first_of(const_range_type needles, size_t pos) const {
557 if (pos > size()) return std::string::npos;
558 size_type ret = qfind_first_of(castToConst().subpiece(pos), needles);
559 return ret == npos ? ret : ret + pos;
562 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
563 size_type find_first_of(Iter needles) const {
564 return find_first_of(const_range_type(needles));
567 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
568 size_type find_first_of(Iter needles, size_t pos) const {
569 return find_first_of(const_range_type(needles), pos);
572 size_type find_first_of(Iter needles, size_t pos, size_t n) const {
573 return find_first_of(const_range_type(needles, n), pos);
576 size_type find_first_of(value_type c) const {
580 size_type find_first_of(value_type c, size_t pos) const {
585 * Determine whether the range contains the given subrange or item.
587 * Note: Call find() directly if the index is needed.
589 bool contains(const const_range_type& other) const {
590 return find(other) != std::string::npos;
593 bool contains(const value_type& other) const {
594 return find(other) != std::string::npos;
597 void swap(Range& rhs) {
598 std::swap(b_, rhs.b_);
599 std::swap(e_, rhs.e_);
603 * Does this Range start with another range?
605 bool startsWith(const const_range_type& other) const {
606 return size() >= other.size()
607 && castToConst().subpiece(0, other.size()) == other;
609 bool startsWith(value_type c) const {
610 return !empty() && front() == c;
614 * Does this Range end with another range?
616 bool endsWith(const const_range_type& other) const {
617 return size() >= other.size()
618 && castToConst().subpiece(size() - other.size()) == other;
620 bool endsWith(value_type c) const {
621 return !empty() && back() == c;
625 * Remove the items in [b, e), as long as this subrange is at the beginning
626 * or end of the Range.
628 * Required for boost::algorithm::trim()
630 void erase(Iter b, Iter e) {
633 } else if (e == e_) {
636 detail::throwOutOfRange();
641 * Remove the given prefix and return true if the range starts with the given
642 * prefix; return false otherwise.
644 bool removePrefix(const const_range_type& prefix) {
645 return startsWith(prefix) && (b_ += prefix.size(), true);
647 bool removePrefix(value_type prefix) {
648 return startsWith(prefix) && (++b_, true);
652 * Remove the given suffix and return true if the range ends with the given
653 * suffix; return false otherwise.
655 bool removeSuffix(const const_range_type& suffix) {
656 return endsWith(suffix) && (e_ -= suffix.size(), true);
658 bool removeSuffix(value_type suffix) {
659 return endsWith(suffix) && (--e_, true);
663 * Replaces the content of the range, starting at position 'pos', with
664 * contents of 'replacement'. Entire 'replacement' must fit into the
665 * range. Returns false if 'replacements' does not fit. Example use:
667 * char in[] = "buffer";
668 * auto msp = MutablesStringPiece(input);
669 * EXPECT_TRUE(msp.replaceAt(2, "tt"));
670 * EXPECT_EQ(msp, "butter");
672 * // not enough space
673 * EXPECT_FALSE(msp.replace(msp.size() - 1, "rr"));
674 * EXPECT_EQ(msp, "butter"); // unchanged
676 bool replaceAt(size_t pos, const_range_type replacement) {
677 if (size() < pos + replacement.size()) {
681 std::copy(replacement.begin(), replacement.end(), begin() + pos);
687 * Replaces all occurences of 'source' with 'dest'. Returns number
688 * of replacements made. Source and dest have to have the same
689 * length. Throws if the lengths are different. If 'source' is a
690 * pattern that is overlapping with itself, we perform sequential
691 * replacement: "aaaaaaa".replaceAll("aa", "ba") --> "bababaa"
695 * char in[] = "buffer";
696 * auto msp = MutablesStringPiece(input);
697 * EXPECT_EQ(msp.replaceAll("ff","tt"), 1);
698 * EXPECT_EQ(msp, "butter");
700 size_t replaceAll(const_range_type source, const_range_type dest) {
701 if (source.size() != dest.size()) {
702 throw std::invalid_argument(
703 "replacement must have the same size as source");
711 size_t num_replaced = 0;
712 size_type found = std::string::npos;
713 while ((found = find(source, pos)) != std::string::npos) {
714 replaceAt(found, dest);
715 pos += source.size();
723 * Splits this `Range` `[b, e)` in the position `i` dictated by the next
724 * occurence of `delimiter`.
726 * Returns a new `Range` `[b, i)` and adjusts this range to start right after
727 * the delimiter's position. This range will be empty if the delimiter is not
728 * found. If called on an empty `Range`, both this and the returned `Range`
733 * folly::StringPiece s("sample string for split_next");
734 * auto p = s.split_step(' ');
736 * // prints "string for split_next"
744 * void tokenize(StringPiece s, char delimiter) {
745 * while (!s.empty()) {
746 * cout << s.split_step(delimiter);
750 * @author: Marcelo Juchem <marcelo@fb.com>
752 Range split_step(value_type delimiter) {
753 auto i = std::find(b_, e_, delimiter);
756 b_ = i == e_ ? e_ : std::next(i);
761 Range split_step(Range delimiter) {
762 auto i = find(delimiter);
763 Range result(b_, i == std::string::npos ? size() : i);
765 b_ = result.end() == e_ ? e_ : std::next(result.end(), delimiter.size());
771 * Convenience method that calls `split_step()` and passes the result to a
772 * functor, returning whatever the functor does. Any additional arguments
773 * `args` passed to this function are perfectly forwarded to the functor.
775 * Say you have a functor with this signature:
777 * Foo fn(Range r) { }
779 * `split_step()`'s return type will be `Foo`. It works just like:
781 * auto result = fn(myRange.split_step(' '));
783 * A functor returning `void` is also supported.
787 * void do_some_parsing(folly::StringPiece s) {
788 * auto version = s.split_step(' ', [&](folly::StringPiece x) {
790 * throw std::invalid_argument("empty string");
792 * return std::strtoull(x.begin(), x.end(), 16);
799 * void parse(folly::StringPiece s) {
800 * s.split_step(' ', parse_field, bar, 10);
801 * s.split_step('\t', parse_field, baz, 20);
803 * auto const kludge = [](folly::StringPiece x, int &out, int def) {
807 * parse_field(x, out, def);
811 * s.split_step('\t', kludge, gaz);
812 * s.split_step(' ', kludge, foo);
821 * static parse_field(folly::StringPiece s, int &out, int def) {
823 * out = folly::to<int>(s);
824 * } catch (std::exception const &) {
830 * @author: Marcelo Juchem <marcelo@fb.com>
832 template <typename TProcess, typename... Args>
833 auto split_step(value_type delimiter, TProcess &&process, Args &&...args)
834 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
835 { return process(split_step(delimiter), std::forward<Args>(args)...); }
837 template <typename TProcess, typename... Args>
838 auto split_step(Range delimiter, TProcess &&process, Args &&...args)
839 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
840 { return process(split_step(delimiter), std::forward<Args>(args)...); }
846 template <class Iter>
847 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
850 void swap(Range<T>& lhs, Range<T>& rhs) {
855 * Create a range from two iterators, with type deduction.
857 template <class Iter>
858 Range<Iter> range(Iter first, Iter last) {
859 return Range<Iter>(first, last);
863 * Creates a range to reference the contents of a contiguous-storage container.
865 // Use pointers for types with '.data()' member
866 template <class Collection,
867 class T = typename std::remove_pointer<
868 decltype(std::declval<Collection>().data())>::type>
869 Range<T*> range(Collection&& v) {
870 return Range<T*>(v.data(), v.data() + v.size());
873 template <class T, size_t n>
874 Range<T*> range(T (&array)[n]) {
875 return Range<T*>(array, array + n);
878 typedef Range<const char*> StringPiece;
879 typedef Range<char*> MutableStringPiece;
880 typedef Range<const unsigned char*> ByteRange;
881 typedef Range<unsigned char*> MutableByteRange;
883 inline std::ostream& operator<<(std::ostream& os,
884 const StringPiece piece) {
885 os.write(piece.start(), piece.size());
889 inline std::ostream& operator<<(std::ostream& os,
890 const MutableStringPiece piece) {
891 os.write(piece.start(), piece.size());
896 * Templated comparison operators
900 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
901 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
905 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
906 return lhs.compare(rhs) < 0;
910 * Specializations of comparison operators for StringPiece
915 template <class A, class B>
916 struct ComparableAsStringPiece {
919 (std::is_convertible<A, StringPiece>::value
920 && std::is_same<B, StringPiece>::value)
922 (std::is_convertible<B, StringPiece>::value
923 && std::is_same<A, StringPiece>::value)
927 } // namespace detail
930 * operator== through conversion for Range<const char*>
932 template <class T, class U>
934 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
935 operator==(const T& lhs, const U& rhs) {
936 return StringPiece(lhs) == StringPiece(rhs);
940 * operator< through conversion for Range<const char*>
942 template <class T, class U>
944 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
945 operator<(const T& lhs, const U& rhs) {
946 return StringPiece(lhs) < StringPiece(rhs);
950 * operator> through conversion for Range<const char*>
952 template <class T, class U>
954 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
955 operator>(const T& lhs, const U& rhs) {
956 return StringPiece(lhs) > StringPiece(rhs);
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);
979 // Do NOT use this, use SpookyHashV2 instead, see commment on hash() above.
980 struct StringPieceHash {
981 std::size_t operator()(const StringPiece str) const {
982 return static_cast<std::size_t>(str.hash());
987 * Finds substrings faster than brute force by borrowing from Boyer-Moore
989 template <class T, class Comp>
990 size_t qfind(const Range<T>& haystack,
991 const Range<T>& needle,
993 // Don't use std::search, use a Boyer-Moore-like trick by comparing
994 // the last characters first
995 auto const nsize = needle.size();
996 if (haystack.size() < nsize) {
997 return std::string::npos;
999 if (!nsize) return 0;
1000 auto const nsize_1 = nsize - 1;
1001 auto const lastNeedle = needle[nsize_1];
1003 // Boyer-Moore skip value for the last char in the needle. Zero is
1004 // not a valid value; skip will be computed the first time it's
1006 std::string::size_type skip = 0;
1008 auto i = haystack.begin();
1009 auto iEnd = haystack.end() - nsize_1;
1012 // Boyer-Moore: match the last element in the needle
1013 while (!eq(i[nsize_1], lastNeedle)) {
1016 return std::string::npos;
1019 // Here we know that the last char matches
1020 // Continue in pedestrian mode
1021 for (size_t j = 0; ; ) {
1023 if (!eq(i[j], needle[j])) {
1024 // Not found, we can skip
1025 // Compute the skip value lazily
1028 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
1035 // Check if done searching
1038 return i - haystack.begin();
1042 return std::string::npos;
1047 inline size_t qfind_first_byte_of(const StringPiece haystack,
1048 const StringPiece needles) {
1049 static auto const qfind_first_byte_of_fn =
1050 folly::CpuId().sse42() ? qfind_first_byte_of_sse42
1051 : qfind_first_byte_of_nosse;
1052 return qfind_first_byte_of_fn(haystack, needles);
1055 } // namespace detail
1057 template <class T, class Comp>
1058 size_t qfind_first_of(const Range<T> & haystack,
1059 const Range<T> & needles,
1061 auto ret = std::find_first_of(haystack.begin(), haystack.end(),
1062 needles.begin(), needles.end(),
1064 return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
1067 struct AsciiCaseSensitive {
1068 bool operator()(char lhs, char rhs) const {
1074 * Check if two ascii characters are case insensitive equal.
1075 * The difference between the lower/upper case characters are the 6-th bit.
1076 * We also check they are alpha chars, in case of xor = 32.
1078 struct AsciiCaseInsensitive {
1079 bool operator()(char lhs, char rhs) const {
1081 if (k == 0) return true;
1082 if (k != 32) return false;
1084 return (k >= 'a' && k <= 'z');
1089 size_t qfind(const Range<T>& haystack,
1090 const typename Range<T>::value_type& needle) {
1091 auto pos = std::find(haystack.begin(), haystack.end(), needle);
1092 return pos == haystack.end() ? std::string::npos : pos - haystack.data();
1096 size_t rfind(const Range<T>& haystack,
1097 const typename Range<T>::value_type& needle) {
1098 for (auto i = haystack.size(); i-- > 0; ) {
1099 if (haystack[i] == needle) {
1103 return std::string::npos;
1106 // specialization for StringPiece
1108 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
1109 // memchr expects a not-null pointer, early return if the range is empty.
1110 if (haystack.empty()) {
1111 return std::string::npos;
1113 auto pos = static_cast<const char*>(
1114 ::memchr(haystack.data(), needle, haystack.size()));
1115 return pos == nullptr ? std::string::npos : pos - haystack.data();
1119 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
1120 // memchr expects a not-null pointer, early return if the range is empty.
1121 if (haystack.empty()) {
1122 return std::string::npos;
1124 auto pos = static_cast<const char*>(
1125 ::memrchr(haystack.data(), needle, haystack.size()));
1126 return pos == nullptr ? std::string::npos : pos - haystack.data();
1129 // specialization for ByteRange
1131 inline size_t qfind(const Range<const unsigned char*>& haystack,
1132 const unsigned char& needle) {
1133 // memchr expects a not-null pointer, early return if the range is empty.
1134 if (haystack.empty()) {
1135 return std::string::npos;
1137 auto pos = static_cast<const unsigned char*>(
1138 ::memchr(haystack.data(), needle, haystack.size()));
1139 return pos == nullptr ? std::string::npos : pos - haystack.data();
1143 inline size_t rfind(const Range<const unsigned char*>& haystack,
1144 const unsigned char& needle) {
1145 // memchr expects a not-null pointer, early return if the range is empty.
1146 if (haystack.empty()) {
1147 return std::string::npos;
1149 auto pos = static_cast<const unsigned char*>(
1150 ::memrchr(haystack.data(), needle, haystack.size()));
1151 return pos == nullptr ? std::string::npos : pos - haystack.data();
1155 size_t qfind_first_of(const Range<T>& haystack,
1156 const Range<T>& needles) {
1157 return qfind_first_of(haystack, needles, AsciiCaseSensitive());
1160 // specialization for StringPiece
1162 inline size_t qfind_first_of(const Range<const char*>& haystack,
1163 const Range<const char*>& needles) {
1164 return detail::qfind_first_byte_of(haystack, needles);
1167 // specialization for ByteRange
1169 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
1170 const Range<const unsigned char*>& needles) {
1171 return detail::qfind_first_byte_of(StringPiece(haystack),
1172 StringPiece(needles));
1175 template<class Key, class Enable>
1179 struct hasher<folly::Range<T*>,
1180 typename std::enable_if<std::is_pod<T>::value, void>::type> {
1181 size_t operator()(folly::Range<T*> r) const {
1182 return hash::SpookyHashV2::Hash64(r.begin(), r.size() * sizeof(T), 0);
1187 * Ubiquitous helper template for knowing what's a string
1189 template <class T> struct IsSomeString {
1190 enum { value = std::is_same<T, std::string>::value
1191 || std::is_same<T, fbstring>::value };
1194 } // !namespace folly
1196 #pragma GCC diagnostic pop
1198 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);