| 1 | // Copyright 2023 Dolphin Emulator Project |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | |
| 4 | #include "DiscIO/SplitFileBlob.h" |
| 5 | |
| 6 | #include <memory> |
| 7 | #include <string_view> |
| 8 | #include <vector> |
| 9 | |
| 10 | #include <fmt/format.h> |
| 11 | |
| 12 | namespace DiscIO |
| 13 | { |
| 14 | SplitPlainFileReader::SplitPlainFileReader(std::vector<SingleFile> files) |
| 15 | : m_files(std::move(files)) |
| 16 | { |
| 17 | m_size = 0; |
| 18 | for (const auto& f : m_files) |
| 19 | m_size += f.size; |
| 20 | } |
| 21 | |
| 22 | std::unique_ptr<SplitPlainFileReader> SplitPlainFileReader::Create(std::string_view first_file_path) |
| 23 | { |
| 24 | constexpr std::string_view part0_iso = ".part0.iso"; |
| 25 | if (!first_file_path.ends_with(part0_iso)) |
| 26 | return nullptr; |
| 27 | |
| 28 | const std::string_view base_path = |
| 29 | first_file_path.substr(0, first_file_path.size() - part0_iso.size()); |
| 30 | std::vector<SingleFile> files; |
| 31 | size_t index = 0; |
| 32 | u64 offset = 0; |
| 33 | while (true) |
| 34 | { |
| 35 | File::DirectIOFile f(fmt::format("{}.part{}.iso", base_path, index), File::AccessMode::Read); |
| 36 | if (!f.IsOpen()) |
| 37 | break; |
| 38 | const u64 size = f.GetSize(); |
| 39 | if (size == 0) |
| 40 | return nullptr; |
| 41 | files.emplace_back(SingleFile{std::move(f), offset, size}); |
| 42 | offset += size; |
| 43 | ++index; |
| 44 | } |
| 45 | |
| 46 | if (files.size() < 2) |
| 47 | return nullptr; |
| 48 | |
| 49 | files.shrink_to_fit(); |
| 50 | return std::unique_ptr<SplitPlainFileReader>(new SplitPlainFileReader(std::move(files))); |
| 51 | } |
| 52 | |
| 53 | std::unique_ptr<BlobReader> SplitPlainFileReader::CopyReader() const |
| 54 | { |
| 55 | return std::unique_ptr<SplitPlainFileReader>{new SplitPlainFileReader(m_files)}; |
| 56 | } |
| 57 | |
| 58 | bool SplitPlainFileReader::Read(u64 offset, u64 nbytes, u8* out_ptr) |
| 59 | { |
| 60 | if (offset >= m_size) |
| 61 | return false; |
| 62 | |
| 63 | u64 current_offset = offset; |
| 64 | u64 rest = nbytes; |
| 65 | u8* out = out_ptr; |
| 66 | for (auto& file : m_files) |
| 67 | { |
| 68 | if (current_offset >= file.offset && current_offset < file.offset + file.size) |
| 69 | { |
| 70 | auto& f = file.file; |
| 71 | const u64 offset_in_file = current_offset - file.offset; |
| 72 | const u64 current_read = std::min(file.size - offset_in_file, rest); |
| 73 | if (!f.OffsetRead(offset_in_file, out, current_read)) |
| 74 | return false; |
| 75 | |
| 76 | rest -= current_read; |
| 77 | if (rest == 0) |
| 78 | return true; |
| 79 | current_offset += current_read; |
| 80 | out += current_read; |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | return rest == 0; |
| 85 | } |
| 86 | } // namespace DiscIO |