1 // Copyright 2019 Dolphin Emulator Project
2 // Licensed under GPLv2+
3 // Refer to the license.txt file included.
4 
5 #pragma once
6 
7 #include <algorithm>
8 
9 #include <unzip.h>
10 
11 #include "Common/CommonTypes.h"
12 #include "Common/ScopeGuard.h"
13 
14 namespace Common
15 {
16 // Reads all of the current file. destination must be big enough to fit the whole file.
17 template <typename ContiguousContainer>
ReadFileFromZip(unzFile file,ContiguousContainer * destination)18 bool ReadFileFromZip(unzFile file, ContiguousContainer* destination)
19 {
20   const u32 MAX_BUFFER_SIZE = 65535;
21 
22   if (unzOpenCurrentFile(file) != UNZ_OK)
23     return false;
24 
25   Common::ScopeGuard guard{[&] { unzCloseCurrentFile(file); }};
26 
27   u32 bytes_to_go = static_cast<u32>(destination->size());
28   while (bytes_to_go > 0)
29   {
30     const int bytes_read =
31         unzReadCurrentFile(file, &(*destination)[destination->size() - bytes_to_go],
32                            std::min(bytes_to_go, MAX_BUFFER_SIZE));
33 
34     if (bytes_read < 0)
35       return false;
36 
37     bytes_to_go -= static_cast<u32>(bytes_read);
38   }
39 
40   return true;
41 }
42 }  // namespace Common
43