Blame view

d2stat.c 1.91 KB
Imanol-Mikel Barba Sabariego authored
1
2
3
4
5
#include "d2stat.h"

#include <stdio.h>
#include <string.h>
6
7
#define readBits(data, start, size) ((*((uint64_t*) &data[(start) / 8]) >> ((start) & 7)) & ((1 << (size)) - 1))
Imanol-Mikel Barba Sabariego authored
8
9
10
11
12
13
// Internal function, gives the offset ***IN BITS, NOT BYTES*** of the specified stat
unsigned long long int _searchStat(D2S_STAT stat, void* charData, size_t dataLen) {
    if(!strncmp(charData, D2S_STAT_HEADER, D2S_STAT_HEADER_LENGTH)) {
        fprintf(stderr,"libd2char error: Stat header not present in charData\n");
        return 0;
    }
14
15
16
    unsigned long long int offset = D2S_STAT_HEADER_LENGTH * 8;
    while(offset < (dataLen * 8)) {
        uint64_t statID = readBits(charData, offset, D2S_STAT_IDENTIFIER_BIT_LENGTH);
Imanol-Mikel Barba Sabariego authored
17
18
19
        if(statID == D2S_STAT_FOOTER) {
            break;
        } else if(statID == stat) {
20
            return offset + D2S_STAT_IDENTIFIER_BIT_LENGTH;
Imanol-Mikel Barba Sabariego authored
21
        }
22
        offset += D2S_STAT_IDENTIFIER_BIT_LENGTH + statCost[statID];
Imanol-Mikel Barba Sabariego authored
23
24
25
26
27
28
29
30
31
32
    }
    return 0;
}

int getStat(D2S_STAT stat, unsigned int* value, void* charData, size_t dataLen) {
    unsigned long long int statOffset = _searchStat(stat,charData,dataLen);
    if(!statOffset) {
        fprintf(stderr,"libd2char error: Unable to find attribute: %d\n", stat);
        return -1;
    }
33
    uint64_t statValue = readBits(charData, statOffset, statCost[stat]);
Imanol-Mikel Barba Sabariego authored
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
    *value = (unsigned int)statValue;
    return 0;
}

int setStat(D2S_STAT stat, unsigned int value, void* charData, size_t dataLen) {
    unsigned long long int statOffset = _searchStat(stat,charData,dataLen);
    if(!statOffset) {
        fprintf(stderr,"libd2char error: Unable to find attribute: %d\n", stat);
        return -1;
    }
    uint64_t statValue = 0;
    memcpy(&statValue, charData + (statOffset / 8), sizeof(statValue));
    statValue &= (~statCostMask[stat] << (statOffset % 8));
    statValue |= (value << (statOffset % 8));
    memcpy(charData + (statOffset / 8), &statValue, sizeof(statValue));
    return 0;
}