X-Git-Url: https://git.saurik.com/apt.git/blobdiff_plain/8cfd5495e30533e2ab708c8dc875f1c6f29650fd..5ac0f77c5575dc06bfc0db383da984c96ce284b9:/apt-pkg/contrib/string_view.h?ds=sidebyside diff --git a/apt-pkg/contrib/string_view.h b/apt-pkg/contrib/string_view.h index 16f324597..c504edd27 100644 --- a/apt-pkg/contrib/string_view.h +++ b/apt-pkg/contrib/string_view.h @@ -13,6 +13,7 @@ #define APT_STRINGVIEW_H #include #include +#include namespace APT { @@ -23,12 +24,13 @@ namespace APT { * used by APT. It is not meant to be used in programs, only inside the * library for performance critical paths. */ -class StringView { +class APT_HIDDEN StringView { const char *data_; size_t size_; public: static constexpr size_t npos = static_cast(-1); + static_assert(APT::StringView::npos == std::string::npos, "npos values are different"); /* Constructors */ constexpr StringView() : data_(""), size_(0) {} @@ -43,10 +45,15 @@ public: return StringView(data_ + pos, n > (size_ - pos) ? (size_ - pos) : n); } - size_t find(int c, size_t pos=0) const { - if (pos != 0) - return substr(pos).find(c); - + size_t find(int c, size_t pos) const { + if (pos == 0) + return find(c); + size_t const found = substr(pos).find(c); + if (found == npos) + return npos; + return pos + found; + } + size_t find(int c) const { const char *found = static_cast(memchr(data_, c, size_)); if (found == NULL) @@ -55,10 +62,12 @@ public: return found - data_; } - size_t rfind(int c, size_t pos=0) const { - if (pos != 0) - return substr(pos).rfind(c); - + size_t rfind(int c, size_t pos) const { + if (pos == npos) + return rfind(c); + return APT::StringView(data_, pos).rfind(c); + } + size_t rfind(int c) const { const char *found = static_cast(memrchr(data_, c, size_)); if (found == NULL) @@ -103,10 +112,21 @@ public: constexpr size_t length() const { return size_; } }; +/** + * \brief Faster comparison for string views (compare size before data) + * + * Still stable, but faster than the normal ordering. */ +static inline int StringViewCompareFast(StringView a, StringView b) { + if (a.size() != b.size()) + return a.size() - b.size(); + + return memcmp(a.data(), b.data(), a.size()); +} + } inline bool operator ==(const char *other, APT::StringView that); -inline bool operator ==(const char *other, APT::StringView that) { return that.compare(other) == 0; } +inline bool operator ==(const char *other, APT::StringView that) { return that.operator==(other); } #endif