/*****
 NAME
 	cmemory-test.m - test program for CMemory class
 VERSION
 	$Id$
 CHANGELOG
 	$Log$
 */

#include <coconut/cmemory.h>
#include <coconut/cmemalloc.h>
#include <stdlib.h>

void print_memory(id <PMemory> mem)
{
	char   nullstr[] = "<null>" ;
	char * str = [mem ptr] ;

	if(str == NULL) str = nullstr ;
	printf("str:\"%s\", size:%d\n", str, [mem size]) ;
}

int main()
{
	id <PAllocator>	alloc ;
	id <PMemory>	memory ;
	id <PMemory>	dupmemory ;
	utf8_char	msg1[] = "cmemory test" ;
	utf8_char	msg2[] = "cmemory test again" ;
	utf8_char	msg3[] = "!@#$" ;
	utf8_char	msg4[] = " " ;
	utf8_char *	ptr ;
	utf8_char 	c ;
	size_t		len ;

	printf("*** self test program for CMemory class\n") ;

	printf("init:\n") ;
	alloc = [[CMemAlloc alloc] init] ;
	memory = [[CMemory alloc] initMemory: alloc] ;

	printf("new:\n") ;
	len = strlen(msg1) + 1 ;
	ptr = [memory new: len] ; memmove(ptr, msg1, len) ;
	print_memory(memory) ;

	printf("copy:\n") ;
	[memory copy: msg2 size: strlen(msg2)+1] ;
	print_memory(memory) ;

	printf("changesize:\n") ;
	ptr = [memory changeSize: 27] ;
	for(c='a' ; c<='z' ; c++, ptr++)
		*ptr = c ; /* ascii machine only */
	*ptr = '\0' ;
	print_memory(memory) ;

	printf("append:\n") ;
	[memory changeSize: [memory size] - 1] ; /* remove last '\0' */
	[memory append: msg3 size: strlen(msg3)] ;
	[memory append: msg1 size: 7 * sizeof(utf8_char)] ;
	c = '\0' ;
	[memory append: &c size: sizeof(utf8_char)] ;
	print_memory(memory) ;

	printf("prepend:\n") ;
	[memory prepend: msg3 size: strlen(msg3)] ;
	print_memory(memory) ;

	printf("insert:\n");
	len = strlen(msg4) ;
	[memory insert: 0 src: msg4 size: len] ;
	[memory insert: [memory size] - 1 src: msg4 size: len] ;
	[memory insert: 5 src: msg4 size: len] ;
	print_memory(memory) ;

	printf("remove:\n");
	[memory remove: 0 size: 4] ;
	[memory remove: [memory size] - 6 size: 5] ;
	print_memory(memory) ;

	printf("duplicate:\n") ;
	dupmemory = [memory duplicate] ;
	[dupmemory remove: 0 size: 2] ;
	print_memory(memory) ;
	print_memory(dupmemory) ;
	[dupmemory release] ;

	printf("clear:\n");
	[memory clear];
	print_memory(memory) ;

	printf("append:\n") ;
	/* add eos */
	[memory append: msg4 size: strlen(msg4)+1] ;
	print_memory(memory) ;

	printf("bye.\n");
	exit(0) ;
}

