From 0d0554845993da46d751b43c92c04d226250eb1d Mon Sep 17 00:00:00 2001 From: Stenzek Date: Mon, 7 Oct 2024 16:39:19 +1000 Subject: [PATCH] MinizipHelpers: Add ReadZipFileToString() --- src/common/minizip_helpers.h | 44 ++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/src/common/minizip_helpers.h b/src/common/minizip_helpers.h index c07f0cccf..4812c6af7 100644 --- a/src/common/minizip_helpers.h +++ b/src/common/minizip_helpers.h @@ -3,7 +3,9 @@ #pragma once +#include "error.h" #include "file_system.h" + #include "ioapi.h" #include "types.h" #include "unzip.h" @@ -88,4 +90,46 @@ namespace MinizipHelpers { return unzOpen2_64(filename, &funcs); } +[[maybe_unused]] static std::optional ReadZipFileToString(unzFile zf, const char* filename, + bool case_sensitivity, Error* error) +{ + std::optional ret; + + int err = unzLocateFile(zf, filename, case_sensitivity); + if (err != UNZ_OK) + { + Error::SetStringView(error, "File not found."); + return ret; + } + + unz_file_info64 fi; + err = unzGetCurrentFileInfo64(zf, &fi, nullptr, 0, nullptr, 0, nullptr, 0); + if (err != UNZ_OK || fi.uncompressed_size > std::numeric_limits::max()) [[unlikely]] + { + Error::SetStringFmt(error, "Failed to get file size: {}", err); + return ret; + } + + err = unzOpenCurrentFile(zf); + if (err != UNZ_OK) [[unlikely]] + { + Error::SetStringFmt(error, "Failed to open file: {}", err); + return ret; + } + + ret = std::string(); + ret->resize(static_cast(fi.uncompressed_size)); + if (!ret->empty()) + { + const int size = unzReadCurrentFile(zf, ret->data(), static_cast(ret->size())); + if (size != static_cast(ret->size())) + { + Error::SetStringFmt(error, "Only read {} of {} bytes.", size, ret->size()); + ret.reset(); + } + } + + return ret; +} + } // namespace MinizipHelpers \ No newline at end of file