dictionary.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. /*-------------------------------------------------------------------------*/
  2. /**
  3. @file dictionary.c
  4. @author N. Devillard
  5. @date Sep 2007
  6. @version $Revision: 1.27 $
  7. @brief Implements a dictionary for string variables.
  8. This module implements a simple dictionary object, i.e. a list
  9. of string/string associations. This object is useful to store e.g.
  10. informations retrieved from a configuration file (ini files).
  11. */
  12. /*--------------------------------------------------------------------------*/
  13. /*
  14. $Id: dictionary.c,v 1.27 2007-11-23 21:39:18 ndevilla Exp $
  15. $Revision: 1.27 $
  16. */
  17. /*---------------------------------------------------------------------------
  18. Includes
  19. ---------------------------------------------------------------------------*/
  20. #include "dictionary.h"
  21. #include <stdio.h>
  22. #include <stdlib.h>
  23. #include <string.h>
  24. #include <unistd.h>
  25. /** Maximum value size for integers and doubles. */
  26. #define MAXVALSZ 1024
  27. /** Minimal allocated number of entries in a dictionary */
  28. #define DICTMINSZ 128
  29. /** Invalid key token */
  30. #define DICT_INVALID_KEY ((char*)-1)
  31. /*---------------------------------------------------------------------------
  32. Private functions
  33. ---------------------------------------------------------------------------*/
  34. /* Doubles the allocated size associated to a pointer */
  35. /* 'size' is the current allocated size. */
  36. static void * mem_double(void * ptr, int size)
  37. {
  38. void * newptr ;
  39. newptr = calloc(2*size, 1);
  40. if (newptr==NULL) {
  41. return NULL ;
  42. }
  43. memcpy(newptr, ptr, size);
  44. free(ptr);
  45. return newptr ;
  46. }
  47. /*-------------------------------------------------------------------------*/
  48. /**
  49. @brief Duplicate a string
  50. @param s String to duplicate
  51. @return Pointer to a newly allocated string, to be freed with free()
  52. This is a replacement for strdup(). This implementation is provided
  53. for systems that do not have it.
  54. */
  55. /*--------------------------------------------------------------------------*/
  56. static char * xstrdup(char * s)
  57. {
  58. char * t ;
  59. if (!s)
  60. return NULL ;
  61. t = malloc(strlen(s)+1) ;
  62. if (t) {
  63. strcpy(t,s);
  64. }
  65. return t ;
  66. }
  67. /*---------------------------------------------------------------------------
  68. Function codes
  69. ---------------------------------------------------------------------------*/
  70. /*-------------------------------------------------------------------------*/
  71. /**
  72. @brief Compute the hash key for a string.
  73. @param key Character string to use for key.
  74. @return 1 unsigned int on at least 32 bits.
  75. This hash function has been taken from an Article in Dr Dobbs Journal.
  76. This is normally a collision-free function, distributing keys evenly.
  77. The key is stored anyway in the struct so that collision can be avoided
  78. by comparing the key itself in last resort.
  79. */
  80. /*--------------------------------------------------------------------------*/
  81. unsigned dictionary_hash(char * key)
  82. {
  83. int len ;
  84. unsigned hash ;
  85. int i ;
  86. len = strlen(key);
  87. for (hash=0, i=0 ; i<len ; i++) {
  88. hash += (unsigned)key[i] ;
  89. hash += (hash<<10);
  90. hash ^= (hash>>6) ;
  91. }
  92. hash += (hash <<3);
  93. hash ^= (hash >>11);
  94. hash += (hash <<15);
  95. return hash ;
  96. }
  97. /*-------------------------------------------------------------------------*/
  98. /**
  99. @brief Create a new dictionary object.
  100. @param size Optional initial size of the dictionary.
  101. @return 1 newly allocated dictionary objet.
  102. This function allocates a new dictionary object of given size and returns
  103. it. If you do not know in advance (roughly) the number of entries in the
  104. dictionary, give size=0.
  105. */
  106. /*--------------------------------------------------------------------------*/
  107. dictionary * dictionary_new(int size)
  108. {
  109. dictionary * d ;
  110. /* If no size was specified, allocate space for DICTMINSZ */
  111. if (size<DICTMINSZ) size=DICTMINSZ ;
  112. if (!(d = (dictionary *)calloc(1, sizeof(dictionary)))) {
  113. return NULL;
  114. }
  115. d->size = size ;
  116. d->val = (char **)calloc(size, sizeof(char*));
  117. d->key = (char **)calloc(size, sizeof(char*));
  118. d->hash = (unsigned int *)calloc(size, sizeof(unsigned));
  119. return d ;
  120. }
  121. /*-------------------------------------------------------------------------*/
  122. /**
  123. @brief Delete a dictionary object
  124. @param d dictionary object to deallocate.
  125. @return void
  126. Deallocate a dictionary object and all memory associated to it.
  127. */
  128. /*--------------------------------------------------------------------------*/
  129. void dictionary_del(dictionary * d)
  130. {
  131. int i ;
  132. if (d==NULL) return ;
  133. for (i=0 ; i<d->size ; i++) {
  134. if (d->key[i]!=NULL)
  135. free(d->key[i]);
  136. if (d->val[i]!=NULL)
  137. free(d->val[i]);
  138. }
  139. free(d->val);
  140. free(d->key);
  141. free(d->hash);
  142. free(d);
  143. return ;
  144. }
  145. /*-------------------------------------------------------------------------*/
  146. /**
  147. @brief Get a value from a dictionary.
  148. @param d dictionary object to search.
  149. @param key Key to look for in the dictionary.
  150. @param def Default value to return if key not found.
  151. @return 1 pointer to internally allocated character string.
  152. This function locates a key in a dictionary and returns a pointer to its
  153. value, or the passed 'def' pointer if no such key can be found in
  154. dictionary. The returned character pointer points to data internal to the
  155. dictionary object, you should not try to free it or modify it.
  156. */
  157. /*--------------------------------------------------------------------------*/
  158. char * dictionary_get(dictionary * d, char * key, char * def)
  159. {
  160. unsigned hash ;
  161. int i ;
  162. hash = dictionary_hash(key);
  163. for (i=0 ; i<d->size ; i++) {
  164. if (d->key[i]==NULL)
  165. continue ;
  166. /* Compare hash */
  167. if (hash==d->hash[i]) {
  168. /* Compare string, to avoid hash collisions */
  169. if (!strcmp(key, d->key[i])) {
  170. return d->val[i] ;
  171. }
  172. }
  173. }
  174. return def ;
  175. }
  176. /*-------------------------------------------------------------------------*/
  177. /**
  178. @brief Set a value in a dictionary.
  179. @param d dictionary object to modify.
  180. @param key Key to modify or add.
  181. @param val Value to add.
  182. @return int 0 if Ok, anything else otherwise
  183. If the given key is found in the dictionary, the associated value is
  184. replaced by the provided one. If the key cannot be found in the
  185. dictionary, it is added to it.
  186. It is Ok to provide a NULL value for val, but NULL values for the dictionary
  187. or the key are considered as errors: the function will return immediately
  188. in such a case.
  189. Notice that if you dictionary_set a variable to NULL, a call to
  190. dictionary_get will return a NULL value: the variable will be found, and
  191. its value (NULL) is returned. In other words, setting the variable
  192. content to NULL is equivalent to deleting the variable from the
  193. dictionary. It is not possible (in this implementation) to have a key in
  194. the dictionary without value.
  195. This function returns non-zero in case of failure.
  196. */
  197. /*--------------------------------------------------------------------------*/
  198. int dictionary_set(dictionary * d, char * key, char * val)
  199. {
  200. int i ;
  201. unsigned hash ;
  202. if (d==NULL || key==NULL) return -1 ;
  203. /* Compute hash for this key */
  204. hash = dictionary_hash(key) ;
  205. /* Find if value is already in dictionary */
  206. if (d->n>0) {
  207. for (i=0 ; i<d->size ; i++) {
  208. if (d->key[i]==NULL)
  209. continue ;
  210. if (hash==d->hash[i]) { /* Same hash value */
  211. if (!strcmp(key, d->key[i])) { /* Same key */
  212. /* Found a value: modify and return */
  213. if (d->val[i]!=NULL)
  214. free(d->val[i]);
  215. d->val[i] = val ? xstrdup(val) : NULL ;
  216. /* Value has been modified: return */
  217. return 0 ;
  218. }
  219. }
  220. }
  221. }
  222. /* Add a new value */
  223. /* See if dictionary needs to grow */
  224. if (d->n==d->size) {
  225. /* Reached maximum size: reallocate dictionary */
  226. d->val = (char **)mem_double(d->val, d->size * sizeof(char*)) ;
  227. d->key = (char **)mem_double(d->key, d->size * sizeof(char*)) ;
  228. d->hash = (unsigned int *)mem_double(d->hash, d->size * sizeof(unsigned)) ;
  229. if ((d->val==NULL) || (d->key==NULL) || (d->hash==NULL)) {
  230. /* Cannot grow dictionary */
  231. return -1 ;
  232. }
  233. /* Double size */
  234. d->size *= 2 ;
  235. }
  236. /* Insert key in the first empty slot */
  237. for (i=0 ; i<d->size ; i++) {
  238. if (d->key[i]==NULL) {
  239. /* Add key here */
  240. break ;
  241. }
  242. }
  243. /* Copy key */
  244. d->key[i] = xstrdup(key);
  245. d->val[i] = val ? xstrdup(val) : NULL ;
  246. d->hash[i] = hash;
  247. d->n ++ ;
  248. return 0 ;
  249. }
  250. /*-------------------------------------------------------------------------*/
  251. /**
  252. @brief Delete a key in a dictionary
  253. @param d dictionary object to modify.
  254. @param key Key to remove.
  255. @return void
  256. This function deletes a key in a dictionary. Nothing is done if the
  257. key cannot be found.
  258. */
  259. /*--------------------------------------------------------------------------*/
  260. void dictionary_unset(dictionary * d, char * key)
  261. {
  262. unsigned hash ;
  263. int i ;
  264. if (key == NULL) {
  265. return;
  266. }
  267. hash = dictionary_hash(key);
  268. for (i=0 ; i<d->size ; i++) {
  269. if (d->key[i]==NULL)
  270. continue ;
  271. /* Compare hash */
  272. if (hash==d->hash[i]) {
  273. /* Compare string, to avoid hash collisions */
  274. if (!strcmp(key, d->key[i])) {
  275. /* Found key */
  276. break ;
  277. }
  278. }
  279. }
  280. if (i>=d->size)
  281. /* Key not found */
  282. return ;
  283. free(d->key[i]);
  284. d->key[i] = NULL ;
  285. if (d->val[i]!=NULL) {
  286. free(d->val[i]);
  287. d->val[i] = NULL ;
  288. }
  289. d->hash[i] = 0 ;
  290. d->n -- ;
  291. return ;
  292. }
  293. /*-------------------------------------------------------------------------*/
  294. /**
  295. @brief Dump a dictionary to an opened file pointer.
  296. @param d Dictionary to dump
  297. @param f Opened file pointer.
  298. @return void
  299. Dumps a dictionary onto an opened file pointer. Key pairs are printed out
  300. as @c [Key]=[Value], one per line. It is Ok to provide stdout or stderr as
  301. output file pointers.
  302. */
  303. /*--------------------------------------------------------------------------*/
  304. void dictionary_dump(dictionary * d, FILE * out)
  305. {
  306. int i ;
  307. if (d==NULL || out==NULL) return ;
  308. if (d->n<1) {
  309. fprintf(out, "empty dictionary\n");
  310. return ;
  311. }
  312. for (i=0 ; i<d->size ; i++) {
  313. if (d->key[i]) {
  314. fprintf(out, "%20s\t[%s]\n",
  315. d->key[i],
  316. d->val[i] ? d->val[i] : "UNDEF");
  317. }
  318. }
  319. return ;
  320. }
  321. /* Test code */
  322. #ifdef TESTDIC
  323. #define NVALS 20000
  324. int main(int argc, char *argv[])
  325. {
  326. dictionary * d ;
  327. char * val ;
  328. int i ;
  329. char cval[90] ;
  330. /* Allocate dictionary */
  331. printf("allocating...\n");
  332. d = dictionary_new(0);
  333. /* Set values in dictionary */
  334. printf("setting %d values...\n", NVALS);
  335. for (i=0 ; i<NVALS ; i++) {
  336. sprintf(cval, "%04d", i);
  337. dictionary_set(d, cval, "salut");
  338. }
  339. printf("getting %d values...\n", NVALS);
  340. for (i=0 ; i<NVALS ; i++) {
  341. sprintf(cval, "%04d", i);
  342. val = dictionary_get(d, cval, DICT_INVALID_KEY);
  343. if (val==DICT_INVALID_KEY) {
  344. printf("cannot get value for key [%s]\n", cval);
  345. }
  346. }
  347. printf("unsetting %d values...\n", NVALS);
  348. for (i=0 ; i<NVALS ; i++) {
  349. sprintf(cval, "%04d", i);
  350. dictionary_unset(d, cval);
  351. }
  352. if (d->n != 0) {
  353. printf("error deleting values\n");
  354. }
  355. printf("deallocating...\n");
  356. dictionary_del(d);
  357. return 0 ;
  358. }
  359. #endif
  360. /* vim: set ts=4 et sw=4 tw=75 */