#include "memory/dl_stream_output.h" #include #include #include "io/dl_log.h" #include "memory/dl_memory.h" #include "io/dl_file.h" namespace dl { constexpr size_t SIZE_STREAM_OUTPUT_BUFFER_DEFAULT = 1024; StreamOutput::StreamOutput() : _head{ 0 }, _delete{ true } { } StreamOutput::~StreamOutput() { assert(_delete); /*if (_delete) free(_buffer);*/ } const std::byte* StreamOutput::GetData() { return _buf.data(); } void StreamOutput::Write(const void* data, size_t byte_count) { size_t result_head = _head + byte_count; if (result_head > _buf.size()) { _buf.resize(result_head); } memcpy(_buf.data() + _head, data, byte_count); _head = result_head; } void StreamOutput::Fill(int val, size_t byte_count) { size_t result_head = _head + byte_count; if (result_head > _buf.size()) { _buf.resize(result_head); } memset(_buf.data() + _head, val, byte_count); _head = result_head; } bool StreamOutput::Save(std::string_view path_name, bool compress) { std::ofstream ofs = File::Set(path_name, true); //std::ofstream ofs; //ofs.open(std::string{ path_name }, std::ofstream::binary | std::ofstream::out | std::ofstream::trunc); if (!ofs.is_open()) { log_err("文件打开(创建)失败:{}", path_name); return false; } if (compress) { Buffer unzip = { _buf.begin(), _buf.begin() + _head }; Buffer buf = Memory::CompressLz4(unzip); ofs.write((char*)buf.data(), buf.size()); } else ofs.write((char*)_buf.data(), _head); return true; } void StreamOutput::Clear() { _head = 0; } void StreamOutput::SetPos(size_t pos) { if (pos > _buf.size()) { _buf.resize(pos); } _head = pos; } void StreamOutput::Compress(Memory::CompressMode mode) { if (mode == Memory::E_NONE) return; Buffer src = { _buf.begin(), _buf.begin() + _head }; Buffer buf; if(mode == Memory::E_LZ4) buf = Memory::CompressLz4(src); #ifndef DL_DISABLE_ZLIB else if (mode == Memory::E_ZIP) buf = Memory::CompressZip(src); #endif else { log_err("无效的压缩模式:", (int)mode); } _buf = buf; _head = buf.size(); } }