summaryrefslogtreecommitdiff
path: root/src/factories/bk64/BKAssetTable.h
blob: a6d580ef6bbe9f0efd9b8deff75bc5078349bd73 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#pragma once

#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <vector>

namespace BK64 {

class SlotSizer {
  public:
    SlotSizer(const std::vector<uint32_t>& offsets, uint32_t dataStart, size_t romSize)
        : mStray(offsets.size(), false), mDataStart(dataStart), mRomSize(romSize) {
        mBoundaries.reserve(offsets.size());
        uint32_t high = 0;
        for (size_t i = 0; i < offsets.size(); i++) {
            if (offsets[i] < high) {
                mStray[i] = true;
                mStrayCount++;
                continue;
            }
            high = offsets[i];
            mBoundaries.push_back(offsets[i]);
        }
        std::sort(mBoundaries.begin(), mBoundaries.end());
        mBoundaries.erase(std::unique(mBoundaries.begin(), mBoundaries.end()), mBoundaries.end());
        mRegionEnd = mBoundaries.empty() ? 0 : mBoundaries.back();
    }

    uint32_t operator()(uint32_t off) const {
        if (off >= mRegionEnd) {
            return 0;
        }
        const auto next = std::upper_bound(mBoundaries.begin(), mBoundaries.end(), off);
        const uint32_t end = std::min(next != mBoundaries.end() ? *next : mRegionEnd, mRegionEnd);
        if (end <= off) {
            return 0;
        }
        const uint64_t start = static_cast<uint64_t>(mDataStart) + off;
        if (start >= mRomSize) {
            return 0;
        }
        return static_cast<uint32_t>(std::min<uint64_t>(end - off, mRomSize - start));
    }

    bool IsStray(size_t index) const {
        return index < mStray.size() && mStray[index];
    }

    size_t StrayCount() const {
        return mStrayCount;
    }

    uint32_t RegionEnd() const {
        return mRegionEnd;
    }

  private:
    std::vector<uint32_t> mBoundaries;
    std::vector<bool> mStray;
    size_t mStrayCount = 0;
    uint32_t mRegionEnd = 0;
    uint32_t mDataStart;
    size_t mRomSize;
};

} // namespace BK64