#include "stdio.h"
#include <ctype.h>
#include "hexdump.h"

void hexdump (const char *label, const uint8_t *data, size_t len) {
    if (label)
        iprintf ("%s (len=%u):\n", label, len);

    for (size_t i = 0; i < len; i += 16) {
        iprintf ("%04u  ", i);  // offset
        for (size_t j = 0; j < 16; j++) {
            if (i + j < len)
                iprintf ("%02X ", data[i + j]);
            else
                iprintf ("   ");  // pad spacing
        }
        iprintf (" ");
        for (size_t j = 0; j < 16 && i + j < len; j++) {
            uint8_t c = data[i + j];
            iprintf ("%c", isprint (c) ? c : '.');
        }
        iprintf ("\n");
    }
}

void hexdump_compact(const uint8_t* data, size_t len, char* out, size_t out_size) {
    size_t pos = 0;

    for (size_t i = 0; i < len; i++) {
        if (pos + 2 >= out_size) break;  // make sure we don¡¯t overflow
        snprintf(out + pos, 3, "%02x", data[i]); // 2 chars + null terminator
        pos += 2;
    }

    if (pos < out_size)
        out[pos] = '\0';
    else
        out[out_size - 1] = '\0'; // ensure null termination
}