#include <assert.h>
#include <stddef.h>
#include <stdio.h>
#include "util.h"

void
enchex(unsigned char *in, size_t inlen, char *out, size_t outlen)
{
	assert(outlen >= inlen * 2 + 1);
	for (size_t i = 0; i < inlen; ++i) {
		snprintf(&out[i * 2], 3, "%02x", in[i]);
	}
}

int
dechex(char *in, size_t inlen, unsigned char *out, size_t outlen)
{
	assert(outlen >= (inlen - 1) / 2);
	for (size_t i = 0; i < outlen; ++i) {
		unsigned int v;
		int n = sscanf(&in[i * 2], "%02x", &v);
		if (n != 1) {
			return -1;
		}
		assert(v < 0x100);
		out[i] = (unsigned char)v;
	}
	return outlen;
}
