/*******************************************************************************
 * Copyright (c) 2005, 2008 Intel Corporation.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Hoang M Nguyen, Intel - Initial API and Implementation
 * $Id: TPTPSupportUtils.c,v 1.5 2008/01/14 07:49:59 ialelekov Exp $
 *******************************************************************************/ 



#include "tptp/TPTPSupportUtils.h"

#include "tptp/TPTPOSCalls.h"


/**
 *********************************************************
 *                                                       
 * @brief                                                
 *    load a given library
 *
 * @return
 *    The library handler or
 *    NULL if unable to load the library.
 *
 * @note
 *    it returns (void *) to have consistent call interface for all platforms.
 *
 *********************************************************/
void * loadThisLib(const char *pLibName)
{
	return ( loadTheModule(pLibName) ) ;
}


/**
 *********************************************************
 *                                                       
 * @brief                                                
 *    generate a unique id string
 *
 * @return
 *    The address of the UUID string
 *    NULL if unable to generate the UUID
 *
 * @note
 *    The caller is responsible to free the returned string with free(char *) function
 *********************************************************/

char * generateUUID()
{
	return ( getGlobalUniqueId() ) ;
}

unsigned char* writeUINTToBuffer(unsigned char *buffer,
							   unsigned int uintData) {
	buffer[0]=(unsigned char)(uintData>>24 & 0x000000ff);
	buffer[1]=(unsigned char)(uintData>>16 & 0x000000ff);
	buffer[2]=(unsigned char)(uintData>>8  & 0x000000ff);
	buffer[3]=(unsigned char)uintData;
	return &buffer[4];
}


unsigned char* readUINTFromBuffer(unsigned char *buffer, unsigned int *uint) {
	*uint=((unsigned int)(buffer[0]<<24)
					  |(unsigned int)(buffer[1]<<16)
					  |(unsigned int)(buffer[2]<<8)
					  | buffer[3]);
	return &buffer[sizeof(unsigned int)];
}

unsigned char* readStringFromBuffer(unsigned char *buffer, char** str) {
	int len, padding;
	
	buffer = readUINTFromBuffer(buffer, &len);

	if (len == 0)
		*str = NULL;
	else {
		*str = (char*) tptp_malloc(len+1);
		memcpy(*str, buffer, len);
		*((*str) + len) = '\0';
		buffer += len;
	}
	
	padding = 4 - len%4;
	if (padding == 4) padding = 0;
	
	return buffer + padding;
}
