update.c (1654B)
1 #include <u.h> 2 #include <libc.h> 3 #include <../util/util.h> 4 #include <../tablist/tablist.h> 5 enum { 6 BSize = 1024 * 8, 7 HSize = BSize / 2, 8 }; 9 10 int db, bn; 11 char *path, buf[BSize]; 12 TLdecoder *tldec; 13 TLencoder *tlenc; 14 Slice *query, *nodes; 15 16 TLnode ** 17 find(TLnode *n) 18 { 19 TLnode **v, *m; 20 int i; 21 if (n->name == nil) return nil; 22 for (i = 0; i < nodes->len; i++) { 23 v = slicegetp(nodes, i); 24 m = *v; 25 if (m->name == nil) continue; 26 if (memcmp(m->name->p, n->name->p, m->name->len) == 0) 27 return v; 28 } 29 return nil; 30 } 31 32 void 33 update(TLnode *n) 34 { 35 TLnode **v; 36 v = find(n); 37 if (v != nil) { 38 *v = n; 39 } else { 40 nodes = sliceappendp(nodes, 1, &n); 41 } 42 } 43 44 void 45 usage(void) 46 { 47 fprint(2, "usage %s db_file < node\n", argv0); 48 exits("usage"); 49 } 50 51 void 52 main(int argc, char *argv[]) 53 { 54 55 fprint(2, "hello\n"); 56 57 int i; 58 59 ARGBEGIN { 60 default: 61 usage(); 62 } ARGEND 63 64 if (argc != 1) usage(); 65 path = argv[0]; 66 db = open(path, OREAD); 67 if (db < 0) sysfatal("can't open db: %r"); 68 69 fprint(2, "reading query\n"); 70 tldec = initTLdecoder(nil); 71 while((bn = read(0, buf, BSize)) > 0) { 72 TLdecode(tldec, buf, bn); 73 } 74 if (bn < 0) sysfatal("%r"); 75 query = tldec->nodes; 76 fprint(2, "qlen %d\n", query->len); 77 78 tldec = initTLdecoder(path); 79 while((bn = read(db, buf, BSize)) > 0) { 80 TLdecode(tldec, buf, bn); 81 } 82 if (bn < 0) sysfatal("%r"); 83 nodes = tldec->nodes; 84 close(db); 85 86 for (i = 0; i < query->len; i++) { 87 TLnode **v; 88 v = slicegetp(query, i); 89 update(*v); 90 } 91 92 db = open(path, OWRITE | OTRUNC); 93 if (db < 0) sysfatal("%r"); 94 tlenc = initTLencoder(nodes); 95 while((bn = TLencode(tlenc, buf, BSize)) > 0) { 96 bn = write(db, buf, bn); 97 if (bn < 0) sysfatal("%r"); 98 } 99 }