Merge branch 'master' of https://git.maemo.org/projects/erwise
[erwise] / Cl / WWWLibrary / HTAtom.c
1 /*                      Atoms: Names to numbers                 HTAtom.c
2 **                      =======================
3 **
4 **      Atoms are names which are given representative pointer values
5 **      so that they can be stored more efficiently, and comparisons
6 **      for equality done more efficiently.
7 **
8 **      Atoms are kept in a hash table consisting of an array of linked lists.
9 **
10 ** Authors:
11 **      TBL     Tim Berners-Lee, WorldWideWeb project, CERN
12 **      (c) Copyright CERN 1991 - See Copyright.html
13 **
14 */
15 #define HASH_SIZE       101             /* Tunable */
16 #include "HTUtils.h"
17 #include "HTAtom.h"
18
19 #ifdef ERWISE
20 #include <stdio.h>
21 #endif
22
23 PRIVATE HTAtom * hash_table[HASH_SIZE];
24 PRIVATE BOOL initialised = NO;
25
26 #ifdef __STDC__
27 PUBLIC HTAtom * HTAtom_for(const char * string)
28 #else
29 PUBLIC HTAtom * HTAtom_for(string)
30     char * string;
31 #endif
32 {
33     int hash;
34     CONST char * p;
35     HTAtom * a;
36     
37     /*          First time around, clear hash table
38     */
39     if (!initialised) {
40         int i;
41         for (i=0; i<HASH_SIZE; i++)
42             hash_table[i] = (HTAtom *) 0;
43         initialised = YES;
44     }
45     
46     /*          Generate hash function
47     */
48     for(p=string, hash=0; *p; p++) {
49         hash = (hash * 3 + *p) % HASH_SIZE;
50     }
51     
52     /*          Search for the string in the list
53     */
54     for (a=hash_table[hash]; a; a=a->next) {
55         if (0==strcmp(a->name, string)) {
56             if (TRACE) printf("HTAtom: Old atom %d for `&s'\n", a, string);
57             return a;                           /* Found: return it */
58         }
59     }
60     
61     /*          Generate a new entry
62     */
63     a = (HTAtom *)malloc(sizeof(*a));
64     if (a == NULL) outofmem(__FILE__, "HTAtom_for");
65     a->name = (char *)malloc(strlen(string)+1);
66     if (a->name == NULL) outofmem(__FILE__, "HTAtom_for");
67     strcpy(a->name, string);
68     a->next = hash_table[hash];         /* Put onto the head of list */
69     hash_table[hash] = a;
70     if (TRACE) printf("HTAtom: New atom %d for `&s'\n", a, string);
71     return a;
72 }
73
74