/* This file is part of Mailfromd.
   Copyright (C) 2007-2025 Sergey Poznyakoff

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>. */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stdlib.h>
#include <string.h>
#include <mailutils/assoc.h>
#include <mailutils/list.h>
#include <mailutils/errno.h>
#include <mailutils/alloc.h>


/* Rudimentary dictionary support */
void
dict_init(mu_assoc_t *dict)
{
	mu_assoc_create(dict, 0);
	mu_assoc_set_destroy_item(*dict, mu_list_free_item);
}

char *
dict_install(mu_assoc_t dict, const char *name, const char *value)
{
	char **pptr;
	int rc;
	
	rc = mu_assoc_install_ref(dict, name, &pptr);
	if (rc == MU_ERR_EXISTS)
		free(*pptr);
	*pptr = mu_strdup(value);
	return 0;
}

void
dict_destroy(mu_assoc_t *dict)
{
	mu_assoc_destroy(dict);
}

char *
dict_getsym(void *data, const char *str)
{
	mu_assoc_t dict = data;
	char *tmp = NULL;
	char *val = NULL;
	
	if (str[0] == '{') {
		int len = strlen(str);
		if (str[len-1] == '}') {
			tmp = malloc(len-1);
			if (!tmp)
				abort();
			memcpy(tmp, str+1, len-2);
			tmp[len-2] = 0;
			str = tmp;
		}
	}

	val = mu_assoc_get(dict, str);
	free(tmp);
	return val;
}

