1 /* lib - a generic library, variation over dictionary */
3 /* Copyright (c) 2011. The SimGrid Team.
4 * All rights reserved. */
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. */
9 #include <xbt/sysdep.h>
13 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_lib, xbt,
14 "A dict with keys of type (name, level)");
16 xbt_lib_t xbt_lib_new(void)
19 lib = xbt_new(s_xbt_lib_t, 1);
20 lib->dict = xbt_dict_new_homogeneous(xbt_free);
26 void xbt_lib_free(xbt_lib_t *plib)
28 xbt_lib_t lib = *plib;
30 xbt_dict_cursor_t cursor;
33 xbt_dict_foreach (lib->dict, cursor, key, elts) {
35 for (i = 0 ; i < lib->levels ; i++)
37 lib->free_f[i](elts[i]);
39 xbt_dict_free(&lib->dict);
40 xbt_free(lib->free_f);
46 int xbt_lib_add_level(xbt_lib_t lib, void_f_pvoid_t free_f)
48 XBT_DEBUG("xbt_lib_add_level");
49 xbt_assert(xbt_dict_is_empty(lib->dict),
50 "Lib is not empty, cannot add a level");
51 lib->free_f = xbt_realloc(lib->free_f,
52 sizeof(void_f_pvoid_t) * (lib->levels + 1));
53 lib->free_f[lib->levels] = free_f;
57 void xbt_lib_set(xbt_lib_t lib, const char *key, int level, void *obj)
59 XBT_DEBUG("xbt_lib_set key '%s:%d' with object %p", key, level, obj);
60 void **elts = xbt_dict_get_or_null(lib->dict, key);
62 elts = xbt_new0(void *, lib->levels);
63 xbt_dict_set(lib->dict, key, elts, NULL);
66 XBT_DEBUG("Replace %p by %p element under key '%s:%d'",
67 elts[level], obj, key, level);
68 lib->free_f[level](elts[level]);
73 void *xbt_lib_get_or_null(xbt_lib_t lib, const char *key, int level)
75 void **elts = xbt_dict_get_or_null(lib->dict, key);
76 return elts ? elts[level] : NULL;