136 lines
1.8 KiB
C++
136 lines
1.8 KiB
C++
#include "dl_stream_input.h"
|
|
|
|
#include <cassert>
|
|
|
|
#include "io/dl_log.h"
|
|
#include "memory/dl_buffer.h"
|
|
|
|
namespace dl
|
|
{
|
|
|
|
StreamInput::StreamInput()
|
|
{
|
|
_buffer = NULL;
|
|
_head = 0;
|
|
_size = 0;
|
|
|
|
}
|
|
|
|
StreamInput::~StreamInput()
|
|
{
|
|
free(_buffer);
|
|
}
|
|
|
|
const std::byte* StreamInput::GetBuffer()
|
|
{
|
|
return _buffer;
|
|
}
|
|
|
|
bool StreamInput::Read(void* data, size_t byte_count)
|
|
{
|
|
size_t result_head = _head + byte_count;
|
|
|
|
if (result_head > _size)
|
|
{
|
|
log_warn("Read超出了buffer大小!");
|
|
_head = _size;
|
|
return false;
|
|
}
|
|
|
|
memcpy(data, _buffer + _head, byte_count);
|
|
|
|
_head = result_head;
|
|
return true;
|
|
}
|
|
|
|
bool StreamInput::LoadFromFile(std::string_view path_name, bool decompress, size_t length)
|
|
{
|
|
ifstream ifs = File::GetFile(path_name;
|
|
if (!g_file->GetFile(path_name, ifs, true))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
//有可能已经加载过了
|
|
free(_buffer);
|
|
|
|
if (decompress || length == 0)
|
|
{
|
|
ifs.seekg(0, std::ios::end);
|
|
_size = (size_t)ifs.tellg();
|
|
}
|
|
else
|
|
{
|
|
ifs.seekg(length, std::ios::beg);
|
|
_size = length;
|
|
}
|
|
|
|
|
|
ifs.seekg(0);
|
|
|
|
|
|
_buffer = (byte*)malloc(_size);
|
|
ifs.read((char*)_buffer, _size);
|
|
|
|
ifs.close();
|
|
|
|
_head = 0;
|
|
|
|
if (decompress)
|
|
{
|
|
Buffer zip = Create{ _buffer, _size };
|
|
Buffer buf = Memory::DecompressLz4(zip);
|
|
free(_buffer);
|
|
_buffer = buf._p;
|
|
_size = buf._size;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
void StreamInput::LoadFromMemory(Buffer buf, bool decompress)
|
|
{
|
|
//有可能已经加载过了
|
|
free(_buffer);
|
|
|
|
if (decompress)
|
|
{
|
|
Buffer unzip = Memory::DecompressLz4(buf);
|
|
_buffer = unzip._p;
|
|
_size = unzip._size;
|
|
}
|
|
else
|
|
{
|
|
_size = buf._size;
|
|
_buffer = (byte*)malloc(_size);
|
|
|
|
memcpy(_buffer, buf._p, buf._size);
|
|
}
|
|
_head = 0;
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
void StreamInput::SetPos(size_t pos)
|
|
{
|
|
if (pos > _size)
|
|
{
|
|
log_err("SetPos超出了buffer大小!");
|
|
return;
|
|
}
|
|
_head = pos;
|
|
}
|
|
|
|
|
|
bool StreamInput::IsEnd()
|
|
{
|
|
assert(_head <= _size);
|
|
|
|
return _head == _size;
|
|
}
|
|
|
|
}
|