/*
 * testhash.c: test program for the hash module.
 *
 *	       specifically, let's have a hash : string->string
 *
 * (C) Duncan C. White, 1996-2008 although it seems longer:-)
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <mem.h>

#include "hash.h"



void myPrint( FILE *out, key k, value v )
{
	fprintf( out, "%s: %s\n", k, (char *)v );
}

static void myFree( value v )
{
	free( v );
}


static value myCopyValue( value v )
{
	return strdup(v);
}


static hash h1;


void test( key k, int expected )
{
	value v = hashFind( h1, k );
	if( v != NULL )
	{
		if( ! expected )
		{
			printf( "error: '%s' found - ", k );
		}
		myPrint( stdout, k, v );
	} else
	{
		if( expected )
		{
			printf( "error: '%s' not found\n", k );
		}
	}
}


void lookuptest( int x1, int x2, int x3, int x4, int xaard, int xgrumble )
{
	printf( "lookup tests:\n" );
	test( "one", x1 );
	test( "two", x2 );
	test( "three", x3 );
	test( "four", x4 );
	test( "aardvark", xaard );
	test( "grumble", xgrumble );
}


void set( hash h, key k, char *v )
{
	hashSet( h, k, myCopyValue(v) );
}


/* 
 * each_cb: print out a (k,v) pair to the FILE *
 *	    hidden in the arg; used in the main
 *	    program to print the hash ourselves.
 */

static void each_cb( key k, value v, value arg )
{
	FILE *out = (FILE *)arg;

	myPrint( out, k, v );
}


void onerun( void )
{
	h1 = hashCreate( myPrint, myFree, myCopyValue );

	set( h1, "one", "eeny" );
	set( h1, "two", "meeny" );
	set( h1, "three", "miny" );
	set( h1, "four", "mo" );

	printf( "here's the hash:\n" );
	hashDump( stdout, h1 );

	lookuptest( 1, 1, 1, 1, 0, 0 );

	printf( "modify hash a bit:\n" );
	set( h1, "one", "solitare" );
	set( h1, "aardvark", "not a herring" );
	set( h1, "three", "quite a few" );

	printf( "now here's the hash:\n" );
	hashDump( stdout, h1 );

	lookuptest( 1, 1, 1, 1, 1, 0 );

	printf( "\nprint the hash out using an explicit foreach loop:\n{\n" );
	hashForeach( h1, &each_cb, stdout );
	printf( "}\n" );

	printf( "\ncopy the hash\n" );
	hash h2 = hashCopy( h1 );

	printf( "modify both hashes a bit:\n" );
	set( h1, "one", "single solitaire" );
	set( h2, "one", "on me ownses, savvy?" );

	printf( "print h1:\n" );
	hashDump( stdout, h1 );

	printf( "print h2:\n" );
	hashDump( stdout, h2 );

	printf( "free the original hash\n" );
	hashFree( h1 );

	printf( "print the copy again:\n" );
	hashDump( stdout, h2 );

	printf( "free the copy\n" );
	hashFree( h2 );
}


int main( int argc, char **argv )
{
	if( argc > 1 )
	{
		malloc(strlen(argv[1]));
	}

	onerun();
	exit(0);
	return 0;
}
