From f2a20a0a800e879b0e52681b7f9b8829047c55a7 Mon Sep 17 00:00:00 2001 From: Max Kellermann Date: Sun, 15 Dec 2013 23:01:01 +0100 Subject: util/WritableBuffer: add cast methods --- src/util/WritableBuffer.hxx | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/util/WritableBuffer.hxx b/src/util/WritableBuffer.hxx index 1b37b56cb..7267813f5 100644 --- a/src/util/WritableBuffer.hxx +++ b/src/util/WritableBuffer.hxx @@ -32,7 +32,11 @@ #include "Compiler.h" -#include +#include + +#ifndef NDEBUG +#include +#endif /** * A reference to a memory area that is writable. @@ -52,6 +56,8 @@ struct WritableBuffer { WritableBuffer() = default; + constexpr WritableBuffer(std::nullptr_t):data(nullptr), size(0) {} + constexpr WritableBuffer(pointer_type _data, size_type _size) :data(_data), size(_size) {} @@ -59,6 +65,29 @@ struct WritableBuffer { return { nullptr, 0 }; } + /** + * Cast a WritableBuffer to a WritableBuffer. A "void" + * buffer records its size in bytes, and when casting to "T", + * the assertion below ensures that the size is a multiple of + * sizeof(T). + */ +#ifdef NDEBUG + constexpr +#endif + static WritableBuffer FromVoid(WritableBuffer other) { + static_assert(sizeof(T) > 0, "Empty base type"); +#ifndef NDEBUG + assert(other.size % sizeof(T) == 0); +#endif + return WritableBuffer(pointer_type(other.data), + other.size / sizeof(T)); + } + + constexpr WritableBuffer ToVoid() const { + static_assert(sizeof(T) > 0, "Empty base type"); + return WritableBuffer(data, size * sizeof(T)); + } + constexpr bool IsNull() const { return data == nullptr; } -- cgit v1.2.3