cells.c (1549B)
1 #include <u.h> 2 #include <libc.h> 3 #include <draw.h> /* for points, rectangles and associated funcs */ 4 5 #include "stack.h" 6 #include "cells.h" 7 8 /*** VALUES ***/ 9 10 Value 11 copy_value(Value v) 12 { 13 return mk_value(v.addr, v.data); 14 } 15 16 Value 17 mk_value(Point addr, char *data) 18 { 19 Value v; 20 v.addr = addr; 21 v.data = strdup(data); 22 return v; 23 } 24 25 void 26 free_value(Value v) 27 { 28 if (v.data != 0) free(v.data); 29 } 30 31 /*** TABLE ***/ 32 33 void 34 free_table(Stack *T) 35 { 36 Value *v; 37 while(T->size > 0){ 38 v = pop(T); 39 free_value(*v); 40 free(v); 41 } 42 } 43 44 Stack* 45 table_read(char *path) 46 { 47 Stack *T; 48 Value *v; 49 char b, *buf; 50 long bufsize, x, y; 51 int fd; 52 T = newstack(); 53 buf = mallocz(1, 1); 54 bufsize = 0; 55 x = 0; 56 y = 0; 57 fd = open(path, OREAD); 58 if (fd == 0) return nil; 59 while (read(fd, &b, 1) > 0) { 60 switch (b){ 61 case '\t': 62 v = malloc(sizeof(Value)); 63 *v = mk_value(Pt(x, y), buf); 64 push(T, v); 65 bufsize = 0; 66 buf = realloc(buf, 1); 67 *buf = 0; 68 x++; 69 break; 70 case '\n': 71 v = malloc(sizeof(Value)); 72 *v = mk_value(Pt(x, y), buf); 73 push(T, v); 74 bufsize = 0; 75 buf = realloc(buf, 1); 76 *buf = 0; 77 y++; 78 x = 0; 79 break; 80 default: 81 buf = realloc(buf, bufsize+2); 82 buf[bufsize] = b; 83 buf[bufsize+1] = 0; 84 bufsize++; 85 } 86 } 87 if (buf != nil) { 88 v = malloc(sizeof(Value)); 89 *v = mk_value(Pt(x, y), buf); 90 push(T, v); 91 } 92 realloc(buf, 0); 93 close(fd); 94 95 return T; 96 } 97 98 99 void 100 print_table(Stack *T) 101 { 102 long i; 103 Value *v; 104 print("----\n"); 105 for (i = 0; i < T->size; i++) { 106 v = T->data[i]; 107 print("%d:%d %s\n", v->addr.x, v->addr.y, v->data); 108 } 109 }