Torch
Loading...
Searching...
No Matches
BKResource.h
1#pragma once
2
3#include "endianness.h"
4
5#include <cstddef>
6#include <cstdint>
7#include <stdexcept>
8#include <vector>
9
10namespace BK64 {
11
12// Reads the fields after a resource's 64-byte header, swapping when the header names the other byte order. Throws
13// when it runs out.
14class ResourceReader {
15 public:
16 explicit ResourceReader(const std::vector<uint8_t>& bytes) : mBytes(bytes) {
17 if (bytes.size() < 0x40) {
18 throw std::runtime_error("the resource is under 64 bytes");
19 }
20 mSwap = (bytes[0] == (uint8_t)Torch::Endianness::Big) != (Torch::Endianness::Native == Torch::Endianness::Big);
21 }
22
23 template <typename T> void Read(T& value) {
24 if (mBytes.size() - mAt < sizeof(T)) {
25 throw std::runtime_error("the resource ends early");
26 }
27 for (size_t i = 0; i < sizeof(T); i++) {
28 ((uint8_t*)&value)[mSwap ? sizeof(T) - 1 - i : i] = mBytes[mAt + i];
29 }
30 mAt += sizeof(T);
31 }
32
33 template <typename T> T Read() {
34 T value;
35 Read(value);
36 return value;
37 }
38
39 template <typename T> void ReadArray(T* values, size_t count) {
40 for (size_t i = 0; i < count; i++) {
41 Read(values[i]);
42 }
43 }
44
45 std::vector<uint8_t> Bytes(size_t size) {
46 if (mBytes.size() - mAt < size) {
47 throw std::runtime_error("the resource ends early");
48 }
49 mAt += size;
50 return std::vector<uint8_t>(mBytes.begin() + (mAt - size), mBytes.begin() + mAt);
51 }
52
53 private:
54 const std::vector<uint8_t>& mBytes;
55 size_t mAt = 0x40;
56 bool mSwap = false;
57};
58
59} // namespace BK64