MemSpan
Synopsis
#include <ts/MemSpan.h>
MemSpan
is a view on a contiguous section of writeable memory. A view does not own the memory and neither allocates nor de-allocates. The memory in the view is always owned by some other container and it is the responsibility of the code to make sure the lifetime of the view is no more than that of the owning container 1.
Description
A MemSpan
is generally constructed on either an array or an allocated buffer. This allows the buffer to be passed around with intrinsic length information. The buffer can also be treated as an array of varying types, which makes working with serialized data much easier.
Reference
class MemSpan
A span of writable memory. Because this is a chunk of memory, conceptually delimited by start and end pointers, the sizing type is ptrdiff_t
so that all of the sizing is consistent with differences between pointers. The memory is owned by some other object and that object must maintain the memory as long as the span references it.
MemSpan
(void *ptr, ptrdiff_t size)Construct a view starting at ptr for size bytes.
void *
data
() constReturn a pointer to the first byte of the span.
ptrdiff_t
size
() constReturn the size of the span.
bool
operator==
(MemSpan const &that) constCheck the equality of two spans, which are equal if they contain the same number of bytes of the same values.
bool
is_same
(MemSpan const &that) constCheck if that is the same span as this, that is the spans contain the exact same bytes.
template<typename
V
>
Vat
(ptrdiff_t n) constReturn a value of type V as if the span were are array of type V.
template<typename
V
>
V *ptr
(ptrdiff_t n) constReturn a pointer to a value of type V as if the span were are array of type V.
MemSpan
prefix
(ptrdiff_t n) constReturn a new instance that contains the first n bytes of the current span. If n is larger than the number of bytes in the span, only that many bytes are returned.
MemSpan &
remove_prefix
(ptrdiff_t n)Remove the first n bytes of the span. If n is more than the number of bytes in the span the result is an empty span. A reference to the instance is returned.
Footnotes
Strong caution must be used with containers such as std::vector
or std::string
because the lifetime of the memory can be much less than the lifetime of the container. In particular, adding or removing any element from a std::vector
can cause a re-allocation, invalidating any view of the original memory. In general views should be treated like iterators, suitable for passing to nested function calls but not for storing.