// Copyright (c) 2012-2024 Wojciech Figat. All rights reserved. #pragma once #include "WriteStream.h" #include "Engine/Core/Types/Span.h" /// /// Direct memory writing stream that uses a single allocation buffer. /// class FLAXENGINE_API MemoryWriteStream : public WriteStream { private: byte* _buffer; byte* _position; uint32 _capacity; public: /// /// Initializes a new instance of the class. /// MemoryWriteStream(); /// /// Initializes a new instance of the class. /// /// Initial write buffer capacity (in bytes). MemoryWriteStream(uint32 capacity); /// /// Destructor /// ~MemoryWriteStream(); public: /// /// Gets the pointer to the buffer in memory. /// FORCE_INLINE byte* GetHandle() const { return _buffer; } /// /// Gets the current capacity of the stream. /// FORCE_INLINE uint32 GetCapacity() const { return _capacity; } /// /// Gets current stream length (capacity in bytes). /// FORCE_INLINE uint32 GetLength() const { return _capacity; } /// /// Gets current position in the stream (in bytes). /// FORCE_INLINE uint32 GetPosition() const { return static_cast(_position - _buffer); } /// /// Skips bytes from the target buffer without writing to it. Moves the write pointer in the buffer forward. /// /// The amount of bytes to skip. /// The pointer to the target bytes in memory. void* Move(uint32 bytes); /// /// Skips the data from the target buffer without writing to it. Moves the write pointer in the buffer forward. /// /// The pointer to the data in memory. template FORCE_INLINE T* Move() { return static_cast(Move(sizeof(T))); } /// /// Skips the data from the target buffer without writing to it. Moves the write pointer in the buffer forward. /// /// The amount of items to read. /// The pointer to the data in memory. template FORCE_INLINE T* Move(uint32 count) { return static_cast(Move(sizeof(T) * count)); } public: /// /// Cleanups the buffers, resets the position and allocated the new memory chunk. /// /// Initial write buffer capacity (in bytes). void Reset(uint32 capacity); /// /// Saves current buffer contents to the file. /// /// The file path. /// True if cannot save data, otherwise false. bool SaveToFile(const StringView& path) const; public: // [WriteStream] void Flush() override; void Close() override; uint32 GetLength() override; uint32 GetPosition() override; void SetPosition(uint32 seek) override; void WriteBytes(const void* data, uint32 bytes) override; }; inline Span ToSpan(MemoryWriteStream& stream) { return Span(stream.GetHandle(), (int32)stream.GetPosition()); }