65 lines
2.8 KiB
C++
65 lines
2.8 KiB
C++
#pragma once
|
|
#include <cstdio>
|
|
#include <cstdint>
|
|
#include <mutex>
|
|
#include <string>
|
|
#include <unordered_map>
|
|
#include <vector>
|
|
|
|
namespace mt_host {
|
|
// MTHD v1. Reject incomplete indices and out-of-file payloads before replacing
|
|
// any original UI texture. Assets are immutable after startup.
|
|
class HdUiArchive {
|
|
public:
|
|
~HdUiArchive() { if (file_) std::fclose(file_); }
|
|
bool open(const std::string& path) {
|
|
if (file_) return false;
|
|
file_ = std::fopen(path.c_str(), "rb");
|
|
if (!file_) return false;
|
|
if (std::fseek(file_, 0, SEEK_END) != 0) return fail();
|
|
const long length = std::ftell(file_);
|
|
if (length < 12 || std::fseek(file_, 0, SEEK_SET) != 0) return fail();
|
|
unsigned char header[12];
|
|
if (!read_bytes(header, 12) || std::string(reinterpret_cast<char*>(header),4) != "MTHD" ||
|
|
u32(header+4) != 1) return fail();
|
|
const auto count = u32(header+8);
|
|
if (!count || count > 100000 || count > std::uint64_t(length-12)/11) return fail();
|
|
for (std::uint32_t i=0; i<count; ++i) {
|
|
unsigned char size[2], range[8];
|
|
if (!read_bytes(size,2)) return fail();
|
|
const unsigned n = size[0] | (unsigned(size[1])<<8);
|
|
if (!n || n > 4096) return fail();
|
|
std::string name(n,'\0');
|
|
if (!read_bytes(name.data(),n) || !read_bytes(range,8)) return fail();
|
|
const auto offset=u32(range), bytes=u32(range+4);
|
|
if (!bytes || std::uint64_t(offset)+bytes > std::uint64_t(length) ||
|
|
!entries_.emplace(std::move(name),std::make_pair(offset,bytes)).second) return fail();
|
|
}
|
|
const long end = std::ftell(file_);
|
|
for (const auto& [name, range] : entries_)
|
|
if (range.first < std::uint64_t(end)) return fail();
|
|
return true;
|
|
}
|
|
std::size_t size() const { return entries_.size(); }
|
|
bool read(const std::string& name, std::vector<std::uint8_t>& out) {
|
|
const auto it=entries_.find(name);
|
|
if (!file_ || it==entries_.end()) return false;
|
|
std::lock_guard<std::mutex> lock(mutex_);
|
|
out.resize(it->second.second);
|
|
if (std::fseek(file_,long(it->second.first),SEEK_SET)==0 && read_bytes(out.data(),out.size())) return true;
|
|
out.clear();
|
|
return false;
|
|
}
|
|
private:
|
|
static std::uint32_t u32(const unsigned char* p) {
|
|
return std::uint32_t(p[0]) | (std::uint32_t(p[1])<<8) |
|
|
(std::uint32_t(p[2])<<16) | (std::uint32_t(p[3])<<24);
|
|
}
|
|
bool read_bytes(void* p,std::size_t n) { return std::fread(p,1,n,file_)==n; }
|
|
bool fail() { std::fclose(file_); file_=nullptr; entries_.clear(); return false; }
|
|
std::FILE* file_=nullptr;
|
|
std::mutex mutex_;
|
|
std::unordered_map<std::string,std::pair<std::uint32_t,std::uint32_t>> entries_;
|
|
};
|
|
} // namespace mt_host
|