expValue.c 2.49 KB
#include <string.h>
#include <malloc.h>
#include <stdio.h>

#include <expValue.h>

union expType
{
	long   iVal;
	double fVal;
	char * cPtr;
};

struct expVal
{
	int type;

	union expType val;
};

/*
 * Constructoren / Destructoren
 */
	s_expVal *
expValueIntNew (long val)
{
	s_expVal * ret = (s_expVal *) malloc (sizeof (s_expVal));

	ret->type     = EXP_TYP_INT;
	ret->val.iVal = val;

	return ret;
}

	s_expVal *
expValueFloatNew (double val)
{
	s_expVal * ret = (s_expVal *) malloc (sizeof (s_expVal));

	ret->type     = EXP_TYP_FLOAT;
	ret->val.fVal = val;

	return ret;
}

	s_expVal *
expValueStringNew (char * val)
{
	s_expVal * ret = (s_expVal *) malloc (sizeof (s_expVal));

	ret->type     = EXP_TYP_STRING;
	ret->val.cPtr = (char *) malloc (sizeof (char) * (strlen (val) + 1));
	strcpy (ret->val.cPtr, val);

	return ret;
}

	s_expVal * 
expValueClone (s_expVal * eVal)
{
	s_expVal * ret = (s_expVal *) malloc (sizeof (s_expVal));

	ret->type = eVal->type;

	switch (eVal->type)
	{
		case EXP_TYP_INT:		ret->val.iVal = eVal->val.iVal; break;
		case EXP_TYP_FLOAT:	ret->val.fVal = eVal->val.fVal; break;
		case EXP_TYP_STRING:	
			{
				ret->val.cPtr = (char *) malloc (
						sizeof (char) * (strlen (eVal->val.cPtr) + 1));
				strcpy (ret->val.cPtr, eVal->val.cPtr);
			}
	}

	return ret;
}

	void
expValueFree (s_expVal * eVal)
{
	if (eVal->type == EXP_TYP_STRING)
		free (eVal->val.cPtr);
	free (eVal);
}


/*
 * Accessors
 */
	long
expValueInt (s_expVal * eVal)
{
	switch (eVal->type)
	{
		case EXP_TYP_INT:		return eVal->val.iVal;
		case EXP_TYP_FLOAT:	return (long) eVal->val.fVal;
		case EXP_TYP_STRING:	return atoi (eVal->val.cPtr);
	}
}

	double
expValueFloat (s_expVal * eVal)
{
	switch (eVal->type)
	{
		case EXP_TYP_INT:		return (double) eVal->val.iVal;
		case EXP_TYP_FLOAT:	return eVal->val.fVal;
		case EXP_TYP_STRING:	return atof (eVal->val.cPtr);
	}
}

	char *
expValueString (s_expVal * eVal)
{
	char   buf[40];
	char * ret = NULL;

	switch (eVal->type)
	{
		case EXP_TYP_INT:
			sprintf (buf, "%d", eVal->val.iVal);
			ret = (char *) malloc (sizeof (char) * (strlen (buf) + 1));
			strcpy (ret, buf);
			break;

		case EXP_TYP_FLOAT:	
			sprintf (buf, "%f", eVal->val.fVal);
			ret = (char *) malloc (sizeof (char) * (strlen (buf) + 1));
			strcpy (ret, buf);
			break;

		case EXP_TYP_STRING:
			ret = (char *) malloc (sizeof (char) * (strlen (eVal->val.cPtr) + 1));
			strcpy (ret, eVal->val.cPtr);
			break;
	}

	return ret;
}

/*
 * analyse expValue 
 */
	int
expValueGetType (s_expVal * eVal)
{
	return eVal->type;
}