/* Hash table functions
   Copyright (C) 1992 Free Software Foundation

This file is part of the GNU Hurd.

The GNU Hurd 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 2, or (at your option)
any later version.

The GNU Hurd 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 the GNU Hurd; see the file COPYING.  If not, write to
the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */

/* Written by Michael I. Bushnell.  */

#define HASH(pg) (id % ht->size)
#define REHASH(pg, h) ((id + (h * h)) % ht->size)

addhash (struct htable *ht,
	 void *item,
	 void ***locp,
	 int id)
{
  int h, firsth = -1;
  void **oldlist;
  int *oldids;
  int oldsize;
  int i;
  
  for (h = HASH (id); 
       (ht->tab[h] != 0 && ht->tab[h] != HASH_DEL && h != firsth);
       firsth = (firsth == -1) ? h : firsth, h = REHASH (id, h))
    ;

  if (ht->tab[h] == 0
      || ht->tab[h] == HASH_DEL)
    {
      ht->tab[h] = pg;
      ht->ids[h] = id;
      *locp = &pgrphash[h];
      return;
    }
  
  /* We have to rehash this again? */
  oldlist = ht->tab;
  oldsize = ht->size;
  oldids = ht->ids;
  
  ht->size = nextprime (2 * ht->size);
  ht->tab = malloc (ht->size * sizeof (struct void *));
  ht->ids = malloc (ht->size * sizeof (int));
  bzero (ht->tab, (ht->size * sizeof (struct void *)));
  
  if (oldlist)
    for (i = 0; i < oldsize; i++)
      if (oldlist[i] != 0
	  && oldlist[i] != HASH_DEL)
	addhash (ht, oldlist[i], locp, oldids[i]);
  addhash (ht, item, locp, id);
  
  if (oldlist)
    {
      free (oldlist);
      free (oldids);
    }
}

void *
findhash (struct htable *ht,
	  int id)
{
  int h, firsth = -1;
  for (h = HASH (id);
       ht->tab[h] != 0 && ht->ids[h] != id && h != firsth;
       firsth = (firsth == -1) ? h : firsth, h = REHASH (id, h))
    ;
  
  if (ht->ids[h] == id)
    return ht->tab[h];
  else
    return 0;
}

