aboutsummaryrefslogtreecommitdiffstats
path: root/variable.c
blob: 620a4b6023ebde5fb5dd9b4cf8507e5381705fb9 (plain)
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
#include "variable.h"
#include "parser.h"

#include <stdio.h>
#include <stdlib.h>

extern char *str_undef;
extern char *str_func;

variable *vmake(uint8_t fromc, uint8_t valtype, void *value)
{
	variable *v = (variable *)malloc(sizeof(variable));
	v->used = 0;
	v->fromc = fromc;
	v->valtype = valtype;
	v->value = 0;
	v->svalue = 0;
	switch (valtype) {
	case STRING:
		v->value = 0;
		v->svalue = value;
		break;
	case INTEGER:
		INT(v) = (int32_t)value;
		isetstr(v);
		break;
	case FUNC:
		v->value = (uint32_t)value;
		v->svalue = str_func;
		break;
	case EXPR:
		v->value = 0;
		v->svalue = value;
		break;
	}
	return v;
}

variable *vmakef(float value)
{
	variable *v = (variable *)malloc(sizeof(variable));
	v->used = 0;
	v->fromc = 0;
	v->valtype = FLOAT;
	FLOAT(v) = value;
	fsetstr(v);
	return v;
}

void fsetstr(variable *f)
{
	if (f->svalue == 0 || f->svalue == str_undef)
		f->svalue = (char *)malloc(16);
	snprintf(f->svalue, 16, "%f", FLOAT(f));
}

void isetstr(variable *i)
{
	if (i->svalue == 0 || i->svalue == str_undef)
		i->svalue = (char *)malloc(12);
	snprintf(i->svalue, 12, "%d", (int)INT(i));
}

variable *itostring(variable *v)
{
	switch (v->valtype) {
	case INTEGER:
		v->valtype = STRING;
		isetstr(v);
		break;
	case FLOAT:
		v->valtype = STRING;
		fsetstr(v);
		break;
	}
	return v;
}

variable *itoint(variable *v)
{
	switch (v->valtype) {
	case STRING:
		v->valtype = INTEGER;
		INT(v) = atoi(v->svalue);
		isetstr(v);
		break;
	case FLOAT:
		v->valtype = INTEGER;
		INT(v) = (int32_t)FLOAT(v);
		isetstr(v);
		break;
	}
	return v;
}

variable *itofloat(variable *v)
{
	switch (v->valtype) {
	case STRING:
		v->valtype = FLOAT;
		FLOAT(v) = strtof(v->svalue, 0);
		fsetstr(v);
		break;
	case INTEGER:
		v->valtype = FLOAT;
		FLOAT(v) = (float)INT(v);
		fsetstr(v);
		break;
	}
	return v;
}