Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
f737b3318e038374cb6be17c89b18497a7c165fb
[simgrid.git] / src / xbt / dict_elm.c
1 /* dict - a generic dictionary, variation over hash table                   */
2
3 /* Copyright (c) 2004-2011. The SimGrid Team.
4  * All rights reserved.                                                     */
5
6 /* This program is free software; you can redistribute it and/or modify it
7  * under the terms of the license (GNU LGPL) which comes with this package. */
8
9 #include "dict_private.h"       /* prototypes of this module */
10
11 XBT_LOG_EXTERNAL_CATEGORY(xbt_dict);
12 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_dict_elm, xbt_dict,
13                                 "Dictionaries internals");
14
15 XBT_LOG_NEW_SUBCATEGORY(xbt_dict_add, xbt_dict,
16                         "Dictionaries internals: elements addition");
17 XBT_LOG_NEW_SUBCATEGORY(xbt_dict_search, xbt_dict,
18                         "Dictionaries internals: searching");
19 XBT_LOG_NEW_SUBCATEGORY(xbt_dict_remove, xbt_dict,
20                         "Dictionaries internals: elements removal");
21 XBT_LOG_NEW_SUBCATEGORY(xbt_dict_collapse, xbt_dict,
22                         "Dictionaries internals: post-removal cleanup");
23
24 xbt_mallocator_t dict_elm_mallocator = NULL;
25
26 xbt_dictelm_t xbt_dictelm_new(xbt_dict_t dict, const char *key, int key_len,
27                               unsigned int hash_code, void *content,
28                               void_f_pvoid_t free_f)
29 {
30   xbt_dictelm_t element = xbt_mallocator_get(dict_elm_mallocator);
31
32   element->key = xbt_new(char, key_len + 1);
33   memcpy((void *) element->key, (void *) key, key_len);
34   element->key[key_len] = '\0';
35
36   element->key_len = key_len;
37   element->hash_code = hash_code;
38
39   element->content = content;
40   element->free_f = free_f;
41   element->next = NULL;
42
43   return element;
44 }
45
46 void xbt_dictelm_free(xbt_dict_t dict, xbt_dictelm_t element)
47 {
48   if (element != NULL) {
49     xbt_free(element->key);
50
51     if (element->free_f != NULL && element->content != NULL) {
52       element->free_f(element->content);
53     }
54
55     xbt_mallocator_release(dict_elm_mallocator, element);
56   }
57 }
58
59 void xbt_dictelm_set_data(xbt_dict_t dict, xbt_dictelm_t element,
60                           void *data, void_f_pvoid_t free_ctn)
61 {
62   if (element->free_f && element->content)
63     element->free_f(element->content);
64
65   element->content = data;
66   element->free_f = free_ctn;
67 }
68
69 void *dict_elm_mallocator_new_f(void)
70 {
71   return xbt_new(s_xbt_dictelm_t, 1);
72 }