universe.c (raw)
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 113 114 115 116 117 118 119 120 121 122 123 |
#include <u.h> #include <libc.h> #include <stdio.h> #include "config.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* cart, char* realm_name) { char path[256] = {0}; char buf[256] = {0}; char name[16] = {0}; char value[64] = {0}; FILE* f; Atom* a; Universe* self; scat(path, DATA_DIR); scat(path, cart); scat(path, "/realms/"); scat(path, realm_name); scat(path, "/universe"); fprintf(stderr, "universe path: %s\n", path); f = fopen(path, "r"); if (f != nil) { self = malloc(sizeof(Universe)); while (fgets(buf, 256, f) != nil && !scmp(buf, 0)) { fprintf(stderr, "read a line\n"); sscanf(buf, "%16s = %64s", name, value); fprintf(stderr, "parsed a line\n"); a = malloc(sizeof(Atom)); fprintf(stderr, "allocated an atom\n"); scpy(name, a->name, 16); fprintf(stderr, "assigned name: %s\n", name); scpy(value, a->value, 64); fprintf(stderr, "assigned value: %s\n", value); a->next = nil; set_atom(self, a); } fclose(f); return self; } return nil; } void save_universe(char* cart, Universe* self, char* realm_name) { char path[256] = {0}; FILE* f; Atom* a; int i; scat(path, DATA_DIR); scat(path, cart); 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]; Atom* last; if (a == nil) { self->atoms[i] = atom; return; } while (a != nil) { last = a; a = a->next; } last->next = atom; } 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; } } |