//
// Created by Kai Jan Kriegel on 17.10.22.
//

#include "utils.h"

#define MAX_HEX_STR         4
#define MAX_HEX_STR_LENGTH  128
char hexStr[MAX_HEX_STR][MAX_HEX_STR_LENGTH];
uint8_t hexStrIdx = 0;

char *hex2Str(unsigned char *data, size_t dataLen) {
    {
        unsigned char *pin = data;
        const char *hex = "0123456789ABCDEF";
        char *pout = hexStr[hexStrIdx];
        uint8_t i = 0;
        uint8_t idx = hexStrIdx;
        size_t len;

        if (dataLen == 0) {
            pout[0] = 0;
        } else {
            /* Trim data that doesn't fit in buffer */
            len = MIN(dataLen, (MAX_HEX_STR_LENGTH / 2));

            for (; i < (len - 1); ++i) {
                *pout++ = hex[(*pin >> 4) & 0xF];
                *pout++ = hex[(*pin++) & 0xF];
            }
            *pout++ = hex[(*pin >> 4) & 0xF];
            *pout++ = hex[(*pin) & 0xF];
            *pout = 0;
        }

        hexStrIdx++;
        hexStrIdx %= MAX_HEX_STR;

        return hexStr[idx];
    }
}