1. Reliable ANSI C token appending routine (Warning! C Code inside!)

I was working on the NightShade parser,
by implementing an ANSI C compatible way of appending
strings, ie. tokens, to an array of strings.
I used doubly linked lists before, yet when compiling
under LCCWin32 for the first time, I found out LCC
don't support the following syntax:

typedef struct
{
    TOKEN *prev;
    TOKEN *next;
    char *value;
} TOKEN;

Nor this:
struct TOKEN
{
      TOKEN *prev;
      TOKEN *next;
      char *value;
};

Since I didn't feel like finding out why LCCWin32
don't support this, I wrote a smaller, slower, but
100% portable string appending routine. It's slow in
appending, but much faster in subscripting. Plus it's
easy to find the amount of tokens you appended.
Since this might be of some use to yall, I figured I'd
post it here.

This is from NightShade.c.
/* Types */
typedef struct
{
     char **toks;
     long length;
} tokens;

/* Function Defines */
void *ns_malloc(int size)
{
	void *ret;
	if((ret = malloc(size)) == 0)
		{
			puts("This program ran out of memory...\n");
			exit(1);
		}
		else
			return ret;
return ret;
}

void *ns_realloc(void *mem,int nsize)
{
	void *ret;
	if((ret = realloc(mem,nsize)) == 0)
		{
			puts("This program ran out of memory...\n");
			exit(1);
		}
		else
			return ret;
return ret;
}

tokens append(tokens dest,char *what)
{
	/* Append string 'what' to tokens variable 'dest'. */
	tokens ndest;
	ndest = dest;
	if(ndest.length <= 0)
		{
			ndest.toks = (char**)ns_malloc(sizeof(char*));
			ndest.length = 1;
			ndest.toks[0] = what;
			return ndest;
		}
	ndest.length++;
	ndest.toks =
	ndest.toks[ndest.length-1] = what;
	return ndest;
}

void killtoks(tokens what)
{
	/* Free memory used by tokens 'what' */
	free(what.toks);
}


-------------------------------------------------------
Above code could be made faster using byref argument
passing,
but I don't like juggling address pointers around when
I write my code, I ussually add them later after all
code has being written.

Here's an example of how to use this code;

main()
{
   tokens t;
   t = append(t,"MTS");
   t = append(t,"RULES!!!");
   printf("%s %s\n",t.toks[0],t.toks[1]);
}

As output you get:
MTS RULES!!!
_


I stress tested the routine and it works fine under
heavy fire.
It appends 5000 short strings in under a second on my
machine.
tokens.length = 1-based, BTW.


Mike The Spike

__________________________________________________
Do You Yahoo!?
Yahoo! Auctions - Buy the things you want at great prices. 
http://auctions.yahoo.com/

____________________________________________________________
T O P I C A  -- Learn More. Surf Less. 
Newsletters, Tips and Discussions on Topics You Choose.
http://www.topica.com/partner/tag01

new topic     » topic index » view message » categorize

Search



Quick Links

User menu

Not signed in.

Misc Menu