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 size_type walk_size() const {
367 return std::distance(b_, e_);
369 bool empty() const { return b_ == e_; }
370 Iter data() const { return b_; }
371 Iter start() const { return b_; }
372 Iter begin() const { return b_; }
373 Iter end() const { return e_; }
374 Iter cbegin() const { return b_; }
375 Iter cend() const { return e_; }
376 value_type& front() {
382 return detail::value_before(e_);
384 const value_type& front() const {
388 const value_type& back() const {
390 return detail::value_before(e_);
392 // Works only for Range<const char*> and Range<char*>
393 std::string str() const { return std::string(b_, size()); }
394 std::string toString() const { return str(); }
395 // Works only for Range<const char*> and Range<char*>
396 fbstring fbstr() const { return fbstring(b_, size()); }
397 fbstring toFbstring() const { return fbstr(); }
399 const_range_type castToConst() const {
400 return const_range_type(*this);
403 // Works only for Range<const char*> and Range<char*>
404 int compare(const const_range_type& o) const {
405 const size_type tsize = this->size();
406 const size_type osize = o.size();
407 const size_type msize = std::min(tsize, osize);
408 int r = traits_type::compare(data(), o.data(), msize);
409 if (r == 0 && tsize != osize) {
410 // We check the signed bit of the subtraction and bit shift it
411 // to produce either 0 or 2. The subtraction yields the
412 // comparison values of either -1 or 1.
413 r = (static_cast<int>(
414 (osize - tsize) >> (CHAR_BIT * sizeof(size_t) - 1)) << 1) - 1;
419 value_type& operator[](size_t i) {
420 DCHECK_GT(size(), i);
424 const value_type& operator[](size_t i) const {
425 DCHECK_GT(size(), i);
429 value_type& at(size_t i) {
430 if (i >= size()) std::__throw_out_of_range("index out of range");
434 const value_type& at(size_t i) const {
435 if (i >= size()) std::__throw_out_of_range("index out of range");
439 // Do NOT use this function, which was left behind for backwards
440 // compatibility. Use SpookyHashV2 instead -- it is faster, and produces
441 // a 64-bit hash, which means dramatically fewer collisions in large maps.
442 // (The above advice does not apply if you are targeting a 32-bit system.)
444 // Works only for Range<const char*> and Range<char*>
447 // ** WANT TO GET RID OF THIS LINT? **
449 // A) Use a better hash function (*cough*folly::Hash*cough*), but
450 // only if you don't serialize data in a format that depends on
451 // this formula (ie the writer and reader assume this exact hash
452 // function is used).
454 // B) If you have to use this exact function then make your own hasher
455 // object and copy the body over (see thrift example: D3972362).
456 // https://github.com/facebook/fbthrift/commit/f8ed502e24ab4a32a9d5f266580
457 FOLLY_DEPRECATED("Replace with folly::Hash if the hash is not serialized")
458 uint32_t hash() const {
459 // Taken from fbi/nstring.h:
460 // Quick and dirty bernstein hash...fine for short ascii strings
461 uint32_t hash = 5381;
462 for (size_t ix = 0; ix < size(); ix++) {
463 hash = ((hash << 5) + hash) + b_[ix];
468 void advance(size_type n) {
469 if (UNLIKELY(n > size())) {
470 std::__throw_out_of_range("index out of range");
475 void subtract(size_type n) {
476 if (UNLIKELY(n > size())) {
477 std::__throw_out_of_range("index out of range");
482 Range subpiece(size_type first, size_type length = npos) const {
483 if (UNLIKELY(first > size())) {
484 std::__throw_out_of_range("index out of range");
487 return Range(b_ + first, std::min(length, size() - first));
490 // unchecked versions
491 void uncheckedAdvance(size_type n) {
492 DCHECK_LE(n, size());
496 void uncheckedSubtract(size_type n) {
497 DCHECK_LE(n, size());
501 Range uncheckedSubpiece(size_type first, size_type length = npos) const {
502 DCHECK_LE(first, size());
503 return Range(b_ + first, std::min(length, size() - first));
516 // string work-alike functions
517 size_type find(const_range_type str) const {
518 return qfind(castToConst(), str);
521 size_type find(const_range_type str, size_t pos) const {
522 if (pos > size()) return std::string::npos;
523 size_t ret = qfind(castToConst().subpiece(pos), str);
524 return ret == npos ? ret : ret + pos;
527 size_type find(Iter s, size_t pos, size_t n) const {
528 if (pos > size()) return std::string::npos;
529 auto forFinding = castToConst();
531 pos ? forFinding.subpiece(pos) : forFinding, const_range_type(s, n));
532 return ret == npos ? ret : ret + pos;
535 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
536 size_type find(const Iter s) const {
537 return qfind(castToConst(), const_range_type(s));
540 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
541 size_type find(const Iter s, size_t pos) const {
542 if (pos > size()) return std::string::npos;
543 size_type ret = qfind(castToConst().subpiece(pos), const_range_type(s));
544 return ret == npos ? ret : ret + pos;
547 size_type find(value_type c) const {
548 return qfind(castToConst(), c);
551 size_type rfind(value_type c) const {
552 return folly::rfind(castToConst(), c);
555 size_type find(value_type c, size_t pos) const {
556 if (pos > size()) return std::string::npos;
557 size_type ret = qfind(castToConst().subpiece(pos), c);
558 return ret == npos ? ret : ret + pos;
561 size_type find_first_of(const_range_type needles) const {
562 return qfind_first_of(castToConst(), needles);
565 size_type find_first_of(const_range_type needles, size_t pos) const {
566 if (pos > size()) return std::string::npos;
567 size_type ret = qfind_first_of(castToConst().subpiece(pos), needles);
568 return ret == npos ? ret : ret + pos;
571 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
572 size_type find_first_of(Iter needles) const {
573 return find_first_of(const_range_type(needles));
576 // Works only for Range<(const) (unsigned) char*> which have Range(Iter) ctor
577 size_type find_first_of(Iter needles, size_t pos) const {
578 return find_first_of(const_range_type(needles), pos);
581 size_type find_first_of(Iter needles, size_t pos, size_t n) const {
582 return find_first_of(const_range_type(needles, n), pos);
585 size_type find_first_of(value_type c) const {
589 size_type find_first_of(value_type c, size_t pos) const {
594 * Determine whether the range contains the given subrange or item.
596 * Note: Call find() directly if the index is needed.
598 bool contains(const const_range_type& other) const {
599 return find(other) != std::string::npos;
602 bool contains(const value_type& other) const {
603 return find(other) != std::string::npos;
606 void swap(Range& rhs) {
607 std::swap(b_, rhs.b_);
608 std::swap(e_, rhs.e_);
612 * Does this Range start with another range?
614 bool startsWith(const const_range_type& other) const {
615 return size() >= other.size()
616 && castToConst().subpiece(0, other.size()) == other;
618 bool startsWith(value_type c) const {
619 return !empty() && front() == c;
623 * Does this Range end with another range?
625 bool endsWith(const const_range_type& other) const {
626 return size() >= other.size()
627 && castToConst().subpiece(size() - other.size()) == other;
629 bool endsWith(value_type c) const {
630 return !empty() && back() == c;
634 * Remove the items in [b, e), as long as this subrange is at the beginning
635 * or end of the Range.
637 * Required for boost::algorithm::trim()
639 void erase(Iter b, Iter e) {
642 } else if (e == e_) {
645 std::__throw_out_of_range("index out of range");
650 * Remove the given prefix and return true if the range starts with the given
651 * prefix; return false otherwise.
653 bool removePrefix(const const_range_type& prefix) {
654 return startsWith(prefix) && (b_ += prefix.size(), true);
656 bool removePrefix(value_type prefix) {
657 return startsWith(prefix) && (++b_, true);
661 * Remove the given suffix and return true if the range ends with the given
662 * suffix; return false otherwise.
664 bool removeSuffix(const const_range_type& suffix) {
665 return endsWith(suffix) && (e_ -= suffix.size(), true);
667 bool removeSuffix(value_type suffix) {
668 return endsWith(suffix) && (--e_, true);
672 * Replaces the content of the range, starting at position 'pos', with
673 * contents of 'replacement'. Entire 'replacement' must fit into the
674 * range. Returns false if 'replacements' does not fit. Example use:
676 * char in[] = "buffer";
677 * auto msp = MutablesStringPiece(input);
678 * EXPECT_TRUE(msp.replaceAt(2, "tt"));
679 * EXPECT_EQ(msp, "butter");
681 * // not enough space
682 * EXPECT_FALSE(msp.replace(msp.size() - 1, "rr"));
683 * EXPECT_EQ(msp, "butter"); // unchanged
685 bool replaceAt(size_t pos, const_range_type replacement) {
686 if (size() < pos + replacement.size()) {
690 std::copy(replacement.begin(), replacement.end(), begin() + pos);
696 * Replaces all occurences of 'source' with 'dest'. Returns number
697 * of replacements made. Source and dest have to have the same
698 * length. Throws if the lengths are different. If 'source' is a
699 * pattern that is overlapping with itself, we perform sequential
700 * replacement: "aaaaaaa".replaceAll("aa", "ba") --> "bababaa"
704 * char in[] = "buffer";
705 * auto msp = MutablesStringPiece(input);
706 * EXPECT_EQ(msp.replaceAll("ff","tt"), 1);
707 * EXPECT_EQ(msp, "butter");
709 size_t replaceAll(const_range_type source, const_range_type dest) {
710 if (source.size() != dest.size()) {
711 throw std::invalid_argument(
712 "replacement must have the same size as source");
720 size_t num_replaced = 0;
721 size_type found = std::string::npos;
722 while ((found = find(source, pos)) != std::string::npos) {
723 replaceAt(found, dest);
724 pos += source.size();
732 * Splits this `Range` `[b, e)` in the position `i` dictated by the next
733 * occurence of `delimiter`.
735 * Returns a new `Range` `[b, i)` and adjusts this range to start right after
736 * the delimiter's position. This range will be empty if the delimiter is not
737 * found. If called on an empty `Range`, both this and the returned `Range`
742 * folly::StringPiece s("sample string for split_next");
743 * auto p = s.split_step(' ');
745 * // prints "string for split_next"
753 * void tokenize(StringPiece s, char delimiter) {
754 * while (!s.empty()) {
755 * cout << s.split_step(delimiter);
759 * @author: Marcelo Juchem <marcelo@fb.com>
761 Range split_step(value_type delimiter) {
762 auto i = std::find(b_, e_, delimiter);
765 b_ = i == e_ ? e_ : std::next(i);
770 Range split_step(Range delimiter) {
771 auto i = find(delimiter);
772 Range result(b_, i == std::string::npos ? size() : i);
774 b_ = result.end() == e_ ? e_ : std::next(result.end(), delimiter.size());
780 * Convenience method that calls `split_step()` and passes the result to a
781 * functor, returning whatever the functor does. Any additional arguments
782 * `args` passed to this function are perfectly forwarded to the functor.
784 * Say you have a functor with this signature:
786 * Foo fn(Range r) { }
788 * `split_step()`'s return type will be `Foo`. It works just like:
790 * auto result = fn(myRange.split_step(' '));
792 * A functor returning `void` is also supported.
796 * void do_some_parsing(folly::StringPiece s) {
797 * auto version = s.split_step(' ', [&](folly::StringPiece x) {
799 * throw std::invalid_argument("empty string");
801 * return std::strtoull(x.begin(), x.end(), 16);
808 * void parse(folly::StringPiece s) {
809 * s.split_step(' ', parse_field, bar, 10);
810 * s.split_step('\t', parse_field, baz, 20);
812 * auto const kludge = [](folly::StringPiece x, int &out, int def) {
816 * parse_field(x, out, def);
820 * s.split_step('\t', kludge, gaz);
821 * s.split_step(' ', kludge, foo);
830 * static parse_field(folly::StringPiece s, int &out, int def) {
832 * out = folly::to<int>(s);
833 * } catch (std::exception const &) {
839 * @author: Marcelo Juchem <marcelo@fb.com>
841 template <typename TProcess, typename... Args>
842 auto split_step(value_type delimiter, TProcess &&process, Args &&...args)
843 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
844 { return process(split_step(delimiter), std::forward<Args>(args)...); }
846 template <typename TProcess, typename... Args>
847 auto split_step(Range delimiter, TProcess &&process, Args &&...args)
848 -> decltype(process(std::declval<Range>(), std::forward<Args>(args)...))
849 { return process(split_step(delimiter), std::forward<Args>(args)...); }
855 template <class Iter>
856 const typename Range<Iter>::size_type Range<Iter>::npos = std::string::npos;
859 void swap(Range<T>& lhs, Range<T>& rhs) {
864 * Create a range from two iterators, with type deduction.
866 template <class Iter>
867 Range<Iter> range(Iter first, Iter last) {
868 return Range<Iter>(first, last);
872 * Creates a range to reference the contents of a contiguous-storage container.
874 // Use pointers for types with '.data()' member
875 template <class Collection,
876 class T = typename std::remove_pointer<
877 decltype(std::declval<Collection>().data())>::type>
878 Range<T*> range(Collection&& v) {
879 return Range<T*>(v.data(), v.data() + v.size());
882 template <class T, size_t n>
883 Range<T*> range(T (&array)[n]) {
884 return Range<T*>(array, array + n);
887 typedef Range<const char*> StringPiece;
888 typedef Range<char*> MutableStringPiece;
889 typedef Range<const unsigned char*> ByteRange;
890 typedef Range<unsigned char*> MutableByteRange;
892 inline std::ostream& operator<<(std::ostream& os,
893 const StringPiece piece) {
894 os.write(piece.start(), piece.size());
898 inline std::ostream& operator<<(std::ostream& os,
899 const MutableStringPiece piece) {
900 os.write(piece.start(), piece.size());
905 * Templated comparison operators
909 inline bool operator==(const Range<T>& lhs, const Range<T>& rhs) {
910 return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
914 inline bool operator<(const Range<T>& lhs, const Range<T>& rhs) {
915 return lhs.compare(rhs) < 0;
919 * Specializations of comparison operators for StringPiece
924 template <class A, class B>
925 struct ComparableAsStringPiece {
928 (std::is_convertible<A, StringPiece>::value
929 && std::is_same<B, StringPiece>::value)
931 (std::is_convertible<B, StringPiece>::value
932 && std::is_same<A, StringPiece>::value)
936 } // namespace detail
939 * operator== through conversion for Range<const char*>
941 template <class T, class U>
943 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
944 operator==(const T& lhs, const U& rhs) {
945 return StringPiece(lhs) == StringPiece(rhs);
949 * operator< through conversion for Range<const char*>
951 template <class T, class U>
953 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
954 operator<(const T& lhs, const U& rhs) {
955 return StringPiece(lhs) < StringPiece(rhs);
959 * operator> through conversion for Range<const char*>
961 template <class T, class U>
963 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
964 operator>(const T& lhs, const U& rhs) {
965 return StringPiece(lhs) > StringPiece(rhs);
969 * operator< through conversion for Range<const char*>
971 template <class T, class U>
973 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
974 operator<=(const T& lhs, const U& rhs) {
975 return StringPiece(lhs) <= StringPiece(rhs);
979 * operator> through conversion for Range<const char*>
981 template <class T, class U>
983 std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool>::type
984 operator>=(const T& lhs, const U& rhs) {
985 return StringPiece(lhs) >= StringPiece(rhs);
989 * Finds substrings faster than brute force by borrowing from Boyer-Moore
991 template <class T, class Comp>
992 size_t qfind(const Range<T>& haystack,
993 const Range<T>& needle,
995 // Don't use std::search, use a Boyer-Moore-like trick by comparing
996 // the last characters first
997 auto const nsize = needle.size();
998 if (haystack.size() < nsize) {
999 return std::string::npos;
1001 if (!nsize) return 0;
1002 auto const nsize_1 = nsize - 1;
1003 auto const lastNeedle = needle[nsize_1];
1005 // Boyer-Moore skip value for the last char in the needle. Zero is
1006 // not a valid value; skip will be computed the first time it's
1008 std::string::size_type skip = 0;
1010 auto i = haystack.begin();
1011 auto iEnd = haystack.end() - nsize_1;
1014 // Boyer-Moore: match the last element in the needle
1015 while (!eq(i[nsize_1], lastNeedle)) {
1018 return std::string::npos;
1021 // Here we know that the last char matches
1022 // Continue in pedestrian mode
1023 for (size_t j = 0; ; ) {
1025 if (!eq(i[j], needle[j])) {
1026 // Not found, we can skip
1027 // Compute the skip value lazily
1030 while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
1037 // Check if done searching
1040 return i - haystack.begin();
1044 return std::string::npos;
1049 inline size_t qfind_first_byte_of(const StringPiece haystack,
1050 const StringPiece needles) {
1051 static auto const qfind_first_byte_of_fn =
1052 folly::CpuId().sse42() ? qfind_first_byte_of_sse42
1053 : qfind_first_byte_of_nosse;
1054 return qfind_first_byte_of_fn(haystack, needles);
1057 } // namespace detail
1059 template <class T, class Comp>
1060 size_t qfind_first_of(const Range<T> & haystack,
1061 const Range<T> & needles,
1063 auto ret = std::find_first_of(haystack.begin(), haystack.end(),
1064 needles.begin(), needles.end(),
1066 return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
1069 struct AsciiCaseSensitive {
1070 bool operator()(char lhs, char rhs) const {
1076 * Check if two ascii characters are case insensitive equal.
1077 * The difference between the lower/upper case characters are the 6-th bit.
1078 * We also check they are alpha chars, in case of xor = 32.
1080 struct AsciiCaseInsensitive {
1081 bool operator()(char lhs, char rhs) const {
1083 if (k == 0) return true;
1084 if (k != 32) return false;
1086 return (k >= 'a' && k <= 'z');
1091 size_t qfind(const Range<T>& haystack,
1092 const typename Range<T>::value_type& needle) {
1093 auto pos = std::find(haystack.begin(), haystack.end(), needle);
1094 return pos == haystack.end() ? std::string::npos : pos - haystack.data();
1098 size_t rfind(const Range<T>& haystack,
1099 const typename Range<T>::value_type& needle) {
1100 for (auto i = haystack.size(); i-- > 0; ) {
1101 if (haystack[i] == needle) {
1105 return std::string::npos;
1108 // specialization for StringPiece
1110 inline size_t qfind(const Range<const char*>& haystack, const char& needle) {
1111 // memchr expects a not-null pointer, early return if the range is empty.
1112 if (haystack.empty()) {
1113 return std::string::npos;
1115 auto pos = static_cast<const char*>(
1116 ::memchr(haystack.data(), needle, haystack.size()));
1117 return pos == nullptr ? std::string::npos : pos - haystack.data();
1121 inline size_t rfind(const Range<const char*>& haystack, const char& needle) {
1122 // memchr expects a not-null pointer, early return if the range is empty.
1123 if (haystack.empty()) {
1124 return std::string::npos;
1126 auto pos = static_cast<const char*>(
1127 ::memrchr(haystack.data(), needle, haystack.size()));
1128 return pos == nullptr ? std::string::npos : pos - haystack.data();
1131 // specialization for ByteRange
1133 inline size_t qfind(const Range<const unsigned char*>& haystack,
1134 const unsigned char& needle) {
1135 // memchr expects a not-null pointer, early return if the range is empty.
1136 if (haystack.empty()) {
1137 return std::string::npos;
1139 auto pos = static_cast<const unsigned char*>(
1140 ::memchr(haystack.data(), needle, haystack.size()));
1141 return pos == nullptr ? std::string::npos : pos - haystack.data();
1145 inline size_t rfind(const Range<const unsigned char*>& haystack,
1146 const unsigned char& needle) {
1147 // memchr expects a not-null pointer, early return if the range is empty.
1148 if (haystack.empty()) {
1149 return std::string::npos;
1151 auto pos = static_cast<const unsigned char*>(
1152 ::memrchr(haystack.data(), needle, haystack.size()));
1153 return pos == nullptr ? std::string::npos : pos - haystack.data();
1157 size_t qfind_first_of(const Range<T>& haystack,
1158 const Range<T>& needles) {
1159 return qfind_first_of(haystack, needles, AsciiCaseSensitive());
1162 // specialization for StringPiece
1164 inline size_t qfind_first_of(const Range<const char*>& haystack,
1165 const Range<const char*>& needles) {
1166 return detail::qfind_first_byte_of(haystack, needles);
1169 // specialization for ByteRange
1171 inline size_t qfind_first_of(const Range<const unsigned char*>& haystack,
1172 const Range<const unsigned char*>& needles) {
1173 return detail::qfind_first_byte_of(StringPiece(haystack),
1174 StringPiece(needles));
1177 template<class Key, class Enable>
1181 struct hasher<folly::Range<T*>,
1182 typename std::enable_if<std::is_pod<T>::value, void>::type> {
1183 size_t operator()(folly::Range<T*> r) const {
1184 return hash::SpookyHashV2::Hash64(r.begin(), r.size() * sizeof(T), 0);
1189 * Ubiquitous helper template for knowing what's a string
1191 template <class T> struct IsSomeString {
1192 enum { value = std::is_same<T, std::string>::value
1193 || std::is_same<T, fbstring>::value };
1196 } // !namespace folly
1198 #pragma GCC diagnostic pop
1200 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(folly::Range);