Skip to content

Commit

Permalink
Span front() and back() methods and SpanPopBack function backport
Browse files Browse the repository at this point in the history
from btc@2b0fcff7f26d59fed4bcafd1602325122a206c67
  • Loading branch information
furszy committed Jul 6, 2021
1 parent 1b2e7c8 commit f36042f
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/span.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include <type_traits>
#include <cstddef>
#include <algorithm>
#include <assert.h>

/** A Span is an object that can refer to a contiguous sequence of objects.
*
Expand All @@ -27,6 +28,8 @@ class Span
constexpr C* data() const noexcept { return m_data; }
constexpr C* begin() const noexcept { return m_data; }
constexpr C* end() const noexcept { return m_data + m_size; }
constexpr C& front() const noexcept { return m_data[0]; }
constexpr C& back() const noexcept { return m_data[m_size - 1]; }
constexpr std::ptrdiff_t size() const noexcept { return m_size; }
constexpr C& operator[](std::ptrdiff_t pos) const noexcept { return m_data[pos]; }

Expand Down Expand Up @@ -57,4 +60,15 @@ constexpr Span<A> MakeSpan(A (&a)[N]) { return Span<A>(a, N); }
template<typename V>
constexpr Span<typename std::remove_pointer<decltype(std::declval<V>().data())>::type> MakeSpan(V& v) { return Span<typename std::remove_pointer<decltype(std::declval<V>().data())>::type>(v.data(), v.size()); }

/** Pop the last element off a span, and return a reference to that element. */
template <typename T>
T& SpanPopBack(Span<T>& span)
{
size_t size = span.size();
assert(size > 0);
T& back = span[size - 1];
span = Span<T>(span.data(), size - 1);
return back;
}

#endif

0 comments on commit f36042f

Please sign in to comment.