-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobject.c
47 lines (37 loc) · 1.08 KB
/
object.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
#include <stdio.h>
#include <string.h>
#include "memory.h"
#include "object.h"
#include "value.h"
#include "vm.h"
#define ALLOCATE_OBJ(type, object_type) \
(type*)allocate_object(sizeof(type), object_type)
static Obj* allocate_object(size_t size, ObjType type){
Obj* object = (Obj*)reallocate(NULL, 0, size);
object-> type = type;
object-> next = vm.objects;
vm.objects = object;
return object;
}
static ObjString* allocate_string(char* chars, int length) {
ObjString* string = ALLOCATE_OBJ(ObjString, OBJ_STRING);
string->length = length;
string->chars = chars;
return string;
}
ObjString* copy_string(const char* chars, int length){
char* heap_chars = ALLOCATE(char, length + 1);
memcpy(heap_chars, chars, length);
heap_chars[length] = '\0';
return allocate_string(heap_chars, length);
}
void print_object(Value value){
switch(OBJ_TYPE(value)){
case OBJ_STRING:
printf("%s", AS_CSTRING(value));
break;
}
}
ObjString* take_string(char* chars, int length){
return allocate_string(chars, length);
}