00001 //======================================================================== 00002 // 00003 // NameToCharCode.cc 00004 // 00005 // Copyright 2001-2002 Glyph & Cog, LLC 00006 // 00007 //======================================================================== 00008 00009 #ifdef __GNUC__ 00010 #pragma implementation 00011 #endif 00012 00013 #include <aconf.h> 00014 #include <string.h> 00015 #include "gmem.h" 00016 #include "NameToCharCode.h" 00017 00018 //------------------------------------------------------------------------ 00019 00020 struct NameToCharCodeEntry { 00021 char *name; 00022 CharCode c; 00023 }; 00024 00025 //------------------------------------------------------------------------ 00026 00027 NameToCharCode::NameToCharCode() { 00028 int i; 00029 00030 size = 31; 00031 len = 0; 00032 tab = (NameToCharCodeEntry *)gmalloc(size * sizeof(NameToCharCodeEntry)); 00033 for (i = 0; i < size; ++i) { 00034 tab[i].name = NULL; 00035 } 00036 } 00037 00038 NameToCharCode::~NameToCharCode() { 00039 int i; 00040 00041 for (i = 0; i < size; ++i) { 00042 if (tab[i].name) { 00043 gfree(tab[i].name); 00044 } 00045 } 00046 gfree(tab); 00047 } 00048 00049 void NameToCharCode::add(char *name, CharCode c) { 00050 NameToCharCodeEntry *oldTab; 00051 int h, i, oldSize; 00052 00053 // expand the table if necessary 00054 if (len >= size / 2) { 00055 oldSize = size; 00056 oldTab = tab; 00057 size = 2*size + 1; 00058 tab = (NameToCharCodeEntry *)gmalloc(size * sizeof(NameToCharCodeEntry)); 00059 for (h = 0; h < size; ++h) { 00060 tab[h].name = NULL; 00061 } 00062 for (i = 0; i < oldSize; ++i) { 00063 if (oldTab[i].name) { 00064 h = hash(oldTab[i].name); 00065 while (tab[h].name) { 00066 if (++h == size) { 00067 h = 0; 00068 } 00069 } 00070 tab[h] = oldTab[i]; 00071 } 00072 } 00073 gfree(oldTab); 00074 } 00075 00076 // add the new name 00077 h = hash(name); 00078 while (tab[h].name && strcmp(tab[h].name, name)) { 00079 if (++h == size) { 00080 h = 0; 00081 } 00082 } 00083 if (!tab[h].name) { 00084 tab[h].name = copyString(name); 00085 } 00086 tab[h].c = c; 00087 00088 ++len; 00089 } 00090 00091 CharCode NameToCharCode::lookup(char *name) { 00092 int h; 00093 00094 h = hash(name); 00095 while (tab[h].name) { 00096 if (!strcmp(tab[h].name, name)) { 00097 return tab[h].c; 00098 } 00099 if (++h == size) { 00100 h = 0; 00101 } 00102 } 00103 return 0; 00104 } 00105 00106 int NameToCharCode::hash(char *name) { 00107 char *p; 00108 unsigned int h; 00109 00110 h = 0; 00111 for (p = name; *p; ++p) { 00112 h = 17 * h + (int)(*p & 0xff); 00113 } 00114 return (int)(h % size); 00115 }
1.4.2