Util.c

From Organic Design wiki
Revision as of 23:53, 26 July 2006 by Nad (talk | contribs) (linked list belongs in here)

int fileRead(char* filename) { }

int fileWrite(char* filename, char* content) { }

char *logAdd(char *msg) { // prepend with a timestamp // append to logfile printf(msg); printf("\n"); return msg; }

// Enter a blank line in log as a marker of new peerd session logAdd("");

int logErr(char *msg) { logAdd(msg); // should prepend "ERROR:" return(err = EXIT_FAILURE); }

// Same as logErr but allows error message to contain an arg int logErr2(char *fmt, char *msg2) { char *msg = malloc(100); sprintf(msg,fmt,msg2); logErr(msg); free(msg); return(err = EXIT_FAILURE); }

// Return an array of strings resulting from splitting passed text at passed character // - the resulting strings are formed from the passed string char **split(char c,char *text) { int len = strlen(text), items = 0, size = 10; char **list = malloc(size); char *i = malloc(len+1), *j = i, *k = i, *item = i; while(*j++ = *text++); while(i <= k+len) { if (*i == c) *i = '\0'; if ((*i++ == '\0')&&strlen(item)) { if (items>size-2) realloc(list,size+=10); list[items++] = item; list[items] = NULL; item = i; } } return list; }

// Replaces missing itoa() and is specialised for binary return a string of \1 and \2 characters void itob(int value, char *buf) { int i; for (i=1; i<=value>>1; i<<=1) *buf++ = value&i ? '\1' : '\2'; }

// ----------------------------------------------------------------------------------------- // // LINKED LIST // - A need keeps arrising in this C implimentation for linked lists because we // need to be able to dynamically add or remove items from any position in the list void linkBefore(item subject, item object) { int si = 3*(int)subject, oi = 3*(int)object; item prev = space[oi] = space[si]; space[si] = space[1+3*(int)prev] = object; space[oi+1] = subject; }

void linkAfter(item subject, item object) { int si = 3*(int)subject, oi = 3*(int)object; item next = space[oi+1] = space[si+1]; space[si+1] = space[3*(int)next] = object; space[oi] = subject; }

void linkRemove(item subject) { int si = 3*(int)subject; space[3*(int)space[si+1]] = space[si] space[1+3*(int)space[si]] = space[si+1] }

void linkTest() { // create a bunch of items // give them ascii-list-items for payloads // do some link manipulation on them // render the sequence of payload indexes at each step }