xrxs/universe.c

105 lines
1.9 KiB
C
Raw Normal View History

#include <u.h>
#include <libc.h>
#include <stdio.h>
#include "util.h"
#include "universe.h"
Universe* create_universe() {
int i;
Universe* self = malloc(sizeof(Universe));
for (i = 0; i < 256; i++) {
self->atoms[i] = nil;
}
return self;
}
Universe* parse_universe(char* realm_name) {
char path[64] = {0};
char buf[256] = {0};
char name[16] = {0};
char value[64] = {0};
FILE* f;
Atom* a;
Universe* self;
scat(path, "realms/");
scat(path, realm_name);
scat(path, "/universe");
f = fopen(path, "r");
if (f != nil) {
self = malloc(sizeof(Universe));
while (fgets(buf, 256, f) != nil) {
sscanf(buf, "%16s = %64s", name, value);
a = malloc(sizeof(Atom));
scpy(name, a->name, 16);
scpy(value, a->value, 64);
a->next = nil;
set_atom(self, a);
}
fclose(f);
return self;
}
return nil;
}
void save_universe(Universe* self, char* realm_name) {
char path[64] = {0};
FILE* f;
Atom* a;
int i;
scat(path, "realms/");
scat(path, realm_name);
scat(path, "/universe");
f = fopen(path, "w");
if (f != nil) {
for (i = 0; i < 256; i++) {
a = self->atoms[i];
while (a != nil) {
fprintf(f, "%s = %s", a->name, a->value);
a = a->next;
}
}
fclose(f);
}
}
void set_atom(Universe* self, Atom* atom) {
uvlong i = hash(atom->name, 256);
Atom* a = self->atoms[i];
while (a != nil) {
a = a->next;
}
a = atom;
atom->next = nil;
}
Atom* get_atom(Universe* self, char* name) {
uvlong i = hash(name, 256);
Atom* a = self->atoms[i];
while (a != nil && !scmp(a->name, name)) {
a = a->next;
}
return a;
}
void destroy_universe(Universe* self) {
int i;
Atom* a;
Atom* next;
if (self != nil) {
for (i = 0; i < 256; i++) {
a = self->atoms[i];
while (a != nil) {
next = a->next;
free(a);
a = next;
}
}
free(self);
self = nil;
}
}