source: trunk/greenstone3-extensions/vishnu/src/ckindexer/hash.c@ 8189

Last change on this file since 8189 was 8189, checked in by kjdon, 20 years ago

first version of Imperial College's Visualiser code

  • Property svn:keywords set to Author Date Id Revision
File size: 1.8 KB
Line 
1#include <stdlib.h>
2#include <stdio.h>
3#include <string.h>
4#include <assert.h>
5
6
7#include "hash.h"
8
9int prime(size_t n)
10{
11 size_t i;
12
13 if (n % 2 == 0)
14 return (n==2);
15 if (n % 3 == 0)
16 return (n==3);
17 if (n % 5 == 0)
18 return (n==5);
19 for (i=7; i*i <= n; i+=2)
20 if (n % i == 0)
21 return 0;
22 return 1;
23}
24
25
26
27size_t getBiggerPrime(size_t val)
28{
29 while(prime(++val)==0);
30 return val;
31}
32
33
34size_t hashSize;
35
36HashPtr *initHash(size_t val)
37{
38 size_t c;
39 HashPtr *table;
40 hashSize=getBiggerPrime(val+(val/2));
41 table =(HashPtr *)malloc(sizeof(HashPtr)*hashSize);
42 if(table==NULL)
43 {
44 hashSize=getBiggerPrime(val);
45 fprintf(stderr,"Having to use smaller hash %d table size\n",
46 hashSize);
47 table =(HashPtr *)malloc(sizeof(HashPtr)*hashSize);
48 }
49 assert(table);
50 for(c=0;c<hashSize;c++) table[c]=NULL;
51 return table;
52}
53
54
55
56size_t hash(char *s)
57{
58 size_t h = 0;
59 while (*s)
60 h+=*s++;
61 return abs(h % hashSize);
62}
63
64
65HashNode *hRetrieve(HashPtr *table, char *target)
66{
67 return hSeqSearch(table[hash(target)],target);
68}
69
70void hInsert(HashPtr *table, HashNode *node)
71{
72 int h;
73 h= hash(node->inf.key);
74 node->next=table[h];
75 table[h]=node;
76}
77
78HashNode *hSeqSearch(HashPtr node, char *target)
79{
80 HashPtr location;
81 for (location=node;location!=NULL;location=location->next)
82 if (!strcmp(location->inf.key,target)) return location;
83 return NULL;
84}
85
86void vapeHashNode(HashPtr node)
87{
88 if(node->next) vapeHashNode(node->next);
89 free(node);
90}
91
92void vapeHash(HashPtr *table)
93{
94 size_t c;
95 for (c=0;c<hashSize;c++)
96 if(table[c]) vapeHashNode(table[c]);
97 free(table);
98}
Note: See TracBrowser for help on using the repository browser.