-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalue.c
84 lines (76 loc) · 1.94 KB
/
value.c
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
//
// Created by Mic Pringle on 03/12/2022.
//
#include <stdio.h>
#include <string.h>
#include "object.h"
#include "memory.h"
#include "value.h"
void initValueArray(ValueArray *array) {
array->capacity = 0;
array->count = 0;
array->values = NULL;
}
void writeValueArray(ValueArray *array, Value value) {
if (array->capacity < array->count + 1) {
int oldCapacity = array->capacity;
array->capacity = GROW_CAPACITY(oldCapacity);
array->values = GROW_ARRAY(Value, array->values, oldCapacity, array->capacity);
}
array->values[array->count] = value;
array->count++;
}
void freeValueArray(ValueArray *array) {
FREE_ARRAY(Value, array->values, array->capacity);
initValueArray(array);
}
void printValue(Value value) {
#ifdef NAN_BOXING
if (IS_BOOL(value)) {
printf(AS_BOOL(value) ? "true" : "false");
} else if (IS_NIL(value)) {
printf("nil");
} else if (IS_NUMBER(value)) {
printf("%g", AS_NUMBER(value));
} else if (IS_OBJ(value)) {
printObject(value);
}
#else
switch (value.type) {
case VAL_BOOL:
printf(AS_BOOL(value) ? "true" : "false");
break;
case VAL_NIL:
printf("nil");
break;
case VAL_NUMBER:
printf("%g", AS_NUMBER(value));
break;
case VAL_OBJ:
printObject(value);
break;
}
#endif
}
bool valuesEqual(Value a, Value b) {
#ifdef NAN_BOXING
if (IS_NUMBER(a) && IS_NUMBER(b)) {
return AS_NUMBER(a) == AS_NUMBER(b);
}
return a == b;
#else
if (a.type != b.type) return false;
switch (a.type) {
case VAL_BOOL:
return AS_BOOL(a) == AS_BOOL(b);
case VAL_NIL:
return true;
case VAL_NUMBER:
return AS_NUMBER(a) == AS_NUMBER(b);
case VAL_OBJ:
return AS_OBJ(a) == AS_OBJ(b);
default:
return false;
}
#endif
}