d2stat.c 1.91 KB
#include "d2stat.h"

#include <stdio.h>
#include <string.h>

#define readBits(data, start, size) ((*((uint64_t*) &data[(start) / 8]) >> ((start) & 7)) & ((1 << (size)) - 1))

// 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;
    }
    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);
        if(statID == D2S_STAT_FOOTER) {
            break;
        } else if(statID == stat) {
            return offset + D2S_STAT_IDENTIFIER_BIT_LENGTH;
        }
        offset += D2S_STAT_IDENTIFIER_BIT_LENGTH + statCost[statID];
    }
    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;
    }
    uint64_t statValue = readBits(charData, statOffset, statCost[stat]);
    *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;
}