summaryrefslogtreecommitdiff
path: root/src/KingSystem/Utils/Byaml/ByamlHashIter.cpp
blob: edce10eed991a9b2e2825d5e65ac5911847092d7 (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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include "KingSystem/Utils/Byaml/ByamlHashIter.h"
#include "KingSystem/Utils/Byaml/Byaml.h"
#include "KingSystem/Utils/Byaml/ByamlData.h"
#include "KingSystem/Utils/Byaml/ByamlLocal.h"

namespace al {

ByamlHashIter::ByamlHashIter(const u8* data) {
    mData = data;
}

s32 ByamlHashIter::getSize() const {
    if (!mData) {
        return 0;
    }

    return ByamlLocalUtil::getContainerSize(mData);
}

const ByamlHashPair* ByamlHashIter::getPairTable() const {
    if (!mData) {
        return nullptr;
    }

    return reinterpret_cast<const ByamlHashPair*>(&mData[mTableOffset]);
}

bool ByamlHashIter::getDataByIndex(ByamlData* data, s32 index) const {
    if (!mData) {
        return false;
    }

    if (ByamlLocalUtil::getContainerSize(mData) == 0) {
        return false;
    }

    const ByamlHashPair* pair_table = getPairTable();
    const ByamlHashPair* pair = &pair_table[index];
    if (!pair)  // This seems wrong, this can never be null?
    {
        return false;
    }

    data->set(pair);

    return true;
}

bool ByamlHashIter::getDataByKey(ByamlData* data, s32 key_index) const {
    if (getSize() == 0) {
        return false;
    }

    const ByamlHashPair* pair = findPair(key_index);
    if (!pair) {
        return false;
    }

    data->set(pair);
    return true;
}

const ByamlHashPair* ByamlHashIter::findPair(s32 key_index) const {
    const ByamlHashPair* pair_table = getPairTable();
    if (!pair_table) {
        return nullptr;
    }

    if (ByamlLocalUtil::getContainerSize(mData) == 0) {
        return nullptr;
    }

    // Binary Search
    s32 start = 0;
    s32 end = getSize();
    s32 index;
    const ByamlHashPair* pair;
    while (true) {
        if (start >= end) {
            return nullptr;
        }

        index = (start + end) / 2;
        pair = &pair_table[index];
        s32 result = key_index - pair->getKey();
        if (result == 0)
            break;
        if (result > 0)
            start = index + 1;
        else if (result < 0)
            end = index;
    }

    return pair;
}

const ByamlHashPair* ByamlHashIter::getPairByIndex(s32 index) const {
    if (index < 0) {
        return nullptr;
    }

    if (getSize() <= index) {
        return nullptr;
    }

    const ByamlHashPair* pair_table = getPairTable();
    return pair_table + index;
}

}  // namespace al