/* This file is part of Mailfromd.
   Copyright (C) 2006-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 <errno.h>
#include "libmf.h"

/* |hash_size| defines a sequence of symbol table sizes. These are prime
   numbers, the distance between each pair of them grows exponentially,
   starting from 64. Hardly someone will need more than 16411 symbols, and
   even if someone will, it is easy enough to add more numbers to the
   sequence. */

static unsigned int hash_size[] = {
    37,   101,  229,  487, 1009, 2039, 4091, 8191, 16411
};

/* |max_rehash| keeps the number of entries in |hash_size| table. */
static unsigned int max_rehash = sizeof (hash_size) / sizeof (hash_size[0]);

struct symtab {
	int flags;
	unsigned int hash_num;  /* Index to hash_size table */
	size_t elsize;          /* Size of an element */
	struct syment **tab;
	void *(*syment_alloc_fun)(size_t size);
	void (*syment_free_fun) (void *);
};

static void
syment_free(struct symtab *st, void *ptr)
{
	if (st->syment_free_fun)
		st->syment_free_fun(ptr);
	else
		free(ptr);
}

static struct syment *
syment_alloc(struct symtab *st, const char *name)
{
	struct syment *ent;
	
	ent = st->syment_alloc_fun ?
		st->syment_alloc_fun(st->elsize) : malloc(st->elsize);
	if (ent) {
		memset(ent, 0, st->elsize);
		ent->refcnt = 1;
		if (st->flags & SYMTAB_COPY_KEY)
			ent->name = (char *) name;
		else {
			ent->name = strdup(name);
			if (!ent->name) {
				syment_free(st, ent);
				return NULL;
			}
		}
	}
	return ent;
}


static unsigned
hash(const char *name, unsigned long hash_num)
{
	unsigned i;
	
	for (i = 0; *name; name++) {
		i <<= 1;
		i ^= *(unsigned char*) name;
	}
	return i % hash_size[hash_num];
}

static void
symtab_free_syment(struct symtab *st, struct syment *elem)
{
	if (--elem->refcnt)
		return;
	if (!(st->flags & SYMTAB_COPY_KEY))
		free(elem->name);
	syment_free(st, elem);
}

static unsigned
symtab_insert_pos(struct symtab *st, const char *name)
{
	unsigned i;
	unsigned pos = hash(name, st->hash_num);
	
	for (i = pos; st->tab[i];) {
		if (++i >= hash_size[st->hash_num])
			i = 0;
		if (i == pos)
			/* FIXME: Error message? */
			abort();
	}
	return i;
}

#define name_cmp(st,a,b) (((st)->flags & SYMTAB_ICASE) ? \
			  strcasecmp(a,b) : strcmp(a,b))

int
symtab_replace(struct symtab *st, struct syment *ent, struct syment **old_ent)
{
	struct syment *entry;
	const char *name = ent->name;
	unsigned i, pos = hash(name, st->hash_num);
	for (i = pos; entry = st->tab[i];) {
		if (name_cmp(st, entry->name, name) == 0)
			break;
		if (++i >= hash_size[st->hash_num])
			i = 0;
		if (i == pos)
			return ENOENT;
	}
	if (old_ent)
		*old_ent = entry;
	st->tab[i] = ent;
	return 0;
}

static int
symtab_rehash(struct symtab *st)
{
	struct syment **old_tab = st->tab;
	struct syment **new_tab;
	unsigned int i;
	unsigned int hash_num = st->hash_num + 1;
	
	if (hash_num >= max_rehash)
		return E2BIG;

	new_tab = calloc(hash_size[hash_num], sizeof(*new_tab));
	if (!new_tab)
		return ENOMEM;
	st->tab = new_tab;
	if (old_tab) {
		st->hash_num = hash_num;
		for (i = 0; i < hash_size[hash_num-1]; i++) {
			struct syment *elt = old_tab[i];
			if (elt->name) {
				unsigned n = symtab_insert_pos(st, elt->name);
				new_tab[n] = elt;
			}
		}
		free(old_tab);
	}
	return 0;
}

const char *
symtab_strerror(int rc)
{
	switch (rc) {
	case ENOENT:
		return _("element not found in table");
	case E2BIG:
		return _("symbol table is full");
	case ENOMEM:
		return strerror(ENOMEM);
	}
	return strerror(rc);
}

int
symtab_remove(struct symtab *st, const char *name)
{
	unsigned int pos, i, j, r;
	struct syment *entry;
	
	pos = hash(name, st->hash_num);
	for (i = pos; entry = st->tab[i];) {
		if (name_cmp(st, entry->name, name) == 0)
			break;
		if (++i >= hash_size[st->hash_num])
			i = 0;
		if (i == pos)
			return ENOENT;
	}
	
	if (!entry)
		return ENOENT;

	symtab_free_syment(st, entry);

	for (;;) {
		st->tab[i] = NULL;
		j = i;

		do {
			if (++i >= hash_size[st->hash_num])
				i = 0;
			if (!st->tab[i])
				return 0;
			r = hash(st->tab[i]->name, st->hash_num);
		}
		while ((j < r && r <= i)
		       || (i < j && j < r) || (r <= i && i < j));
		st->tab[j] = st->tab[i];
	}
	return 0;
}

