Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Use new/delete for s_xbt_cfgelm_t
[simgrid.git] / src / xbt / config.cpp
1 /* Copyright (c) 2004-2014,2016. The SimGrid Team.
2  * All rights reserved.                                                     */
3
4 #include <stdio.h>
5
6 #include <functional>
7 #include <string>
8 #include <type_traits>
9
10 #include <xbt/config.h>
11 #include <xbt/config.hpp>
12 #include "xbt/misc.h"
13 #include "xbt/sysdep.h"
14 #include "xbt/log.h"
15 #include "xbt/ex.h"
16 #include "xbt/dynar.h"
17 #include "xbt/dict.h"
18
19 // *****
20
21 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_cfg, xbt, "configuration support");
22
23 XBT_EXPORT_NO_IMPORT(xbt_cfg_t) simgrid_config = NULL;
24
25 namespace {
26
27 // We could define some range/iterator for the num values.
28 static inline
29 void increment(e_xbt_cfgelm_type_t& type)
30 {
31   typedef std::underlying_type<e_xbt_cfgelm_type_t>::type underlying_type;
32   type = (e_xbt_cfgelm_type_t) ((underlying_type) type + 1);
33 }
34
35 }
36
37 /* xbt_cfgelm_t: the typedef corresponding to a config variable. */
38
39 typedef struct s_xbt_cfgelm_t {
40   /* Description */
41   std::string desc;
42
43   /* Allowed type of the variable */
44   e_xbt_cfgelm_type_t type;
45   bool isdefault = true;
46
47   /* Callbacks */
48   xbt_cfg_cb_t cb_set = nullptr;
49
50   /* Advanced callbacks */
51   xbt_cfg_cb_ext_t cb_set_ext = nullptr;
52   void* cb_set_data = nullptr;
53   xbt_cfg_cb_free_t cb_set_free = nullptr;
54
55   /* actual content (could be an union or something) */
56   xbt_dynar_t content = nullptr;
57
58   ~s_xbt_cfgelm_t()
59   {
60     XBT_DEBUG("Frees cfgelm %p", this);
61     if (!this)
62       return;
63     if (this->cb_set_free)
64       this->cb_set_free(this->cb_set_data);
65     if (this->type != xbt_cfgelm_alias)
66       xbt_dynar_free(&(this->content));
67   }
68
69 } s_xbt_cfgelm_t, *xbt_cfgelm_t;
70
71 static const char *xbt_cfgelm_type_name[xbt_cfgelm_type_count] = { "int", "double", "string", "boolean", "any", "outofbound" };
72
73 const struct xbt_boolean_couple xbt_cfgelm_boolean_values[] = {
74   { "yes",    "no"},
75   {  "on",   "off"},
76   {"true", "false"},
77   {   "1",     "0"},
78   {  NULL,    NULL}
79 };
80
81 /* Internal stuff used in cache to free a variable */
82 static void xbt_cfgelm_free(void *data)
83 {
84   delete (xbt_cfgelm_t) data;
85 }
86
87 /* Retrieve the variable we'll modify */
88 static xbt_cfgelm_t xbt_cfgelm_get(xbt_cfg_t cfg, const char *name, e_xbt_cfgelm_type_t type);
89
90 /*----[ Memory management ]-----------------------------------------------*/
91 /** @brief Constructor
92  *
93  * Initialise a config set
94  */
95 xbt_cfg_t xbt_cfg_new(void)
96 {
97   return (xbt_cfg_t) xbt_dict_new_homogeneous(&xbt_cfgelm_free);
98 }
99
100 /** @brief Destructor */
101 void xbt_cfg_free(xbt_cfg_t * cfg)
102 {
103   XBT_DEBUG("Frees cfg set %p", cfg);
104   xbt_dict_free((xbt_dict_t *) cfg);
105 }
106
107 /** @brief Dump a config set for debuging purpose
108  *
109  * @param name The name to give to this config set
110  * @param indent what to write at the beginning of each line (right number of spaces)
111  * @param cfg the config set
112  */
113 void xbt_cfg_dump(const char *name, const char *indent, xbt_cfg_t cfg)
114 {
115   xbt_dict_t dict = (xbt_dict_t) cfg;
116   xbt_dict_cursor_t cursor = NULL;
117   xbt_cfgelm_t variable = NULL;
118   char *key = NULL;
119   int i;
120   int size;
121   int ival;
122   char *sval;
123   double dval;
124
125   if (name)
126     printf("%s>> Dumping of the config set '%s':\n", indent, name);
127
128   xbt_dict_foreach(dict, cursor, key, variable) {
129     printf("%s  %s:", indent, key);
130
131     size = xbt_dynar_length(variable->content);
132     printf ("%s. Actual size=%d. postset=%p\n",
133             xbt_cfgelm_type_name[variable->type], size, variable->cb_set);
134
135     switch (variable->type) {
136     case xbt_cfgelm_int:
137       for (i = 0; i < size; i++) {
138         ival = xbt_dynar_get_as(variable->content, i, int);
139         printf("%s    %d\n", indent, ival);
140       }
141       break;
142     case xbt_cfgelm_double:
143       for (i = 0; i < size; i++) {
144         dval = xbt_dynar_get_as(variable->content, i, double);
145         printf("%s    %f\n", indent, dval);
146       }
147       break;
148     case xbt_cfgelm_string:
149       for (i = 0; i < size; i++) {
150         sval = xbt_dynar_get_as(variable->content, i, char *);
151         printf("%s    %s\n", indent, sval);
152       }
153       break;
154     case xbt_cfgelm_boolean:
155       for (i = 0; i < size; i++) {
156         ival = xbt_dynar_get_as(variable->content, i, int);
157         printf("%s    %d\n", indent, ival);
158       }
159       break;
160     case xbt_cfgelm_alias:
161       /* no content */
162       break;
163     default:
164       printf("%s    Invalid type!!\n", indent);
165       break;
166     }
167   }
168
169   if (name)
170     printf("%s<< End of the config set '%s'\n", indent, name);
171   fflush(stdout);
172
173   xbt_dict_cursor_free(&cursor);
174 }
175
176 /*----[ Registering stuff ]-----------------------------------------------*/
177 /** @brief Register an element within a config set
178  *
179  *  @param cfg the config set
180  *  @param name the name of the config element
181  *  @param desc a description for this item (used by xbt_cfg_help())
182  *  @param type the type of the config element
183  *  @param cb_set callback function called when a value is set
184  */
185 static void xbt_cfg_register(
186   xbt_cfg_t * cfg, const char *name, const char *desc, e_xbt_cfgelm_type_t type,
187   xbt_cfg_cb_t cb_set,
188   xbt_cfg_cb_ext_t cb_set_ext, void* cb_set_data, xbt_cfg_cb_free_t cb_set_free)
189 {
190   if (*cfg == NULL)
191     *cfg = xbt_cfg_new();
192   xbt_assert(type >= xbt_cfgelm_int && type <= xbt_cfgelm_boolean,
193               "type of %s not valid (%d should be between %d and %d)",
194              name, (int)type, xbt_cfgelm_int, xbt_cfgelm_boolean);
195
196   xbt_cfgelm_t res = (xbt_cfgelm_t) xbt_dict_get_or_null((xbt_dict_t) * cfg, name);
197   xbt_assert(NULL == res, "Refusing to register the config element '%s' twice.", name);
198
199   res = new s_xbt_cfgelm_t();
200   XBT_DEBUG("Register cfg elm %s (%s) (%s (=%d) @%p in set %p)",
201             name, desc, xbt_cfgelm_type_name[type], (int)type, res, *cfg);
202   res->type = type;
203   res->desc = desc;
204   res->cb_set = cb_set;
205   res->cb_set_ext = cb_set_ext;
206   res->cb_set_data = cb_set_data;
207   res->cb_set_free = cb_set_free;
208
209   switch (type) {
210   case xbt_cfgelm_int:
211     res->content = xbt_dynar_new(sizeof(int), NULL);
212     break;
213   case xbt_cfgelm_double:
214     res->content = xbt_dynar_new(sizeof(double), NULL);
215     break;
216   case xbt_cfgelm_string:
217     res->content = xbt_dynar_new(sizeof(char *), xbt_free_ref);
218     break;
219   case xbt_cfgelm_boolean:
220     res->content = xbt_dynar_new(sizeof(int), NULL);
221     break;
222   default:
223     XBT_ERROR("%d is an invalid type code", (int)type);
224     break;
225   }
226
227   xbt_dict_set((xbt_dict_t) * cfg, name, res, NULL);
228 }
229
230 void xbt_cfg_register_double(const char *name, double default_value,xbt_cfg_cb_t cb_set, const char *desc){
231   xbt_cfg_register(&simgrid_config,name,desc,xbt_cfgelm_double,cb_set, NULL, NULL, NULL);
232   xbt_cfg_setdefault_double(name, default_value);
233 }
234 void xbt_cfg_register_int(const char *name, int default_value,xbt_cfg_cb_t cb_set, const char *desc) {
235   xbt_cfg_register(&simgrid_config,name,desc,xbt_cfgelm_int,cb_set, NULL, NULL, NULL);
236   xbt_cfg_setdefault_int(name, default_value);
237 }
238 void xbt_cfg_register_string(const char *name, const char *default_value, xbt_cfg_cb_t cb_set, const char *desc){
239   xbt_cfg_register(&simgrid_config,name,desc,xbt_cfgelm_string,cb_set, NULL, NULL, NULL);
240   xbt_cfg_setdefault_string(name, default_value);
241 }
242 void xbt_cfg_register_boolean(const char *name, const char*default_value,xbt_cfg_cb_t cb_set, const char *desc){
243   xbt_cfg_register(&simgrid_config,name,desc,xbt_cfgelm_boolean,cb_set, NULL, NULL, NULL);
244   xbt_cfg_setdefault_boolean(name, default_value);
245 }
246
247 /** Register a config with an extended callback
248  *
249  *  @param name      Name of the flag
250  *  @param desc      Description of the flag
251  *  @param type      Type of the flag
252  *  @param cb        Extended callback
253  *  @param data      Data associated with the callback
254  *  @param data_free Function used to free the callback data (or NULL)
255  */
256 void xbt_cfg_register_ext(const char *name, const char *desc, e_xbt_cfgelm_type_t type,
257   xbt_cfg_cb_ext_t cb, void* data, xbt_cfg_cb_free_t data_free)
258 {
259   xbt_cfg_register(&simgrid_config, name, desc, type, NULL, cb, data, data_free);
260 }
261
262 void xbt_cfg_register_alias(const char *newname, const char *oldname)
263 {
264   if (simgrid_config == NULL)
265     simgrid_config = xbt_cfg_new();
266
267   xbt_cfgelm_t res = (xbt_cfgelm_t) xbt_dict_get_or_null((xbt_dict_t) simgrid_config, oldname);
268   xbt_assert(NULL == res, "Refusing to register the option '%s' twice.", oldname);
269
270   res = (xbt_cfgelm_t) xbt_dict_get_or_null((xbt_dict_t) simgrid_config, newname);
271   xbt_assert(res, "Cannot define an alias to the non-existing option '%s'.", newname);
272
273   res = new s_xbt_cfgelm_t();
274   XBT_DEBUG("Register cfg alias %s -> %s)",oldname,newname);
275
276   res->desc = bprintf("Deprecated alias for %s",newname);
277   res->type = xbt_cfgelm_alias;
278   res->content = (xbt_dynar_t)newname;
279
280   xbt_dict_set((xbt_dict_t) simgrid_config, oldname, res, NULL);
281 }
282
283 /**
284  * @brief Parse a string and register the stuff described.
285  *
286  * @param cfg the config set
287  * @param entry a string describing the element to register
288  *
289  * The string may consist in several variable descriptions separated by a space.
290  * Each of them must use the following syntax: \<name\>:\<type\>
291  * with type being one of  'string','int','bool' or 'double'.
292  *
293  * Note that this does not allow to set the description, so you should prefer the other interface
294  */
295 void xbt_cfg_register_str(xbt_cfg_t * cfg, const char *entry)
296 {
297   char *entrycpy = xbt_strdup(entry);
298   char *tok;
299
300   e_xbt_cfgelm_type_t type;
301   XBT_DEBUG("Register string '%s'", entry);
302
303   tok = strchr(entrycpy, ':');
304   xbt_assert(tok, "Invalid config element descriptor: %s; Should be <name>:<type>", entry);
305   *(tok++) = '\0';
306
307   for (type = (e_xbt_cfgelm_type_t)0; type < xbt_cfgelm_type_count && strcmp(tok, xbt_cfgelm_type_name[type]); increment(type));
308   xbt_assert(type < xbt_cfgelm_type_count,
309       "Invalid type in config element descriptor: %s; Should be one of 'string', 'int' or 'double'.", entry);
310
311   xbt_cfg_register(cfg, entrycpy, NULL, type, NULL, NULL, NULL, NULL);
312
313   free(entrycpy);               /* strdup'ed by dict mechanism, but cannot be const */
314 }
315
316 /** @brief Displays the declared aliases and their description */
317 void xbt_cfg_aliases(void)
318 {
319   xbt_dict_cursor_t dict_cursor;
320   unsigned int dynar_cursor;
321   xbt_cfgelm_t variable;
322   char *name;
323   xbt_dynar_t names = xbt_dynar_new(sizeof(char *), NULL);
324
325   xbt_dict_foreach((xbt_dict_t )simgrid_config, dict_cursor, name, variable)
326     xbt_dynar_push(names, &name);
327   xbt_dynar_sort_strings(names);
328
329   xbt_dynar_foreach(names, dynar_cursor, name) {
330     variable = (xbt_cfgelm_t) xbt_dict_get((xbt_dict_t )simgrid_config, name);
331
332     if (variable->type == xbt_cfgelm_alias)
333       printf("   %s: %s\n", name, variable->desc.c_str());
334   }
335 }
336
337 /** @brief Displays the declared options and their description */
338 void xbt_cfg_help(void)
339 {
340   xbt_dict_cursor_t dict_cursor;
341   unsigned int dynar_cursor;
342   xbt_cfgelm_t variable;
343   char *name;
344   xbt_dynar_t names = xbt_dynar_new(sizeof(char *), NULL);
345
346   xbt_dict_foreach((xbt_dict_t )simgrid_config, dict_cursor, name, variable)
347     xbt_dynar_push(names, &name);
348   xbt_dynar_sort_strings(names);
349
350   xbt_dynar_foreach(names, dynar_cursor, name) {
351     int size;
352     variable = (xbt_cfgelm_t) xbt_dict_get((xbt_dict_t )simgrid_config, name);
353     if (variable->type == xbt_cfgelm_alias)
354       continue;
355
356     printf("   %s: %s\n", name, variable->desc.c_str());
357     printf("       Type: %s; ", xbt_cfgelm_type_name[variable->type]);
358     size = xbt_dynar_length(variable->content);
359     printf("Current value: ");
360
361     if (size != 1)
362       printf(size == 0 ? "n/a\n" : "{ ");
363     for (int i = 0; i < size; i++) {
364       const char *sep = (size == 1 ? "\n" : (i < size - 1 ? ", " : " }\n"));
365
366       switch (variable->type) {
367       case xbt_cfgelm_int:
368         printf("%d%s", xbt_dynar_get_as(variable->content, i, int), sep);
369         break;
370       case xbt_cfgelm_double:
371         printf("%f%s", xbt_dynar_get_as(variable->content, i, double), sep);
372         break;
373       case xbt_cfgelm_string:
374         printf("'%s'%s", xbt_dynar_get_as(variable->content, i, char *), sep);
375         break;
376       case xbt_cfgelm_boolean: {
377         int b = xbt_dynar_get_as(variable->content, i, int);
378         const char *bs = b ? xbt_cfgelm_boolean_values[0].true_val: xbt_cfgelm_boolean_values[0].false_val;
379         if (b == 0 || b == 1)
380           printf("'%s'%s", bs, sep);
381         else
382           printf("'%s/%d'%s", bs, b, sep);
383         break;
384       }
385       default:
386         printf("Invalid type!!%s", sep);
387         break;
388       }
389     }
390   }
391   xbt_dynar_free(&names);
392 }
393
394 static xbt_cfgelm_t xbt_cfgelm_get(xbt_cfg_t cfg, const char *name, e_xbt_cfgelm_type_t type)
395 {
396   xbt_cfgelm_t res = (xbt_cfgelm_t) xbt_dict_get_or_null((xbt_dict_t) cfg, name);
397
398   // The user used the old name. Switch to the new one after a short warning
399   while (res && res->type == xbt_cfgelm_alias) {
400     const char* newname = (const char *)res->content;
401     XBT_INFO("Option %s has been renamed to %s. Consider switching.", name, newname);
402     res = xbt_cfgelm_get(cfg, newname, type);
403   }
404
405   if (!res) {
406     xbt_cfg_help();
407     fflush(stdout);
408     THROWF(not_found_error, 0, "No registered variable '%s' in this config set.", name);
409   }
410
411   xbt_assert(type == xbt_cfgelm_any || res->type == type,
412               "You tried to access to the config element %s as an %s, but its type is %s.",
413               name, xbt_cfgelm_type_name[type], xbt_cfgelm_type_name[res->type]);
414   return res;
415 }
416
417 /** @brief Get the type of this variable in that configuration set
418  *
419  * @param cfg the config set
420  * @param name the name of the element
421  *
422  * @return the type of the given element
423  */
424 e_xbt_cfgelm_type_t xbt_cfg_get_type(xbt_cfg_t cfg, const char *name)
425 {
426   xbt_cfgelm_t variable = NULL;
427
428   variable = (xbt_cfgelm_t) xbt_dict_get_or_null((xbt_dict_t) cfg, name);
429   if (!variable)
430     THROWF(not_found_error, 0, "Can't get the type of '%s' since this variable does not exist", name);
431
432   XBT_DEBUG("type in variable = %d", (int)variable->type);
433   return variable->type;
434 }
435
436 /*----[ Setting ]---------------------------------------------------------*/
437 /**  @brief va_args version of xbt_cfg_set
438  *
439  * @param cfg config set to fill
440  * @param name  variable name
441  * @param pa  variable value
442  *
443  * Add some values to the config set.
444  */
445 void xbt_cfg_set_vargs(xbt_cfg_t cfg, const char *name, va_list pa)
446 {
447   char *str;
448   int i;
449   double d;
450   e_xbt_cfgelm_type_t type = xbt_cfgelm_type_count; /* Set a dummy value to make gcc happy. It cannot get uninitialized */
451
452   xbt_ex_t e;
453
454   TRY {
455     type = xbt_cfg_get_type(cfg, name);
456   }
457   CATCH(e) {
458     if (e.category == not_found_error) {
459       xbt_ex_free(e);
460       THROWF(not_found_error, 0, "Can't set the property '%s' since it's not registered", name);
461     }
462     RETHROW;
463   }
464
465   switch (type) {
466   case xbt_cfgelm_string:
467     str = va_arg(pa, char *);
468     xbt_cfg_set_string(name, str);
469     break;
470   case xbt_cfgelm_int:
471     i = va_arg(pa, int);
472     xbt_cfg_set_int(name, i);
473     break;
474   case xbt_cfgelm_double:
475     d = va_arg(pa, double);
476     xbt_cfg_set_double(name, d);
477     break;
478   case xbt_cfgelm_boolean:
479     str = va_arg(pa, char *);
480     xbt_cfg_set_boolean(name, str);
481     break;
482   default:
483     xbt_die("Config element variable %s not valid (type=%d)", name, (int)type);
484   }
485 }
486
487 /** @brief Add a NULL-terminated list of pairs {(char*)key, value} to the set
488  *
489  * @param cfg config set to fill
490  * @param name variable name
491  * @param ... variable value
492  */
493 void xbt_cfg_set(xbt_cfg_t cfg, const char *name, ...)
494 {
495   va_list pa;
496
497   va_start(pa, name);
498   xbt_cfg_set_vargs(cfg, name, pa);
499   va_end(pa);
500 }
501
502 /** @brief Add values parsed from a string into a config set
503  *
504  * @param options a string containing the content to add to the config set. This is a '\\t',' ' or '\\n' or ','
505  * separated list of variables. Each individual variable is like "[name]:[value]" where [name] is the name of an
506  * already registered variable, and [value] conforms to the data type under which this variable was registered.
507  *
508  * @todo This is a crude manual parser, it should be a proper lexer.
509  */
510 void xbt_cfg_set_parse(const char *options)
511 {
512   if (!options || !strlen(options)) {   /* nothing to do */
513     return;
514   }
515   char *optionlist_cpy = xbt_strdup(options);
516
517   XBT_DEBUG("List to parse and set:'%s'", options);
518   char *option = optionlist_cpy;
519   while (1) {                   /* breaks in the code */
520     if (!option)
521       break;
522     char *name = option;
523     int len = strlen(name);
524     XBT_DEBUG("Still to parse and set: '%s'. len=%d; option-name=%ld", name, len, (long) (option - name));
525
526     /* Pass the value */
527     while (option - name <= (len - 1) && *option != ' ' && *option != '\n' && *option != '\t' && *option != ',') {
528       XBT_DEBUG("Take %c.", *option);
529       option++;
530     }
531     if (option - name == len) {
532       XBT_DEBUG("Boundary=EOL");
533       option = NULL;            /* don't do next iteration */
534     } else {
535       XBT_DEBUG("Boundary on '%c'. len=%d;option-name=%ld", *option, len, (long) (option - name));
536       /* Pass the following blank chars */
537       *(option++) = '\0';
538       while (option - name < (len - 1) && (*option == ' ' || *option == '\n' || *option == '\t')) {
539         /*      fprintf(stderr,"Ignore a blank char.\n"); */
540         option++;
541       }
542       if (option - name == len - 1)
543         option = NULL;          /* don't do next iteration */
544     }
545     XBT_DEBUG("parse now:'%s'; parse later:'%s'", name, option);
546
547     if (name[0] == ' ' || name[0] == '\n' || name[0] == '\t')
548       continue;
549     if (!strlen(name))
550       break;
551
552     char *val = strchr(name, ':');
553     xbt_assert(val, "Option '%s' badly formatted. Should be of the form 'name:value'", name);
554     /* don't free(optionlist_cpy) if the assert fails, 'name' points inside it */
555     *(val++) = '\0';
556
557     if (strncmp(name, "contexts/", strlen("contexts/")) && strncmp(name, "path", strlen("path")))
558       XBT_INFO("Configuration change: Set '%s' to '%s'", name, val);
559
560     TRY {
561       xbt_cfg_set_as_string(name,val);
562     } CATCH_ANONYMOUS {
563       free(optionlist_cpy);
564       RETHROW;
565     }
566   }
567   free(optionlist_cpy);
568 }
569
570 /** @brief Set the value of a variable, using the string representation of that value
571  *
572  * @param key name of the variable to modify
573  * @param value string representation of the value to set
574  *
575  * @return the first char after the parsed value in val
576  */
577
578 void *xbt_cfg_set_as_string(const char *key, const char *value) {
579   xbt_ex_t e;
580
581   char *ret;
582   volatile xbt_cfgelm_t variable = NULL;
583   int i;
584   double d;
585
586   TRY {
587     while (variable == NULL) {
588       variable = (xbt_cfgelm_t) xbt_dict_get((xbt_dict_t) simgrid_config, key);
589       if (variable->type == xbt_cfgelm_alias) {
590         const char *newname = (const char*)variable->content;
591         XBT_INFO("Note: configuration '%s' is deprecated. Please use '%s' instead.", key, newname);
592         key = newname;
593         variable = NULL;
594       }
595     }
596   } CATCH(e) {
597     if (e.category == not_found_error) {
598       xbt_ex_free(e);
599       THROWF(not_found_error, 0, "No registered variable corresponding to '%s'.", key);
600     }
601     RETHROW;
602   }
603
604   switch (variable->type) {
605   case xbt_cfgelm_string:
606     xbt_cfg_set_string(key, value);     /* throws */
607     break;
608   case xbt_cfgelm_int:
609     i = strtol(value, &ret, 0);
610     if (ret == value) {
611       xbt_die("Value of option %s not valid. Should be an integer", key);
612     }
613     xbt_cfg_set_int(key, i);  /* throws */
614     break;
615   case xbt_cfgelm_double:
616     d = strtod(value, &ret);
617     if (ret == value) {
618       xbt_die("Value of option %s not valid. Should be a double", key);
619     }
620     xbt_cfg_set_double(key, d);       /* throws */
621     break;
622   case xbt_cfgelm_boolean:
623     xbt_cfg_set_boolean(key, value);  /* throws */
624     ret = (char *)value + strlen(value);
625     break;
626   default:
627     THROWF(unknown_error, 0, "Type of config element %s is not valid.", key);
628     break;
629   }
630   return ret;
631 }
632
633 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
634  *
635  * This is useful to change the default value of a variable while allowing
636  * users to override it with command line arguments
637  */
638 void xbt_cfg_setdefault_int(const char *name, int val)
639 {
640   xbt_cfgelm_t variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_int);
641
642   if (variable->isdefault){
643     xbt_cfg_set_int(name, val);
644     variable->isdefault = true;
645   } else
646     XBT_DEBUG("Do not override configuration variable '%s' with value '%d' because it was already set.", name, val);
647 }
648
649 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
650  *
651  * This is useful to change the default value of a variable while allowing
652  * users to override it with command line arguments
653  */
654 void xbt_cfg_setdefault_double(const char *name, double val)
655 {
656   xbt_cfgelm_t variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_double);
657
658   if (variable->isdefault) {
659     xbt_cfg_set_double(name, val);
660     variable->isdefault = true;
661   } else
662     XBT_DEBUG("Do not override configuration variable '%s' with value '%f' because it was already set.", name, val);
663 }
664
665 /** @brief Set a string value to \a name within \a cfg if it wasn't changed yet
666  *
667  * This is useful to change the default value of a variable while allowing
668  * users to override it with command line arguments
669  */
670 void xbt_cfg_setdefault_string(const char *name, const char *val)
671 {
672   xbt_cfgelm_t variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_string);
673
674   if (variable->isdefault){
675     xbt_cfg_set_string(name, val);
676     variable->isdefault = true;
677   } else
678     XBT_DEBUG("Do not override configuration variable '%s' with value '%s' because it was already set.", name, val);
679 }
680
681 /** @brief Set an boolean value to \a name within \a cfg if it wasn't changed yet
682  *
683  * This is useful to change the default value of a variable while allowing
684  * users to override it with command line arguments
685  */
686 void xbt_cfg_setdefault_boolean(const char *name, const char *val)
687 {
688   xbt_cfgelm_t variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_boolean);
689
690   if (variable->isdefault){
691     xbt_cfg_set_boolean(name, val);
692     variable->isdefault = true;
693   }
694    else
695     XBT_DEBUG("Do not override configuration variable '%s' with value '%s' because it was already set.", name, val);
696 }
697
698 /** @brief Set an integer value to \a name within \a cfg
699  *
700  * @param name the name of the variable
701  * @param val the value of the variable
702  */
703 void xbt_cfg_set_int(const char *name, int val)
704 {
705   xbt_cfgelm_t variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_int);
706
707   xbt_dynar_set(variable->content, 0, &val);
708
709   if (variable->cb_set)
710     variable->cb_set(name);
711   if (variable->cb_set_ext)
712     variable->cb_set_ext(name, variable->cb_set_data);
713   variable->isdefault = false;
714 }
715
716 /** @brief Set or add a double value to \a name within \a cfg
717  *
718  * @param name the name of the variable
719  * @param val the double to set
720  */
721 void xbt_cfg_set_double(const char *name, double val)
722 {
723   xbt_cfgelm_t variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_double);
724
725   xbt_dynar_set(variable->content, 0, &val);
726
727   if (variable->cb_set)
728     variable->cb_set(name);
729   if (variable->cb_set_ext)
730     variable->cb_set_ext(name, variable->cb_set_data);
731   variable->isdefault = false;
732 }
733
734 /** @brief Set or add a string value to \a name within \a cfg
735  *
736  * @param cfg the config set
737  * @param name the name of the variable
738  * @param val the value to be added
739  *
740  */
741 void xbt_cfg_set_string(const char *name, const char *val)
742 {
743   char *newval = xbt_strdup(val);
744   xbt_cfgelm_t variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_string);
745
746   if (!xbt_dynar_is_empty(variable->content)) {
747     char *sval = xbt_dynar_get_as(variable->content, 0, char *);
748     free(sval);
749   }
750
751   xbt_dynar_set(variable->content, 0, &newval);
752
753   if (variable->cb_set)
754     variable->cb_set(name);
755   if (variable->cb_set_ext)
756     variable->cb_set_ext(name, variable->cb_set_data);
757   variable->isdefault = false;
758 }
759
760 /** @brief Set or add a boolean value to \a name within \a cfg
761  *
762  * @param name the name of the variable
763  * @param val the value of the variable
764  */
765 void xbt_cfg_set_boolean(const char *name, const char *val)
766 {
767   int bval=-1;
768   xbt_cfgelm_t variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_boolean);
769
770   for (int i = 0; xbt_cfgelm_boolean_values[i].true_val != NULL; i++) {
771     if (strcmp(val, xbt_cfgelm_boolean_values[i].true_val) == 0){
772       bval = 1;
773       break;
774     }
775     if (strcmp(val, xbt_cfgelm_boolean_values[i].false_val) == 0){
776       bval = 0;
777       break;
778     }
779   }
780   xbt_assert(bval != -1, "Value of option '%s' not valid. Should be a boolean (yes,no,on,off,true,false,0,1)", val);
781   xbt_dynar_set(variable->content, 0, &bval);
782
783   if (variable->cb_set)
784     variable->cb_set(name);
785   if (variable->cb_set_ext)
786     variable->cb_set_ext(name, variable->cb_set_data);
787   variable->isdefault = false;
788 }
789
790
791 /* Say if the value is the default value */
792 int xbt_cfg_is_default_value(const char *name)
793 {
794   xbt_cfgelm_t variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_any);
795   return variable->isdefault;
796 }
797
798 /*----[ Getting ]---------------------------------------------------------*/
799 /** @brief Retrieve an integer value of a variable (get a warning if not uniq)
800  *
801  * @param name the name of the variable
802  *
803  * Returns the first value from the config set under the given name.
804  * If there is more than one value, it will issue a warning. Consider using xbt_cfg_get_dynar() instead.
805  */
806 int xbt_cfg_get_int(const char *name)
807 {
808   xbt_cfgelm_t variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_int);
809
810   if (xbt_dynar_length(variable->content) > 1) {
811     XBT_WARN("You asked for the first value of the config element '%s', but there is %lu values",
812          name, xbt_dynar_length(variable->content));
813   }
814
815   return xbt_dynar_get_as(variable->content, 0, int);
816 }
817
818 /** @brief Retrieve a double value of a variable (get a warning if not uniq)
819  *
820  * @param cfg the config set
821  * @param name the name of the variable
822  *
823  * Returns the first value from the config set under the given name.
824  * If there is more than one value, it will issue a warning. Consider using xbt_cfg_get_dynar() instead.
825  */
826 double xbt_cfg_get_double(const char *name)
827 {
828   xbt_cfgelm_t variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_double);
829
830   if (xbt_dynar_length(variable->content) > 1) {
831     XBT_WARN ("You asked for the first value of the config element '%s', but there is %lu values\n",
832          name, xbt_dynar_length(variable->content));
833   }
834
835   return xbt_dynar_get_as(variable->content, 0, double);
836 }
837
838 /** @brief Retrieve a string value of a variable (get a warning if not uniq)
839  *
840  * @param cfg the config set
841  * @param name the name of the variable
842  *
843  * Returns the first value from the config set under the given name.
844  * If there is more than one value, it will issue a warning. Consider using
845  * xbt_cfg_get_dynar() instead. Returns NULL if there is no value.
846  *
847  * \warning the returned value is the actual content of the config set
848  */
849 char *xbt_cfg_get_string(const char *name)
850 {
851   xbt_cfgelm_t variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_string);
852
853   if (xbt_dynar_length(variable->content) > 1) {
854     XBT_WARN("You asked for the first value of the config element '%s', but there is %lu values\n",
855          name, xbt_dynar_length(variable->content));
856   } else if (xbt_dynar_is_empty(variable->content)) {
857     return NULL;
858   }
859
860   return xbt_dynar_get_as(variable->content, 0, char *);
861 }
862
863 /** @brief Retrieve a boolean value of a variable (get a warning if not uniq)
864  *
865  * @param cfg the config set
866  * @param name the name of the variable
867  *
868  * Returns the first value from the config set under the given name.
869  * If there is more than one value, it will issue a warning. Consider using xbt_cfg_get_dynar() instead.
870  */
871 int xbt_cfg_get_boolean(const char *name)
872 {
873   xbt_cfgelm_t variable = xbt_cfgelm_get(simgrid_config, name, xbt_cfgelm_boolean);
874
875   if (xbt_dynar_length(variable->content) > 1) {
876     XBT_WARN("You asked for the first value of the config element '%s', but there is %lu values",
877          name, xbt_dynar_length(variable->content));
878   }
879
880   return xbt_dynar_get_as(variable->content, 0, int);
881 }
882
883 namespace simgrid {
884 namespace config {
885
886 static void callCallback(const char* name, void* data)
887 {
888   (*(std::function<void(const char*)>*) data)(name);
889 }
890
891 static void freeCallback(void* data)
892 {
893   delete (std::function<void(const char*)>*) data;
894 }
895
896 void registerConfig(const char* name, const char* description,
897   e_xbt_cfgelm_type_t type,
898   std::function<void(const char*)> callback)
899 {
900   std::function<void(const char*)>* code
901     = new std::function<void(const char*)>(std::move(callback));
902   xbt_cfg_register_ext(name, description, type,
903     callCallback, code, freeCallback);
904 }
905
906 }
907 }
908
909 #ifdef SIMGRID_TEST
910 #include "xbt.h"
911 #include "xbt/ex.h"
912
913 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(xbt_cfg);
914
915 XBT_TEST_SUITE("config", "Configuration support");
916
917 static xbt_cfg_t make_set()
918 {
919   xbt_cfg_t set = NULL;
920
921   xbt_log_threshold_set(&_XBT_LOGV(xbt_cfg), xbt_log_priority_critical);
922   xbt_cfg_register_str(&set, "speed:int");
923   xbt_cfg_register_str(&set, "peername:string");
924   xbt_cfg_register_str(&set, "user:string");
925
926   return set;
927 }                               /* end_of_make_set */
928
929 XBT_PUBLIC_DATA(xbt_cfg_t) simgrid_config;
930
931 XBT_TEST_UNIT("memuse", test_config_memuse, "Alloc and free a config set")
932 {
933   simgrid_config = make_set();
934   xbt_test_add("Alloc and free a config set");
935   xbt_cfg_set_parse("peername:veloce user:bidule");
936   xbt_cfg_free(&simgrid_config);
937 }
938
939 XBT_TEST_UNIT("use", test_config_use, "Data retrieving tests")
940 {
941   simgrid_config = make_set();
942   xbt_test_add("Get a single value");
943   {
944     /* get_single_value */
945     int ival;
946
947     xbt_cfg_set_parse("peername:toto:42 speed:42");
948     ival = xbt_cfg_get_int("speed");
949     if (ival != 42)
950       xbt_test_fail("Speed value = %d, I expected 42", ival);
951   }
952
953   xbt_test_add("Access to a non-existant entry");
954   {
955     xbt_ex_t e;
956
957     TRY {
958       xbt_cfg_set_parse("color:blue");
959     } CATCH(e) {
960       if (e.category != not_found_error)
961         xbt_test_exception(e);
962       xbt_ex_free(e);
963     }
964   }
965   xbt_cfg_free(&simgrid_config);
966 }
967 #endif                          /* SIMGRID_TEST */