#pragma once

#include "fs/IMapSink.h"
#include "fs/Error.h"
#include "tl/memory_buffer.h"
#include "fs/Api.h"

namespace fs
{
//////////////////////////////////////////////////////////////////////////

class MemorySource;

class FS_API MemorySink final : public IMapSink
{
public:
	MemorySink(size_t reserve = BUFSIZ);
	explicit MemorySink(tl::memory_buffer&& buffer);
	~MemorySink() override = default;

	MemorySink(MemorySink&& sink) = default;
	MemorySink& operator=(MemorySink&& sink) = default;

	tl::optional<Error> getLastError() const override;

	size_t write(tl::span<const uint8_t> data) override;
	void seekBeg(uint64_t offset) override;
	void seekRel(int64_t offset) override;
	uint64_t tell() const override;
	uint64_t getSize() const override;
	tl::span<const uint8_t> getDataView() const;
	tl::memory_buffer getDataCopy() const;
	tl::memory_buffer getDataMove();
	void clear();
	void swap(MemorySource& source);
	void reserve(size_t capacity);
	void shrinkToFit();

	tl::span<uint8_t> map(size_t size) override;

	size_t getPreferredBufferSize() const override;

	//this applies OVER the current size
	void preReserve(size_t size);

	static tl::memory_buffer extractData(MemorySink sink);

private:
	size_t m_offset = 0;
	tl::memory_buffer m_data;
	mutable tl::optional<Error> m_optLastError;
};

//////////////////////////////////////////////////////////////////////////
}

