From 217415226e104bb699f66a85bc4c1fe92df20abb Mon Sep 17 00:00:00 2001 From: Sahan Fernando Date: Thu, 8 Jul 2021 00:58:46 +1000 Subject: [PATCH] AK: Add helper type for serializing structures into buffer --- AK/BinaryBufferWriter.h | 47 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 AK/BinaryBufferWriter.h diff --git a/AK/BinaryBufferWriter.h b/AK/BinaryBufferWriter.h new file mode 100644 index 00000000000..db7ea998de2 --- /dev/null +++ b/AK/BinaryBufferWriter.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2021, Sahan Fernando + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include +#include + +namespace AK { + +class BinaryBufferWriter { +public: + BinaryBufferWriter(Bytes target) + : m_target(target) + { + } + + template + requires(AK::Detail::IsTriviallyConstructible) T& append_structure() + { + VERIFY((reinterpret_cast(m_target.data()) + m_offset) % alignof(T) == 0); + VERIFY(m_offset + sizeof(T) <= m_target.size()); + T* allocated = new (m_target.data() + m_offset) T; + m_offset += sizeof(T); + return *allocated; + } + + void skip_bytes(size_t num_bytes) + { + VERIFY(m_offset + num_bytes <= m_target.size()); + m_offset += num_bytes; + } + + [[nodiscard]] size_t current_offset() const + { + return m_offset; + } + +private: + Bytes m_target; + size_t m_offset { 0 }; +}; + +}