From f3b77386610d011885f5fc088040f8521719fd6a Mon Sep 17 00:00:00 2001 From: Zang MingJie Date: Tue, 15 Jun 2021 23:26:20 +0800 Subject: [PATCH] Make span more C++20 std::span like (#7642) * Make span more C++20 std::span like The span itself doesn't qualify const-ness of the object. The const-ness can be derived from template argument, by using: * Span * Span * Apply suggestions from code review Co-authored-by: Boris Zbarsky Co-authored-by: Boris Zbarsky --- src/lib/support/Span.h | 32 +++++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/src/lib/support/Span.h b/src/lib/support/Span.h index 5e7b46d79ad533..bd1e7cdd72219d 100644 --- a/src/lib/support/Span.h +++ b/src/lib/support/Span.h @@ -21,6 +21,8 @@ #include #include +#include + namespace chip { /** @@ -31,13 +33,15 @@ template class Span { public: + using pointer = T *; + constexpr Span() : mDataBuf(nullptr), mDataLen(0) {} - constexpr Span(const T * databuf, size_t datalen) : mDataBuf(databuf), mDataLen(datalen) {} + constexpr Span(pointer databuf, size_t datalen) : mDataBuf(databuf), mDataLen(datalen) {} template - constexpr explicit Span(const T (&databuf)[N]) : Span(databuf, N) + constexpr explicit Span(T (&databuf)[N]) : Span(databuf, N) {} - const T * data() const { return mDataBuf; } + constexpr pointer data() const { return mDataBuf; } size_t size() const { return mDataLen; } bool empty() const { return size() == 0; } bool data_equal(const Span & other) const @@ -45,8 +49,15 @@ class Span return (size() == other.size()) && (empty() || (memcmp(data(), other.data(), size() * sizeof(T)) == 0)); } + Span SubSpan(size_t offset, size_t length) const + { + VerifyOrDie(offset <= mDataLen); + VerifyOrDie(length <= mDataLen - offset); + return Span(mDataBuf + offset, length); + } + private: - const T * mDataBuf; + pointer mDataBuf; size_t mDataLen; }; @@ -54,10 +65,12 @@ template class FixedSpan { public: + using pointer = T *; + constexpr FixedSpan() : mDataBuf(nullptr) {} - constexpr explicit FixedSpan(const T * databuf) : mDataBuf(databuf) {} + constexpr explicit FixedSpan(pointer databuf) : mDataBuf(databuf) {} - const T * data() const { return mDataBuf; } + constexpr pointer data() const { return mDataBuf; } size_t size() const { return N; } bool empty() const { return data() == nullptr; } bool data_equal(const FixedSpan & other) const @@ -67,11 +80,12 @@ class FixedSpan } private: - const T * mDataBuf; + pointer mDataBuf; }; -using ByteSpan = Span; +using ByteSpan = Span; +using MutableByteSpan = Span; template -using FixedByteSpan = FixedSpan; +using FixedByteSpan = FixedSpan; } // namespace chip