#ifndef lint
static char *sccsid = "@(#)assoclist.c	1.1 (Steve Hill) 3/9/90";
#endif

/* assoclist.c
 *
 * Association lists enable values to be associated with a key.
 */

#include <stdio.h>

#include "basetype.h"
#include "error.h"
#include "list.h"
#include "assoclist.h"

/* Assoc
 *
 * Create an association between name and value.  An association list
 * is a list of such entries.
 */

assoc_t	*
Assoc(name, value)
char		*name;
address_t	value;
{
	assoc_t	*assoc;

	assoc = (assoc_t *) malloc(sizeof(assoc_t));
	if (assoc == AssocNull)
		FatalError(__FILE__, __LINE__, "Assoc: out of memory");

	assoc->name  = name;
	assoc->value = value;

	return(assoc);
}

/* AssocListGet
 *
 * Search an association list for the entry corresponding to the
 * specified name.  Returns a NULL pointer if the entry does not exist.
 */

address_t
AssocListGet(name, assoc_list)
char		*name;
assoc_list_t	*assoc_list;
{
	while (assoc_list != AssocListNull)
	{
		if (strcmp(name, assoc_list->elem->name) == 0)
			return(assoc_list->elem->value);

		assoc_list = assoc_list->ptr;
	}

	return((address_t) NULL);
}

/* AssocListAdd
 *
 * Add the specified value under the given name.  If the name is already
 * in the list, then return AssocListNull, otherwise return the new
 * association list.
 */

assoc_list_t *
AssocListAdd(name, value, assoc_list)
char		*name;
address_t	value;
assoc_list_t	*assoc_list;
{
	assoc_t	*assoc;

	if (AssocListGet(name, assoc_list) != (address_t) NULL)
		return(AssocListNull);

	assoc = Assoc(name, value);

	return((assoc_list_t *) ListCons((address_t) assoc,
					 (list_t *) assoc_list));
}
