// Copyright (c) 2012-2023 Wojciech Figat. All rights reserved.
#pragma once
#include "WriteStream.h"
///
/// Implementation of of the stream that can be used for fast data writing to the memory.
///
class FLAXENGINE_API MemoryWriteStream : public WriteStream
{
private:
byte* _buffer;
byte* _position;
uint32 _capacity;
public:
MemoryWriteStream();
///
/// Init
///
/// Initial write buffer capacity (in bytes).
MemoryWriteStream(uint32 capacity);
///
/// Destructor
///
~MemoryWriteStream();
public:
///
/// Gets buffer handle
///
/// Pointer to the buffer in memory
FORCE_INLINE byte* GetHandle() const
{
return _buffer;
}
///
/// Gets current capacity of the memory stream
///
/// Stream capacity in bytes
FORCE_INLINE uint32 GetCapacity() const
{
return _capacity;
}
///
/// Gets current stream length (capacity in bytes)
///
/// Stream length in bytes
FORCE_INLINE uint32 GetLength() const
{
return _capacity;
}
///
/// Gets current position in the stream (in bytes)
///
/// Stream position 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
///
/// Filepath
/// 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;
};