int
symtab_get_index(unsigned *idx,
		 struct symtab *st, const char *name,
		 int *install)
{
	int rc;
	unsigned i, pos;
	struct syment *elem;
  
	if (!st->tab) {
		if (install) {
			rc = symtab_rehash(st);
			if (rc)
				return rc;
		} else
			return ENOENT;
	}

	pos = hash(name, st->hash_num);

	for (i = pos; elem = st->tab[i];) {
		if (name_cmp(st, elem->name, name) == 0) {
			if (install)
				*install = 0;
			*idx = i; 
			return 0;
		}
      
		if (++i >= hash_size[st->hash_num])
			i = 0;
		if (i == pos)
			break;
	}

	if (!install)
		return ENOENT;
  
	if (!elem) {
		*install = 1;
		*idx = i;
		return 0;
	}

	if ((rc = symtab_rehash(st)) != 0)
		return rc;

	return symtab_get_index(idx, st, name, install);
}

int
symtab_lookup_or_install(struct syment **elp, 
			 struct symtab *st, const char *name, int *install)
{
	unsigned i;
	int rc = symtab_get_index(&i, st, name, install);
	if (rc == 0) {
		if (install && *install == 1) {
			struct syment *ent = syment_alloc(st, name);
			if (!ent)
				return ENOMEM;
			st->tab[i] = ent;
			*elp = ent;
		} else
			*elp = st->tab[i];
	}
	return rc;
}

int
symtab_lookup_or_install_entry(struct syment **elp, 
			       struct symtab *st, struct syment *ent,
			       int *install)
{
	unsigned i;
	int rc = symtab_get_index(&i, st, ent->name, install);
	if (rc == 0) {
		if (install && *install == 1) {
			st->tab[i] = ent;
			ent->refcnt++;
			*elp = ent;
		} else
			*elp = st->tab[i];
	}
	return rc;
}

void
symtab_clear(struct symtab *st)
{
	unsigned i, hs;
  
	if (!st || !st->tab)
		return;

	hs = hash_size[st->hash_num];
	for (i = 0; i < hs; i++) {
		struct syment *elem = st->tab[i];
		if (elem) {
			symtab_free_syment(st, elem);
			st->tab[i] = NULL;
		}
	}
}

struct symtab *
symtab_create(size_t elsize, int flags,
	      void *(*alloc_fun)(size_t), void (*free_fun)(void *))
{
	struct symtab *st = malloc(sizeof(*st));
	if (st) {
		memset(st, 0, sizeof(*st));
		st->flags = flags;
		st->elsize = elsize;
		st->syment_alloc_fun = alloc_fun;
		st->syment_free_fun = free_fun;
		st->tab = calloc(hash_size[st->hash_num], sizeof(*st->tab));
		if (!st->tab) {
			free(st);
			st = NULL;
		}
	}
	return st;
}

void
symtab_destroy(struct symtab **pst)
{
	if (pst && *pst) {
		struct symtab *st = *pst;
		symtab_clear(st);
		free(st->tab);
		free(st);
		*pst = NULL;
	}
}

size_t
symtab_count_entries(struct symtab *st)
{
	unsigned i;
	size_t count = 0;
	
	for (i = 0; i < hash_size[st->hash_num]; i++)
		if (st->tab[i])
			count++;
	return count;
}

int
symtab_enumerate(struct symtab *st, symtab_enumerator_t fun, void *data)
{
	unsigned i;
	
	for (i = 0; i < hash_size[st->hash_num]; i++) {
		struct syment *ep = st->tab[i];
		if (ep) {
			int rc = fun(ep, data);
			if (rc)
				return rc;
		}
	}
	return 0;
}

int
symtab_import(struct symtab *dst, struct symtab *src,
	      symtab_selfun selfun, symtab_errfun errfun,
	      symtab_confun confun, symtab_cpyfun cpyfun,
	      void *closure)
{
	unsigned i;
	
	for (i = 0; i < hash_size[src->hash_num]; i++) {
		struct syment *srcent = src->tab[i];
		if (srcent && (!selfun || selfun(srcent, closure))) {
			struct syment *dstent;
			int install;
			unsigned j;
			int rc;

			if (cpyfun) {
				if (cpyfun(&dstent, srcent, dst->elsize,
					   closure))
					continue;
			} else {
				dstent = src->tab[i];
				dstent->refcnt++;
			}
			
			rc = symtab_get_index(&j, dst, dstent->name,
					      &install);
			if (rc) {
				if (!errfun
				    || errfun(rc, dst, srcent->name,
					      closure))
					return rc;
				else
					continue;
			}
			if (!install) {
				if (!confun)
					return EBUSY;
				dstent = dst->tab[j];
				rc = confun(dst, dstent, srcent, closure);
				if (rc)
					return rc;
				continue;
			}
			dst->tab[j] = dstent;
		}
	}
	return 0;
}
				
	








   
