#include "StdAfx.h"
#include "fs/ProcessStream.h"
#include "fs/IStreamSource.h"
#include "tl/memory_buffer.h"
#include "tl/narrow_cast.h"

namespace fs
{
static constexpr size_t k_defaultBufferSize = 100 * 1024;


ProcessStreamResult processStream(IStreamSource& i_source, const ProcessDataCallback& i_dataCallback, size_t i_bufferSize)
{
	size_t bufferSize = i_bufferSize;
	if (bufferSize == 0)
		bufferSize = i_source.getPreferredBufferSize();

	if (bufferSize == 0)
		bufferSize = k_defaultBufferSize;

	tl::memory_buffer buffer;
	buffer.resize_uninitialized(bufferSize);

	do
	{
		const uint64_t read = i_source.read(buffer);
		tl::optional<Error> optLastError = i_source.getLastError();
		if (optLastError.has_value())
		{
			return *optLastError;
		}
		if (read == 0)
			return tl::success();

		if (i_dataCallback)
			i_dataCallback({ buffer.data(), tl::narrow<size_t>(read) });
	} while (!i_source.isEOS());

	return tl::success();
}


}
