/* -*- c-basic-offset: 4; -*-
 *
 * $Id: hextype.c,v 1.1 2001/05/30 06:04:59 mbp Exp $
 * 
 * Copyright (C) 1999, 2000, 2001 Martin Pool <mbp@sourcefrog.net>
 *
 * You may use, modify, and redistribute this code without limitation
 * except that this copyright notice must be preserved.
 */

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

#include "hextype.h"

#define UNPRINTABLE_CHAR '_'
#define NULL_CHAR '.'
#define MIDDLE_BREAK " "

/*
 * Print out in a debugging form the LEN bytes of data starting at P.
 * Format is 16 bytes per line, with a little gap after the first
 * eight.  On the far left is the relative position, then the hex,
 * then the ascii characters if they are printable.
 */
void hextype(FILE *f, const void *p, size_t len)
{
    char           *str;

    str = hextype_tostr(p, len);
    fputs(str, f);
    fputc('\n', f);
    free(str);
}


/**
 * Convert binary data into hex representation, and return that in a
 * newly-allocated buffer.  There is no trailing newline.
 */
char *hextype_tostr(const void *p, size_t len)
{
    size_t              i, j;
    unsigned char const *d = (unsigned char const *) p;
    size_t              buflen;
    char                *buf, *o;

    /* At most one 80-character line per 16 bytes */
    buflen = (len + 16) / 16 * 80 + 1;
    o = buf = malloc(sizeof(char) * buflen);

    for (i = 0; i < len; ) {
	o += sprintf(o, "%5x: ", i);
	for (j = i; j < len && j < (i+16); j++) {
	    o += sprintf(o, "%02x ", d[j]);
	    if (j == i+7)
		o += sprintf(o, MIDDLE_BREAK);
	}
	for (; j < i+16; j++) {
	    o += sprintf(o, "   ");
	    if (j == i+7)
		o += sprintf(o, MIDDLE_BREAK);
	}
	o += sprintf(o, "  ");
	for (j = i; j < len && j < (i+16); j++) {
	    if (d[j] >= 0x20 && d[j] < 0x7f)
		*o++ = d[j];
	    else if (d[j] >= 0xa0 && d[j] < 0xff)
		*o++ = d[j];
	    else if (d[j] == 0)
		*o++ = NULL_CHAR;
	    else
		*o++ = UNPRINTABLE_CHAR;
	} 

	i = j;
	if (i < len)
	    *o++ = '\n';
	assert(o < buf + buflen);
    }

    /* We don't increment here so that the final \n will be overwritten. */
    *o++ = '\0';

    return buf;
}
