// $Source: /local/data/cvs/yellowbank/postgres/src/y_util/y_util.c,v $
// $Revision: 1.3 $
// $State: Exp $
// $Date: 2006/10/24 02:09:59 $
// $Author: yrp001 $
// $Locker:  $

#include "postgres.h"
#include "fmgr.h"
#include <stdio.h>

typedef unsigned int uint;

PG_FUNCTION_INFO_V1( y_bytea_to_hex );
Datum
y_bytea_to_hex( PG_FUNCTION_ARGS )
{
	if( PG_ARGISNULL(0) ) {
		PG_RETURN_NULL();
	}
	bytea* bytea_in = PG_GETARG_BYTEA_P(0);

	char c;
	uint cui;
	int i, ret;
	char* astring;

	unsigned int len = VARSIZE( bytea_in ) - VARHDRSZ;
	// four bits of each byte per hex character, i.e. 2 * len
	text* result = (text*)palloc(VARHDRSZ + (len * 2));
	VARATT_SIZEP( result ) = VARHDRSZ + (len * 2);

	astring = (char*)palloc( 1 + (len * 2) );

	// We will be overwriting the trailing \0 on each iteration until
	// the end.
	for( i = 0; i < len; i++ ) {
		c = *(VARDATA(bytea_in) + i);
		cui = (uint)c;
		cui = (cui >> 4) & 0x0f;
		ret = snprintf( astring + (i * 2), 2, "%x", cui );
		cui = (uint)c & 0x0f;
		ret = snprintf( astring + (i * 2) + 1, 2, "%x", cui );
	}

	memcpy( VARDATA( result ),
		astring,
		len * 2 );

	PG_RETURN_TEXT_P( result );
}

/*
 octet_length function already does this

PG_FUNCTION_INFO_V1( y_bytea_size );
Datum
y_bytea_size( PG_FUNCTION_ARGS )
{
	if( PG_ARGISNULL(0) ) {
		PG_RETURN_NULL();
	}
	bytea* bytea_in = PG_GETARG_BYTEA_P(0);

	unsigned int result;

	result = VARSIZE( bytea_in ) - VARHDRSZ;

	PG_RETURN_INT32( result );
}
*/

