playground-sdk/core/pfp.cpp

52 lines
1.9 KiB
C++

#include "core/pfp.h"
#include <cstring>
namespace playground {
namespace {
class PfpVfs : public Vfs {
public:
struct Entry { uint32_t off, size; };
Bytes data;
std::vector<std::string> names;
std::vector<Entry> entries;
const std::vector<std::string>& list() const override { return names; }
bool read(const std::string& path, Bytes& out) const override {
std::string key = normalizePath(path);
for (size_t i = 0; i < names.size(); i++) {
if (normalizePath(names[i]) == key) {
out.assign(data.begin() + entries[i].off, data.begin() + entries[i].off + entries[i].size);
return true;
}
}
return false;
}
};
uint32_t rd32(const uint8_t* p) { return p[0] | (p[1] << 8) | (p[2] << 16) | (uint32_t(p[3]) << 24); }
} // namespace
std::unique_ptr<Vfs> openPfp(const std::string& file, std::string* err) {
auto v = std::make_unique<PfpVfs>();
if (!readFile(file, v->data)) { if (err) *err = "cannot read " + file; return nullptr; }
const Bytes& d = v->data;
if (d.size() < 8 || std::memcmp(d.data(), "PFPK", 4) != 0) { if (err) *err = "not a PFPK archive"; return nullptr; }
uint32_t n = rd32(d.data() + 4);
size_t p = 8;
for (uint32_t i = 0; i < n; i++) {
if (p >= d.size()) { if (err) *err = "PFPK table truncated"; return nullptr; }
size_t l = d[p++];
if (p + l + 8 > d.size()) { if (err) *err = "PFPK table truncated"; return nullptr; }
std::string name(reinterpret_cast<const char*>(&d[p]), l);
p += l;
PfpVfs::Entry e{rd32(&d[p]), rd32(&d[p + 4])};
p += 8;
if (size_t(e.off) + e.size > d.size()) { if (err) *err = "PFPK entry out of range: " + name; return nullptr; }
v->names.push_back(name);
v->entries.push_back(e);
}
return v;
}
} // namespace playground