1 /* 2 Copyright (c) 2011, 2021, Oracle and/or its affiliates. All rights 3 reserved. 4 5 This program is free software; you can redistribute it and/or modify 6 it under the terms of the GNU General Public License, version 2.0, 7 as published by the Free Software Foundation. 8 9 This program is also distributed with certain software (including 10 but not limited to OpenSSL) that is licensed under separate terms, 11 as designated in a particular file or component or in included license 12 documentation. The authors of MySQL hereby grant you an additional 13 permission to link the program and your derivative works with the 14 separately licensed software that they have included with MySQL. 15 16 This program is distributed in the hope that it will be useful, 17 but WITHOUT ANY WARRANTY; without even the implied warranty of 18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 GNU General Public License, version 2.0, for more details. 20 21 You should have received a copy of the GNU General Public License 22 along with this program; if not, write to the Free Software 23 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 24 02110-1301 USA 25 */ 26 27 28 /* SIMPLE HASH TABLE. Maps a null-terminated string to a pointer. 29 Creates and manages its own copy of the string. 30 */ 31 #include <stdio.h> 32 #include <string.h> 33 34 template<typename T> class LookupTable { 35 public: 36 int elements; 37 bool do_free_values; 38 39 LookupTable(int sz = 128) : 40 elements(0), 41 do_free_values(false), 42 size(sz), 43 symtab(new Entry *[sz]) 44 { 45 for(int i = 0 ; i < size ; i++) 46 symtab[i] = 0; 47 } 48 49 ~LookupTable()50 ~LookupTable() { 51 for(int i = 0 ; i < size ; i++) { 52 Entry *sym = symtab[i]; 53 while(sym) { 54 if(do_free_values) free((void *) sym->value); 55 Entry *next = sym->next; 56 delete sym; 57 sym = next; 58 } 59 } 60 delete[] symtab; 61 } 62 63 find(const char * name)64 T * find(const char *name) { 65 Uint32 h = do_hash(name) % size; 66 for(Entry *sym = symtab[h] ; sym != 0 ; sym = sym->next) 67 if(strcmp(name, sym->key) == 0) 68 return sym->value; 69 return 0; 70 } 71 insert(const char * name,T * value)72 void insert(const char *name, T * value) { 73 Uint32 h = do_hash(name) % size; 74 Entry *sym = new Entry(name, value); 75 sym->next = symtab[h]; 76 symtab[h] = sym; 77 elements++; 78 } 79 80 81 private: 82 class Entry { 83 public: 84 char *key; 85 T * value; 86 Entry *next; 87 Entry(const char * name,T * val)88 Entry(const char *name, T * val) { 89 key = strdup(name); 90 value = val; 91 } 92 ~Entry()93 ~Entry() { 94 free(key); 95 } 96 }; 97 98 int size; 99 Entry ** symtab; 100 do_hash(const char * string)101 Uint32 do_hash(const char *string) { 102 Uint32 h = 0; 103 for(const char *s = string; *s != 0; s++) h = 37 * h + *s; 104 return h; 105 } 106 }; 107 108