Skip to content

Commit e0eae75

Browse files
authored
Create object.c
1 parent d209b2c commit e0eae75

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

object.c

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
#include "object.h"
2+
#include "vm.h"
3+
#include "memory.h"
4+
#include <string.h>
5+
#include <stdio.h>
6+
7+
static uint32_t hashString(const char* key, int length) {
8+
uint32_t hash = 2166136261u;
9+
for (int i = 0; i < length; i++) {
10+
hash ^= (uint8_t)key[i];
11+
hash *= 16777619;
12+
}
13+
return hash;
14+
}
15+
16+
ObjString* takeString(VM* vm, char* chars, int length) {
17+
uint32_t hash = hashString(chars, length);
18+
19+
ObjString* string = ALLOCATE_OBJ(vm, ObjString, OBJ_STRING);
20+
string->length = length;
21+
string->chars = chars;
22+
string->hash = hash;
23+
24+
return string;
25+
}
26+
27+
ObjString* copyString(VM* vm, const char* chars, int length) {
28+
uint32_t hash = hashString(chars, length);
29+
30+
char* heapChars = ALLOCATE(vm, char, length + 1);
31+
memcpy(heapChars, chars, length);
32+
heapChars[length] = '\0';
33+
34+
ObjString* string = ALLOCATE_OBJ(vm, ObjString, OBJ_STRING);
35+
string->length = length;
36+
string->chars = heapChars;
37+
string->hash = hash;
38+
39+
return string;
40+
}
41+
42+
void printObject(Value value) {
43+
switch (OBJ_TYPE(value)) {
44+
case OBJ_STRING:
45+
printf("%s", AS_CSTRING(value));
46+
break;
47+
}
48+
}
49+
50+
void freeObject(VM* vm, Obj* object) {
51+
switch (object->type) {
52+
case OBJ_STRING: {
53+
ObjString* string = (ObjString*)object;
54+
FREE_ARRAY(vm, char, string->chars, string->length + 1);
55+
FREE(vm, ObjString, object);
56+
break;
57+
}
58+
}
59+
}

0 commit comments

Comments
 (0)