Skip to content

Commit

Permalink
Make span more C++20 std::span like (#7642)
Browse files Browse the repository at this point in the history
* 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<uint8_t>
* Span<const uint8_t>

* Apply suggestions from code review

Co-authored-by: Boris Zbarsky <bzbarsky@apple.com>

Co-authored-by: Boris Zbarsky <bzbarsky@apple.com>
  • Loading branch information
2 people authored and pull[bot] committed Jul 9, 2021
1 parent 4c9a384 commit 2499776
Showing 1 changed file with 23 additions and 9 deletions.
32 changes: 23 additions & 9 deletions src/lib/support/Span.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
#include <cstdlib>
#include <string.h>

#include <support/CodeUtils.h>

namespace chip {

/**
Expand All @@ -31,33 +33,44 @@ template <class T>
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 <size_t N>
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
{
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;
};

template <class T, size_t N>
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
Expand All @@ -67,11 +80,12 @@ class FixedSpan
}

private:
const T * mDataBuf;
pointer mDataBuf;
};

using ByteSpan = Span<uint8_t>;
using ByteSpan = Span<const uint8_t>;
using MutableByteSpan = Span<uint8_t>;
template <size_t N>
using FixedByteSpan = FixedSpan<uint8_t, N>;
using FixedByteSpan = FixedSpan<const uint8_t, N>;

} // namespace chip

0 comments on commit 2499776

Please sign in to comment.