Subversion Repositories Kolibri OS

Rev

Blame | Last modification | View Log | Download | RSS feed

  1. # CDict - a simple dictionary implementation in C
  2. ## Ready to use!
  3.  
  4. It may be used out of the box with key and value of type `CStr` (which is `char *` - zero-terminated string). Once it instantiated in some file using `CDICT_INST` definition:
  5.  
  6. ```C
  7. #define CDICT_INST
  8. #include "cdict.h"
  9. ```
  10.  
  11. It may be then declared just using `#include`:
  12.  
  13. ```C
  14. #include "cdict.h"
  15.  
  16. int main() {
  17.     CDict_CStr_CStr dict;
  18.     if (!cdict_CStr_CStr_init(&dict)) {
  19.         printf("CDict returned error #%d", dict.error_code);
  20.         return 0;
  21.     }
  22.     cdict_CStr_CStr_add_vv(&dict, "key_a", "value_a", CDICT_REPLACE_EXIST);
  23.     printf("[key_a] = \"%s\"\n", cdict_CStr_CStr_get_v(&dict, "key_a"));
  24. }
  25. ```
  26.  
  27. ## Easy to configure!
  28.  
  29. If you want to create a dictionary for other key types you should provide your own keys hashing and comparsion functions, in such case the instantiation of the library will look like this:
  30.  
  31. ```C
  32. #define CDICT_INST
  33. #define CDICT_KEY_T MyType
  34. #define CDICT_HASH_FN(pkey) my_hash(pkey)
  35. #define CDICT_CMP_FN(pkey0, pkey1) my_cmp(pkey0, pkey1)
  36. #include "cdict.h"
  37.  
  38. int my_cmp(MyType *pkey0, MyType *pkey1) {
  39.     // Return `whatever_negative` if `key0 < key1`, `0` if `key0 == key1` and `whatever_positive` if `key0 > key1`
  40. }
  41.  
  42. unsigned long my_hash(MyType *key) {
  43.     // Return the hash of the key
  44. }
  45. ```
  46.  
  47. Then to use the new dictionary you only need to define key type before the header inclusion:
  48.  
  49. ```C
  50. #define CDICT_KEY_T MyType
  51. #include "cdict.h"
  52.  
  53. // ...
  54.     CDict_MyType_CStr dict;
  55.     cdict_MyType_CStr_init(&dict);
  56. // ...
  57. ```
  58.  
  59. If you want to specify the type of values - just define the type:
  60.  
  61. ```C
  62. #define CDICT_VAL_T MyValueType
  63. ```
  64.  
  65. And so on.
  66.  
  67. ## Dependency-free!
  68.  
  69. Every single used dependency may be redefined:
  70.  
  71. ```C
  72. #define CDICT_ASSERT_FN(x) my_assert(x);
  73. ```
  74.  
  75. ## Flexible!
  76.  
  77. May define user data to be used in overriden functions (for example - custom allocators):
  78.  
  79. ```C
  80. #define CDICT_USER_DATA_T UserData
  81. #define CDICT_HASHTAB_ITEM_ALLOC_FN(cdict, size) item_alloc(cdict, size)
  82. #define CDICT_HASHTAB_ITEM_FREE_FN(cdict, ptr) item_free(cdict, ptr)
  83. #define CDICT_HASHTAB_ALLOC_FN(cdict, size) hashtab_alloc(cdict, size)
  84. ```
  85.  
  86. ## Checkout
  87.  
  88. [The library](cdict.h).
  89.