jeudi 25 août 2016

How to genericize uint_t based functions

I created a utility function here for demonstration, which take an unsigned 16-bit integer. I have multiple use cases where I want to reuse this function for say uint8_t, uint32_t, and uint64_t. My first approach was to remove the type, and instead pass a void pointer. This however did not work because in order to perform any sort of arithmetic I would need to dereference the pointer. With that said, the only way to do that with void* is to cast the associated type. Aside from a nasty switch statement checking for types, I’m not sure how else to get the job done. I did find a tagged union approach which I was not familiar with, but that still shares the same concern above. The function in question can be found below:

#define MAX_BYTE 0xFF
#define BITS_PER_BYTE 8
static void encodeToUint16(uint16_t *num, uint8_t *buffer, size_t len) {

    uint8_t bytePos = 0;

    for (int i = len; i >= 0; i--) {
        buffer[i] = (i == len) ? (*num & MAX_BYTE) : ((*num >> bytePos) & MAX_BYTE);
        bytePos += BITS_PER_BYTE;
    }
}

My goal is to try and find a safe, generic way for this function to be shared across different unsigned int types. Although this question seems specific to encodeToUint16, the end pattern is something that can shared throughout the project in general.

Aucun commentaire:

Enregistrer un commentaire