expValue.c
2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
#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;
}