00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025 #include <string.h>
00026 #include <stdio.h>
00027 #include <assert.h>
00028
00029 #include "dictionary.h"
00030
00031
00032 void *
00033 dict_lookup (const dictionary *d, const char *key)
00034 {
00035 dict_pair *top;
00036 dict_pair *middle;
00037 dict_pair *bottom;
00038 int result;
00039
00040 assert (d);
00041 assert (key);
00042
00043 top = d->dict;
00044 bottom = d->dict + d->size;
00045
00046 while (top < bottom)
00047 {
00048 middle = top + ((bottom - top) / 2);
00049
00050 result = strcmp (key, middle->key);
00051 if (result == 0)
00052 return middle->value;
00053
00054 if (result < 0)
00055 bottom = middle;
00056 else
00057 top = middle + 1;
00058 }
00059
00060 return 0;
00061 }
00062
00063
00064
00065 #ifdef UNIT_TEST_DICTIONARY_C
00066
00067 #include <stdio.h>
00068
00069 int lookup (const dictionary* dict, const char* key)
00070 {
00071 int *valptr = (int*)(dict_lookup (dict, key));
00072
00073 return valptr ? *valptr : 999;
00074 }
00075
00076 int main (int argc, char **argv)
00077 {
00078 int values[] = { 5, 6, 7, 8, 9 };
00079 int result;
00080 int i;
00081
00082 dict_pair pair_array[] = {
00083 { "aardbei", &values[0] },
00084 { "banaan", &values[1] },
00085 { "citroen", &values[2] },
00086 { "druif", &values[3] },
00087 { "eland", &values[4] } };
00088
00089 dictionary dict = { pair_array, 5 };
00090
00091 for (i = 0 ; i < 5 ; ++i)
00092 {
00093 result = lookup (&dict, pair_array[i].key);
00094 if (result != values[i])
00095 {
00096 printf ("Lookup of parameter %s returned %i, expected %i/n",
00097 pair_array[i].key, result, values[i]);
00098 exit (1);
00099 }
00100 }
00101
00102 if (lookup (&dict, "xxx") != 999)
00103 {
00104 printf ("Lookup of non-existing parameter did not fail, " \
00105 "but should have/n");
00106 exit (1);
00107 }
00108
00109 exit (0);
00110 }
00111
00112 #endif