Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Sanitize the way surf options are declared: in surf_config not dupplicated in simix...
[simgrid.git] / src / xbt / config.c
1 /* $Id$ */
2
3 /* config - Dictionnary where the type of each variable is provided.            */
4
5 /* This is useful to build named structs, like option or property sets.     */
6
7 /* Copyright (c) 2001,2002,2003,2004 Martin Quinson. All rights reserved.   */
8
9 /* This program is free software; you can redistribute it and/or modify it
10  * under the terms of the license (GNU LGPL) which comes with this package. */
11
12 #include <stdio.h>
13 #include "xbt/misc.h"
14 #include "xbt/sysdep.h"
15 #include "xbt/log.h"
16 #include "xbt/ex.h"
17 #include "xbt/dynar.h"
18 #include "xbt/dict.h"
19 #include "xbt/peer.h"
20
21 #include "xbt/config.h"         /* prototypes of this module */
22
23 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_cfg, xbt, "configuration support");
24
25 /* xbt_cfgelm_t: the typedef corresponding to a config variable.
26
27    Both data and DTD are mixed, but fixing it now would prevent me to ever
28    defend my thesis. */
29
30 typedef struct {
31   /* Description */
32   const char *desc;
33
34   /* Allowed type of the variable */
35   e_xbt_cfgelm_type_t type;
36   int min, max;
37
38   /* Callbacks */
39   xbt_cfg_cb_t cb_set;
40   xbt_cfg_cb_t cb_rm;
41
42   /* actual content
43      (cannot be an union because type peer uses both str and i) */
44   xbt_dynar_t content;
45 } s_xbt_cfgelm_t, *xbt_cfgelm_t;
46
47 static const char *xbt_cfgelm_type_name[xbt_cfgelm_type_count] =
48   { "int", "double", "string", "peer", "any" };
49
50 /* Internal stuff used in cache to free a variable */
51 static void xbt_cfgelm_free(void *data);
52
53 /* Retrieve the variable we'll modify */
54 static xbt_cfgelm_t xbt_cfgelm_get(xbt_cfg_t cfg, const char *name,
55                                    e_xbt_cfgelm_type_t type);
56
57 /*----[ Memory management ]-----------------------------------------------*/
58
59 /** @brief Constructor
60  *
61  * Initialise an config set
62  */
63
64
65 xbt_cfg_t xbt_cfg_new(void)
66 {
67   return (xbt_cfg_t) xbt_dict_new();
68 }
69
70 /** \brief Copy an existing configuration set
71  *
72  * \arg whereto the config set to be created
73  * \arg tocopy the source data
74  *
75  * This only copy the registrations, not the actual content
76  */
77
78 void xbt_cfg_cpy(xbt_cfg_t tocopy, xbt_cfg_t * whereto)
79 {
80   xbt_dict_cursor_t cursor = NULL;
81   xbt_cfgelm_t variable = NULL;
82   char *name = NULL;
83
84   DEBUG1("Copy cfg set %p", tocopy);
85   *whereto = NULL;
86   xbt_assert0(tocopy, "cannot copy NULL config");
87
88   xbt_dict_foreach((xbt_dict_t) tocopy, cursor, name, variable) {
89     xbt_cfg_register(*whereto, name, variable->desc, variable->type, variable->min,
90                      variable->max, variable->cb_set, variable->cb_rm);
91   }
92 }
93
94 /** @brief Destructor */
95 void xbt_cfg_free(xbt_cfg_t * cfg)
96 {
97   DEBUG1("Frees cfg set %p", cfg);
98   xbt_dict_free((xbt_dict_t *) cfg);
99 }
100
101 /** @brief Dump a config set for debuging purpose
102  *
103  * \arg name The name to give to this config set
104  * \arg indent what to write at the begining of each line (right number of spaces)
105  * \arg cfg the config set
106  */
107 void xbt_cfg_dump(const char *name, const char *indent, xbt_cfg_t cfg)
108 {
109   xbt_dict_t dict = (xbt_dict_t) cfg;
110   xbt_dict_cursor_t cursor = NULL;
111   xbt_cfgelm_t variable = NULL;
112   char *key = NULL;
113   int i;
114   int size;
115   int ival;
116   char *sval;
117   double dval;
118   xbt_peer_t hval;
119
120   if (name)
121     printf("%s>> Dumping of the config set '%s':\n", indent, name);
122   xbt_dict_foreach(dict, cursor, key, variable) {
123
124     printf("%s  %s:", indent, key);
125
126     size = xbt_dynar_length(variable->content);
127     printf
128       ("%d_to_%d_%s. Actual size=%d. prerm=%p,postset=%p, List of values:\n",
129        variable->min, variable->max, xbt_cfgelm_type_name[variable->type],
130        size, variable->cb_rm, variable->cb_set);
131
132     switch (variable->type) {
133
134     case xbt_cfgelm_int:
135       for (i = 0; i < size; i++) {
136         ival = xbt_dynar_get_as(variable->content, i, int);
137         printf("%s    %d\n", indent, ival);
138       }
139       break;
140
141     case xbt_cfgelm_double:
142       for (i = 0; i < size; i++) {
143         dval = xbt_dynar_get_as(variable->content, i, double);
144         printf("%s    %f\n", indent, dval);
145       }
146       break;
147
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
155     case xbt_cfgelm_peer:
156       for (i = 0; i < size; i++) {
157         hval = xbt_dynar_get_as(variable->content, i, xbt_peer_t);
158         printf("%s    %s:%d\n", indent, hval->name, hval->port);
159       }
160       break;
161
162     default:
163       printf("%s    Invalid type!!\n", indent);
164     }
165
166   }
167
168   if (name)
169     printf("%s<< End of the config set '%s'\n", indent, name);
170   fflush(stdout);
171
172   xbt_dict_cursor_free(&cursor);
173   return;
174 }
175
176 /*
177  * free an config element
178  */
179
180 void xbt_cfgelm_free(void *data)
181 {
182   xbt_cfgelm_t c = (xbt_cfgelm_t) data;
183
184   DEBUG1("Frees cfgelm %p", c);
185   if (!c)
186     return;
187   xbt_dynar_free(&(c->content));
188   free(c);
189 }
190
191 /*----[ Registering stuff ]-----------------------------------------------*/
192
193 /** @brief Register an element within a config set
194  *
195  *  @arg cfg the config set
196  *  @arg type the type of the config element
197  *  @arg min the minimum
198  *  @arg max the maximum
199  */
200
201 void
202 xbt_cfg_register(xbt_cfg_t cfg,
203                  const char *name, const char *desc, e_xbt_cfgelm_type_t type,
204                  int min, int max, xbt_cfg_cb_t cb_set, xbt_cfg_cb_t cb_rm)
205 {
206   xbt_cfgelm_t res;
207
208   xbt_assert(cfg);
209   xbt_assert4(type >= xbt_cfgelm_int && type <= xbt_cfgelm_peer,
210               "type of %s not valid (%d should be between %d and %d)",
211               name, type, xbt_cfgelm_int, xbt_cfgelm_peer);
212   res = xbt_dict_get_or_null((xbt_dict_t) cfg, name);
213
214   if (res) {
215     WARN1("Config elem %s registered twice.", name);
216     /* Will be removed by the insertion of the new one */
217   }
218
219   res = xbt_new(s_xbt_cfgelm_t, 1);
220   DEBUG8("Register cfg elm %s (%s) (%d to %d %s (=%d) @%p in set %p)",
221          name, desc, min, max, xbt_cfgelm_type_name[type], type, res, cfg);
222
223   res->desc = desc;
224   res->type = type;
225   res->min = min;
226   res->max = max;
227   res->cb_set = cb_set;
228   res->cb_rm = cb_rm;
229
230   switch (type) {
231   case xbt_cfgelm_int:
232     res->content = xbt_dynar_new(sizeof(int), NULL);
233     break;
234
235   case xbt_cfgelm_double:
236     res->content = xbt_dynar_new(sizeof(double), NULL);
237     break;
238
239   case xbt_cfgelm_string:
240     res->content = xbt_dynar_new(sizeof(char *), xbt_free_ref);
241     break;
242
243   case xbt_cfgelm_peer:
244     res->content = xbt_dynar_new(sizeof(xbt_peer_t), xbt_peer_free_voidp);
245     break;
246
247   default:
248     ERROR1("%d is an invalide type code", type);
249   }
250
251   xbt_dict_set((xbt_dict_t) cfg, name, res, &xbt_cfgelm_free);
252 }
253
254 /** @brief Unregister an element from a config set.
255  *
256  *  @arg cfg the config set
257  *  @arg name the name of the elem to be freed
258  *
259  *  Note that it removes both the description and the actual content.
260  *  Throws not_found when no such element exists.
261  */
262
263 void xbt_cfg_unregister(xbt_cfg_t cfg, const char *name)
264 {
265   DEBUG2("Unregister elm '%s' from set %p", name, cfg);
266   xbt_dict_remove((xbt_dict_t) cfg, name);
267 }
268
269 /**
270  * @brief Parse a string and register the stuff described.
271  *
272  * @arg cfg the config set
273  * @arg entry a string describing the element to register
274  *
275  * The string may consist in several variable descriptions separated by a space.
276  * Each of them must use the following syntax: \<name\>:\<min nb\>_to_\<max nb\>_\<type\>
277  * with type being one of  'string','int', 'peer' or 'double'.
278  *
279  * @fixme: this does not allow to set the description
280  */
281
282 void xbt_cfg_register_str(xbt_cfg_t cfg, const char *entry)
283 {
284   char *entrycpy = xbt_strdup(entry);
285   char *tok;
286
287   int min, max;
288   e_xbt_cfgelm_type_t type;
289   DEBUG1("Register string '%s'", entry);
290
291   tok = strchr(entrycpy, ':');
292   xbt_assert2(tok, "Invalid config element descriptor: %s%s",
293               entry, "; Should be <name>:<min nb>_to_<max nb>_<type>");
294   *(tok++) = '\0';
295
296   min = strtol(tok, &tok, 10);
297   xbt_assert1(tok, "Invalid minimum in config element descriptor %s", entry);
298
299   xbt_assert2(strcmp(tok, "_to_"),
300               "Invalid config element descriptor : %s%s",
301               entry, "; Should be <name>:<min nb>_to_<max nb>_<type>");
302   tok += strlen("_to_");
303
304   max = strtol(tok, &tok, 10);
305   xbt_assert1(tok, "Invalid maximum in config element descriptor %s", entry);
306
307   xbt_assert2(*(tok++) == '_',
308               "Invalid config element descriptor: %s%s", entry,
309               "; Should be <name>:<min nb>_to_<max nb>_<type>");
310
311   for (type = 0;
312        type < xbt_cfgelm_type_count
313        && strcmp(tok, xbt_cfgelm_type_name[type]); type++);
314   xbt_assert2(type < xbt_cfgelm_type_count,
315               "Invalid type in config element descriptor: %s%s", entry,
316               "; Should be one of 'string', 'int', 'peer' or 'double'.");
317
318   xbt_cfg_register(cfg, entrycpy, NULL, type, min, max, NULL, NULL);
319
320   free(entrycpy);               /* strdup'ed by dict mechanism, but cannot be const */
321 }
322
323 /** @brief Check that each variable have the right amount of values */
324
325 void xbt_cfg_check(xbt_cfg_t cfg)
326 {
327   xbt_dict_cursor_t cursor;
328   xbt_cfgelm_t variable;
329   char *name;
330   int size;
331
332   xbt_assert0(cfg, "NULL config set.");
333   DEBUG1("Check cfg set %p", cfg);
334
335   xbt_dict_foreach((xbt_dict_t) cfg, cursor, name, variable) {
336     size = xbt_dynar_length(variable->content);
337     if (variable->min > size) {
338       xbt_dict_cursor_free(&cursor);
339       THROW4(mismatch_error, 0,
340              "Config elem %s needs at least %d %s, but there is only %d values.",
341              name, variable->min, xbt_cfgelm_type_name[variable->type], size);
342     }
343
344     if (variable->max > 0 && variable->max < size) {
345       xbt_dict_cursor_free(&cursor);
346       THROW4(mismatch_error, 0,
347              "Config elem %s accepts at most %d %s, but there is %d values.",
348              name, variable->max, xbt_cfgelm_type_name[variable->type], size);
349     }
350   }
351
352   xbt_dict_cursor_free(&cursor);
353 }
354
355 static xbt_cfgelm_t xbt_cfgelm_get(xbt_cfg_t cfg,
356                                    const char *name, e_xbt_cfgelm_type_t type)
357 {
358   xbt_cfgelm_t res = NULL;
359
360   res = xbt_dict_get_or_null((xbt_dict_t) cfg, name);
361   if (!res)
362     THROW1(not_found_error, 0,
363            "No registered variable '%s' in this config set", name);
364
365   xbt_assert3(type == xbt_cfgelm_any || res->type == type,
366               "You tried to access to the config element %s as an %s, but its type is %s.",
367               name,
368               xbt_cfgelm_type_name[type], xbt_cfgelm_type_name[res->type]);
369
370   return res;
371 }
372
373 /** @brief Get the type of this variable in that configuration set
374  *
375  * \arg cfg the config set
376  * \arg name the name of the element
377  * \arg type the result
378  *
379  */
380
381 e_xbt_cfgelm_type_t xbt_cfg_get_type(xbt_cfg_t cfg, const char *name)
382 {
383
384   xbt_cfgelm_t variable = NULL;
385
386   variable = xbt_dict_get_or_null((xbt_dict_t) cfg, name);
387   if (!variable)
388     THROW1(not_found_error, 0,
389            "Can't get the type of '%s' since this variable does not exist",
390            name);
391
392   INFO1("type in variable = %d", variable->type);
393
394   return variable->type;
395 }
396
397 /*----[ Setting ]---------------------------------------------------------*/
398 /**  @brief va_args version of xbt_cfg_set
399  *
400  * \arg cfg config set to fill
401  * \arg n   variable name
402  * \arg pa  variable value
403  *
404  * Add some values to the config set.
405  */
406 void xbt_cfg_set_vargs(xbt_cfg_t cfg, const char *name, va_list pa)
407 {
408   char *str;
409   int i;
410   double d;
411   e_xbt_cfgelm_type_t type = 0; /* Set a dummy value to make gcc happy. It cannot get uninitialized */
412
413   xbt_ex_t e;
414
415   TRY {
416     type = xbt_cfg_get_type(cfg, name);
417   } CATCH(e) {
418     if (e.category == not_found_error) {
419       xbt_ex_free(e);
420       THROW1(not_found_error, 0,
421              "Can't set the property '%s' since it's not registered", name);
422     }
423     RETHROW;
424   }
425
426   switch (type) {
427   case xbt_cfgelm_peer:
428     str = va_arg(pa, char *);
429     i = va_arg(pa, int);
430     xbt_cfg_set_peer(cfg, name, str, i);
431     break;
432
433   case xbt_cfgelm_string:
434     str = va_arg(pa, char *);
435     xbt_cfg_set_string(cfg, name, str);
436     break;
437
438   case xbt_cfgelm_int:
439     i = va_arg(pa, int);
440     xbt_cfg_set_int(cfg, name, i);
441     break;
442
443   case xbt_cfgelm_double:
444     d = va_arg(pa, double);
445     xbt_cfg_set_double(cfg, name, d);
446     break;
447
448   default:
449     xbt_assert2(0, "Config element variable %s not valid (type=%d)", name,
450                 type);
451   }
452 }
453
454 /** @brief Add a NULL-terminated list of pairs {(char*)key, value} to the set
455  *
456  * \arg cfg config set to fill
457  * \arg name variable name
458  * \arg varargs variable value
459  *
460  */
461 void xbt_cfg_set(xbt_cfg_t cfg, const char *name, ...)
462 {
463   va_list pa;
464
465   va_start(pa, name);
466   xbt_cfg_set_vargs(cfg, name, pa);
467   va_end(pa);
468 }
469
470 /** @brief Add values parsed from a string into a config set
471  *
472  * \arg cfg config set to fill
473  * \arg options a string containing the content to add to the config set. This
474  * is a '\\t',' ' or '\\n' or ',' separated list of variables. Each individual variable is
475  * like "[name]:[value]" where [name] is the name of an already registred
476  * variable, and [value] conforms to the data type under which this variable was
477  * registred.
478  *
479  * @todo This is a crude manual parser, it should be a proper lexer.
480  */
481
482 void xbt_cfg_set_parse(xbt_cfg_t cfg, const char *options)
483 {
484   xbt_ex_t e;
485
486   int i;
487   double d;
488   char *str;
489
490   xbt_cfgelm_t variable = NULL;
491   char *optionlist_cpy;
492   char *option, *name, *val;
493
494   int len;
495
496   XBT_IN;
497   if (!options || !strlen(options)) {   /* nothing to do */
498     return;
499   }
500   optionlist_cpy = xbt_strdup(options);
501
502   DEBUG1("List to parse and set:'%s'", options);
503   option = optionlist_cpy;
504   while (1) {                   /* breaks in the code */
505
506     if (!option)
507       break;
508     name = option;
509     len = strlen(name);
510     DEBUG3("Still to parse and set: '%s'. len=%d; option-name=%ld",
511            name, len, (long) (option - name));
512
513     /* Pass the value */
514     while (option - name <= (len - 1) && *option != ' ' && *option != '\n'
515            && *option != '\t' && *option != ',') {
516       DEBUG1("Take %c.", *option);
517       option++;
518     }
519     if (option - name == len) {
520       DEBUG0("Boundary=EOL");
521       option = NULL;            /* don't do next iteration */
522
523     } else {
524       DEBUG3("Boundary on '%c'. len=%d;option-name=%ld",
525              *option, len, (long) (option - name));
526
527       /* Pass the following blank chars */
528       *(option++) = '\0';
529       while (option - name < (len - 1) &&
530              (*option == ' ' || *option == '\n' || *option == '\t')) {
531         /*      fprintf(stderr,"Ignore a blank char.\n"); */
532         option++;
533       }
534       if (option - name == len - 1)
535         option = NULL;          /* don't do next iteration */
536     }
537     DEBUG2("parse now:'%s'; parse later:'%s'", name, option);
538
539     if (name[0] == ' ' || name[0] == '\n' || name[0] == '\t')
540       continue;
541     if (!strlen(name))
542       break;
543
544     val = strchr(name, ':');
545     if (!val) {
546       free(optionlist_cpy);
547       xbt_assert1(FALSE,
548                   "Option '%s' badly formated. Should be of the form 'name:value'",
549                   name);
550     }
551     *(val++) = '\0';
552
553     INFO2("Configuration change: Set '%s' to '%s'", name, val);
554
555     TRY {
556       variable = xbt_dict_get((xbt_dict_t) cfg, name);
557     }
558     CATCH(e) {
559       /* put it back on what won't get freed, ie within "options" and out of "optionlist_cpy" */
560       name = (char *) (optionlist_cpy - name + options);
561       free(optionlist_cpy);
562       if (e.category == not_found_error) {
563         xbt_ex_free(e);
564         THROW1(not_found_error, 0,
565                "No registrated variable corresponding to '%s'.", name);
566       }
567       RETHROW;
568     }
569
570     TRY {
571       switch (variable->type) {
572       case xbt_cfgelm_string:
573         xbt_cfg_set_string(cfg, name, val);     /* throws */
574         break;
575
576       case xbt_cfgelm_int:
577         i = strtol(val, &val, 0);
578         if (val == NULL) {
579           free(optionlist_cpy);
580           xbt_assert1(FALSE,
581                       "Value of option %s not valid. Should be an integer",
582                       name);
583         }
584
585         xbt_cfg_set_int(cfg, name, i);  /* throws */
586         break;
587
588       case xbt_cfgelm_double:
589         d = strtod(val, &val);
590         if (val == NULL) {
591           free(optionlist_cpy);
592           xbt_assert1(FALSE,
593                       "Value of option %s not valid. Should be a double",
594                       name);
595         }
596
597         xbt_cfg_set_double(cfg, name, d);       /* throws */
598         break;
599
600       case xbt_cfgelm_peer:
601         str = val;
602         val = strchr(val, ':');
603         if (!val) {
604           free(optionlist_cpy);
605           xbt_assert1(FALSE,
606                       "Value of option %s not valid. Should be an peer (machine:port)",
607                       name);
608         }
609
610         *(val++) = '\0';
611         i = strtol(val, &val, 0);
612         if (val == NULL) {
613           free(optionlist_cpy);
614           xbt_assert1(FALSE,
615                       "Value of option %s not valid. Should be an peer (machine:port)",
616                       name);
617         }
618
619         xbt_cfg_set_peer(cfg, name, str, i);    /* throws */
620         break;
621
622       default:
623         THROW1(unknown_error, 0, "Type of config element %s is not valid.",
624                name);
625       }
626     }
627     CATCH(e) {
628       free(optionlist_cpy);
629       RETHROW;
630     }
631   }
632   free(optionlist_cpy);
633
634 }
635
636 /** @brief Set or add an integer value to \a name within \a cfg
637  *
638  * \arg cfg the config set
639  * \arg name the name of the variable
640  * \arg val the value of the variable
641  */
642 void xbt_cfg_set_int(xbt_cfg_t cfg, const char *name, int val)
643 {
644   xbt_cfgelm_t variable;
645
646   VERB2("Configuration setting: %s=%d", name, val);
647   variable = xbt_cfgelm_get(cfg, name, xbt_cfgelm_int);
648
649   if (variable->max == 1) {
650     if (variable->cb_rm && xbt_dynar_length(variable->content))
651       (*variable->cb_rm) (name, 0);
652
653     xbt_dynar_set(variable->content, 0, &val);
654   } else {
655     if (variable->max
656         && xbt_dynar_length(variable->content) ==
657         (unsigned long) variable->max)
658       THROW3(mismatch_error, 0,
659              "Cannot add value %d to the config element %s since it's already full (size=%d)",
660              val, name, variable->max);
661
662     xbt_dynar_push(variable->content, &val);
663   }
664
665   if (variable->cb_set)
666     (*variable->cb_set) (name, xbt_dynar_length(variable->content) - 1);
667 }
668
669 /** @brief Set or add a double value to \a name within \a cfg
670  *
671  * \arg cfg the config set
672  * \arg name the name of the variable
673  * \arg val the doule to set
674  */
675
676 void xbt_cfg_set_double(xbt_cfg_t cfg, const char *name, double val)
677 {
678   xbt_cfgelm_t variable;
679
680   VERB2("Configuration setting: %s=%f", name, val);
681   variable = xbt_cfgelm_get(cfg, name, xbt_cfgelm_double);
682
683   if (variable->max == 1) {
684     if (variable->cb_rm && xbt_dynar_length(variable->content))
685       (*variable->cb_rm) (name, 0);
686
687     xbt_dynar_set(variable->content, 0, &val);
688   } else {
689     if (variable->max && xbt_dynar_length(variable->content) == variable->max)
690       THROW3(mismatch_error, 0,
691              "Cannot add value %f to the config element %s since it's already full (size=%d)",
692              val, name, variable->max);
693
694     xbt_dynar_push(variable->content, &val);
695   }
696
697   if (variable->cb_set)
698     (*variable->cb_set) (name, xbt_dynar_length(variable->content) - 1);
699 }
700
701 /** @brief Set or add a string value to \a name within \a cfg
702  *
703  * \arg cfg the config set
704  * \arg name the name of the variable
705  * \arg val the value to be added
706  *
707  */
708
709 void xbt_cfg_set_string(xbt_cfg_t cfg, const char *name, const char *val)
710 {
711   xbt_cfgelm_t variable;
712   char *newval = xbt_strdup(val);
713
714   VERB2("Configuration setting: %s=%s", name, val);
715   variable = xbt_cfgelm_get(cfg, name, xbt_cfgelm_string);
716   DEBUG5("Variable: %d to %d %s (=%d) @%p",
717          variable->min, variable->max, xbt_cfgelm_type_name[variable->type],
718          variable->type, variable);
719
720   if (variable->max == 1) {
721     if (xbt_dynar_length(variable->content)) {
722       if (variable->cb_rm)
723         (*variable->cb_rm) (name, 0);
724       else if (variable->type == xbt_cfgelm_string) {
725         char *sval = xbt_dynar_get_as(variable->content, 0, char *);
726         free(sval);
727       }
728     }
729
730     xbt_dynar_set(variable->content, 0, &newval);
731   } else {
732     if (variable->max && xbt_dynar_length(variable->content) == variable->max)
733       THROW3(mismatch_error, 0,
734              "Cannot add value %s to the config element %s since it's already full (size=%d)",
735              name, val, variable->max);
736
737     xbt_dynar_push(variable->content, &newval);
738   }
739
740   if (variable->cb_set)
741     (*variable->cb_set) (name, xbt_dynar_length(variable->content) - 1);
742 }
743
744 /** @brief Set or add an peer value to \a name within \a cfg
745  *
746  * \arg cfg the config set
747  * \arg name the name of the variable
748  * \arg peer the peer
749  * \arg port the port number
750  *
751  * \e peer values are composed of a string (peername) and an integer (port)
752  */
753
754 void
755 xbt_cfg_set_peer(xbt_cfg_t cfg, const char *name, const char *peer, int port)
756 {
757   xbt_cfgelm_t variable;
758   xbt_peer_t val = xbt_peer_new(peer, port);
759
760   VERB3("Configuration setting: %s=%s:%d", name, peer, port);
761
762   variable = xbt_cfgelm_get(cfg, name, xbt_cfgelm_peer);
763
764   if (variable->max == 1) {
765     if (variable->cb_rm && xbt_dynar_length(variable->content))
766       (*variable->cb_rm) (name, 0);
767
768     xbt_dynar_set(variable->content, 0, &val);
769   } else {
770     if (variable->max && xbt_dynar_length(variable->content) == variable->max)
771       THROW4(mismatch_error, 0,
772              "Cannot add value %s:%d to the config element %s since it's already full (size=%d)",
773              peer, port, name, variable->max);
774
775     xbt_dynar_push(variable->content, &val);
776   }
777
778   if (variable->cb_set)
779     (*variable->cb_set) (name, xbt_dynar_length(variable->content) - 1);
780 }
781
782 /* ---- [ Removing ] ---- */
783
784 /** @brief Remove the provided \e val integer value from a variable
785  *
786  * \arg cfg the config set
787  * \arg name the name of the variable
788  * \arg val the value to be removed
789  */
790 void xbt_cfg_rm_int(xbt_cfg_t cfg, const char *name, int val)
791 {
792
793   xbt_cfgelm_t variable;
794   unsigned int cpt;
795   int seen;
796
797   variable = xbt_cfgelm_get(cfg, name, xbt_cfgelm_int);
798
799   if (xbt_dynar_length(variable->content) == variable->min)
800     THROW3(mismatch_error, 0,
801            "Cannot remove value %d from the config element %s since it's already at its minimal size (=%d)",
802            val, name, variable->min);
803
804   xbt_dynar_foreach(variable->content, cpt, seen) {
805     if (seen == val) {
806       if (variable->cb_rm)
807         (*variable->cb_rm) (name, cpt);
808       xbt_dynar_cursor_rm(variable->content, &cpt);
809       return;
810     }
811   }
812
813   THROW2(not_found_error, 0,
814          "Can't remove the value %d of config element %s: value not found.",
815          val, name);
816 }
817
818 /** @brief Remove the provided \e val double value from a variable
819  *
820  * \arg cfg the config set
821  * \arg name the name of the variable
822  * \arg val the value to be removed
823  */
824
825 void xbt_cfg_rm_double(xbt_cfg_t cfg, const char *name, double val)
826 {
827   xbt_cfgelm_t variable;
828   unsigned int cpt;
829   double seen;
830
831   variable = xbt_cfgelm_get(cfg, name, xbt_cfgelm_double);
832
833   if (xbt_dynar_length(variable->content) == variable->min)
834     THROW3(mismatch_error, 0,
835            "Cannot remove value %f from the config element %s since it's already at its minimal size (=%d)",
836            val, name, variable->min);
837
838   xbt_dynar_foreach(variable->content, cpt, seen) {
839     if (seen == val) {
840       xbt_dynar_cursor_rm(variable->content, &cpt);
841       if (variable->cb_rm)
842         (*variable->cb_rm) (name, cpt);
843       return;
844     }
845   }
846
847   THROW2(not_found_error, 0,
848          "Can't remove the value %f of config element %s: value not found.",
849          val, name);
850 }
851
852 /** @brief Remove the provided \e val string value from a variable
853  *
854  * \arg cfg the config set
855  * \arg name the name of the variable
856  * \arg val the value of the string which will be removed
857  */
858 void xbt_cfg_rm_string(xbt_cfg_t cfg, const char *name, const char *val)
859 {
860   xbt_cfgelm_t variable;
861   unsigned int cpt;
862   char *seen;
863
864   variable = xbt_cfgelm_get(cfg, name, xbt_cfgelm_string);
865
866   if (xbt_dynar_length(variable->content) == variable->min)
867     THROW3(mismatch_error, 0,
868            "Cannot remove value %s from the config element %s since it's already at its minimal size (=%d)",
869            name, val, variable->min);
870
871   xbt_dynar_foreach(variable->content, cpt, seen) {
872     if (!strcpy(seen, val)) {
873       if (variable->cb_rm)
874         (*variable->cb_rm) (name, cpt);
875       xbt_dynar_cursor_rm(variable->content, &cpt);
876       return;
877     }
878   }
879
880   THROW2(not_found_error, 0,
881          "Can't remove the value %s of config element %s: value not found.",
882          val, name);
883 }
884
885 /** @brief Remove the provided \e val peer value from a variable
886  *
887  * \arg cfg the config set
888  * \arg name the name of the variable
889  * \arg peer the peername
890  * \arg port the port number
891  */
892
893 void
894 xbt_cfg_rm_peer(xbt_cfg_t cfg, const char *name, const char *peer, int port)
895 {
896   xbt_cfgelm_t variable;
897   unsigned int cpt;
898   xbt_peer_t seen;
899
900   variable = xbt_cfgelm_get(cfg, name, xbt_cfgelm_peer);
901
902   if (xbt_dynar_length(variable->content) == variable->min)
903     THROW4(mismatch_error, 0,
904            "Cannot remove value %s:%d from the config element %s since it's already at its minimal size (=%d)",
905            peer, port, name, variable->min);
906
907   xbt_dynar_foreach(variable->content, cpt, seen) {
908     if (!strcpy(seen->name, peer) && seen->port == port) {
909       if (variable->cb_rm)
910         (*variable->cb_rm) (name, cpt);
911       xbt_dynar_cursor_rm(variable->content, &cpt);
912       return;
913     }
914   }
915
916   THROW3(not_found_error, 0,
917          "Can't remove the value %s:%d of config element %s: value not found.",
918          peer, port, name);
919 }
920
921 /** @brief Remove the \e pos th value from the provided variable */
922
923 void xbt_cfg_rm_at(xbt_cfg_t cfg, const char *name, int pos)
924 {
925
926   xbt_cfgelm_t variable;
927
928   variable = xbt_cfgelm_get(cfg, name, xbt_cfgelm_any);
929
930   if (xbt_dynar_length(variable->content) == variable->min)
931     THROW3(mismatch_error, 0,
932            "Cannot remove %dth value from the config element %s since it's already at its minimal size (=%d)",
933            pos, name, variable->min);
934
935   if (variable->cb_rm)
936     (*variable->cb_rm) (name, pos);
937   xbt_dynar_remove_at(variable->content, pos, NULL);
938 }
939
940 /** @brief Remove all the values from a variable
941  *
942  * \arg cfg the config set
943  * \arg name the name of the variable
944  */
945
946 void xbt_cfg_empty(xbt_cfg_t cfg, const char *name)
947 {
948   xbt_cfgelm_t variable = NULL;
949   xbt_ex_t e;
950
951   TRY {
952     variable = xbt_dict_get((xbt_dict_t) cfg, name);
953   } CATCH(e) {
954     if (e.category != not_found_error)
955       RETHROW;
956
957     xbt_ex_free(e);
958     THROW1(not_found_error, 0,
959            "Can't empty  '%s' since this config element does not exist",
960            name);
961   }
962
963   if (variable) {
964     if (variable->cb_rm) {
965       unsigned int cpt;
966       void *ignored;
967       xbt_dynar_foreach(variable->content, cpt, ignored) {
968         (*variable->cb_rm) (name, cpt);
969       }
970     }
971     xbt_dynar_reset(variable->content);
972   }
973 }
974
975 /*----[ Getting ]---------------------------------------------------------*/
976
977 /** @brief Retrieve an integer value of a variable (get a warning if not uniq)
978  *
979  * \arg cfg the config set
980  * \arg name the name of the variable
981  * \arg val the wanted value
982  *
983  * Returns the first value from the config set under the given name.
984  * If there is more than one value, it will issue a warning. Consider using
985  * xbt_cfg_get_dynar() instead.
986  *
987  * \warning the returned value is the actual content of the config set
988  */
989 int xbt_cfg_get_int(xbt_cfg_t cfg, const char *name)
990 {
991   xbt_cfgelm_t variable = xbt_cfgelm_get(cfg, name, xbt_cfgelm_int);
992
993   if (xbt_dynar_length(variable->content) > 1) {
994     WARN2
995       ("You asked for the first value of the config element '%s', but there is %lu values",
996        name, xbt_dynar_length(variable->content));
997   }
998
999   return xbt_dynar_get_as(variable->content, 0, int);
1000 }
1001
1002 /** @brief Retrieve a double value of a variable (get a warning if not uniq)
1003  *
1004  * \arg cfg the config set
1005  * \arg name the name of the variable
1006  * \arg val the wanted value
1007  *
1008  * Returns the first value from the config set under the given name.
1009  * If there is more than one value, it will issue a warning. Consider using
1010  * xbt_cfg_get_dynar() instead.
1011  *
1012  * \warning the returned value is the actual content of the config set
1013  */
1014
1015 double xbt_cfg_get_double(xbt_cfg_t cfg, const char *name)
1016 {
1017   xbt_cfgelm_t variable = xbt_cfgelm_get(cfg, name, xbt_cfgelm_double);
1018
1019   if (xbt_dynar_length(variable->content) > 1) {
1020     WARN2
1021       ("You asked for the first value of the config element '%s', but there is %lu values\n",
1022        name, xbt_dynar_length(variable->content));
1023   }
1024
1025   return xbt_dynar_get_as(variable->content, 0, double);
1026 }
1027
1028 /** @brief Retrieve a string value of a variable (get a warning if not uniq)
1029  *
1030  * \arg th the config set
1031  * \arg name the name of the variable
1032  * \arg val the wanted value
1033  *
1034  * Returns the first value from the config set under the given name.
1035  * If there is more than one value, it will issue a warning. Consider using
1036  * xbt_cfg_get_dynar() instead.
1037  *
1038  * \warning the returned value is the actual content of the config set
1039  */
1040
1041 char *xbt_cfg_get_string(xbt_cfg_t cfg, const char *name)
1042 {
1043   xbt_cfgelm_t variable = xbt_cfgelm_get(cfg, name, xbt_cfgelm_string);
1044
1045   if (xbt_dynar_length(variable->content) > 1) {
1046     WARN2
1047       ("You asked for the first value of the config element '%s', but there is %lu values\n",
1048        name, xbt_dynar_length(variable->content));
1049   }
1050
1051   return xbt_dynar_get_as(variable->content, 0, char *);
1052 }
1053
1054 /** @brief Retrieve an peer value of a variable (get a warning if not uniq)
1055  *
1056  * \arg cfg the config set
1057  * \arg name the name of the variable
1058  * \arg peer the peer
1059  * \arg port the port number
1060  *
1061  * Returns the first value from the config set under the given name.
1062  * If there is more than one value, it will issue a warning. Consider using
1063  * xbt_cfg_get_dynar() instead.
1064  *
1065  * \warning the returned value is the actual content of the config set
1066  */
1067
1068 void xbt_cfg_get_peer(xbt_cfg_t cfg, const char *name, char **peer, int *port)
1069 {
1070   xbt_cfgelm_t variable;
1071   xbt_peer_t val;
1072
1073   variable = xbt_cfgelm_get(cfg, name, xbt_cfgelm_peer);
1074
1075   if (xbt_dynar_length(variable->content) > 1) {
1076     WARN2
1077       ("You asked for the first value of the config element '%s', but there is %lu values\n",
1078        name, xbt_dynar_length(variable->content));
1079   }
1080
1081   val = xbt_dynar_get_as(variable->content, 0, xbt_peer_t);
1082   *peer = val->name;
1083   *port = val->port;
1084 }
1085
1086 /** @brief Retrieve the dynar of all the values stored in a variable
1087  *
1088  * \arg cfg where to search in
1089  * \arg name what to search for
1090  * \arg dynar result
1091  *
1092  * Get the data stored in the config set.
1093  *
1094  * \warning the returned value is the actual content of the config set
1095  */
1096 xbt_dynar_t xbt_cfg_get_dynar(xbt_cfg_t cfg, const char *name)
1097 {
1098   xbt_cfgelm_t variable = NULL;
1099   xbt_ex_t e;
1100
1101   TRY {
1102     variable = xbt_dict_get((xbt_dict_t) cfg, name);
1103   } CATCH(e) {
1104     if (e.category == not_found_error) {
1105       xbt_ex_free(e);
1106       THROW1(not_found_error, 0,
1107              "No registered variable %s in this config set", name);
1108     }
1109     RETHROW;
1110   }
1111
1112   return variable->content;
1113 }
1114
1115
1116 /** @brief Retrieve one of the integer value of a variable */
1117 int xbt_cfg_get_int_at(xbt_cfg_t cfg, const char *name, int pos)
1118 {
1119
1120   xbt_cfgelm_t variable = xbt_cfgelm_get(cfg, name, xbt_cfgelm_int);
1121   return xbt_dynar_get_as(variable->content, pos, int);
1122 }
1123
1124 /** @brief Retrieve one of the double value of a variable */
1125 double xbt_cfg_get_double_at(xbt_cfg_t cfg, const char *name, int pos)
1126 {
1127
1128   xbt_cfgelm_t variable = xbt_cfgelm_get(cfg, name, xbt_cfgelm_double);
1129   return xbt_dynar_get_as(variable->content, pos, double);
1130 }
1131
1132
1133 /** @brief Retrieve one of the string value of a variable */
1134 char *xbt_cfg_get_string_at(xbt_cfg_t cfg, const char *name, int pos)
1135 {
1136
1137   xbt_cfgelm_t variable = xbt_cfgelm_get(cfg, name, xbt_cfgelm_string);
1138   return xbt_dynar_get_as(variable->content, pos, char *);
1139 }
1140
1141 /** @brief Retrieve one of the peer value of a variable */
1142 void
1143 xbt_cfg_get_peer_at(xbt_cfg_t cfg, const char *name, int pos,
1144                     char **peer, int *port)
1145 {
1146
1147   xbt_cfgelm_t variable = xbt_cfgelm_get(cfg, name, xbt_cfgelm_int);
1148   xbt_peer_t val = xbt_dynar_get_ptr(variable->content, pos);
1149
1150   *port = val->port;
1151   *peer = val->name;
1152 }
1153
1154
1155 #ifdef SIMGRID_TEST
1156 #include "xbt.h"
1157 #include "xbt/ex.h"
1158
1159 XBT_LOG_EXTERNAL_CATEGORY(xbt_cfg);
1160
1161 XBT_TEST_SUITE("config", "Configuration support");
1162
1163 static xbt_cfg_t make_set()
1164 {
1165   xbt_cfg_t set = NULL;
1166
1167   xbt_log_threshold_set(&_XBT_LOGV(xbt_cfg),xbt_log_priority_critical);
1168   set = xbt_cfg_new();
1169   xbt_cfg_register_str(set, "speed:1_to_2_int");
1170   xbt_cfg_register_str(set, "peername:1_to_1_string");
1171   xbt_cfg_register_str(set, "user:1_to_10_string");
1172
1173   return set;
1174 }                               /* end_of_make_set */
1175
1176 XBT_TEST_UNIT("memuse", test_config_memuse, "Alloc and free a config set")
1177 {
1178   xbt_cfg_t set = make_set();
1179   xbt_test_add0("Alloc and free a config set");
1180   xbt_cfg_set_parse(set,
1181                     "peername:veloce user:mquinson\nuser:oaumage\tuser:alegrand");
1182   xbt_cfg_free(&set);
1183   xbt_cfg_free(&set);
1184 }
1185
1186 XBT_TEST_UNIT("validation", test_config_validation, "Validation tests")
1187 {
1188   xbt_cfg_t set = set = make_set();
1189   xbt_ex_t e;
1190
1191   xbt_test_add0("Having too few elements for speed");
1192   xbt_cfg_set_parse(set,
1193                     "peername:veloce user:mquinson\nuser:oaumage\tuser:alegrand");
1194   TRY {
1195     xbt_cfg_check(set);
1196   }
1197   CATCH(e) {
1198     if (e.category != mismatch_error ||
1199         strncmp(e.msg, "Config elem speed needs",
1200                 strlen("Config elem speed needs")))
1201       xbt_test_fail1("Got an exception. msg=%s", e.msg);
1202     xbt_ex_free(e);
1203   }
1204   xbt_cfg_free(&set);
1205   xbt_cfg_free(&set);
1206
1207
1208
1209   xbt_test_add0("Having too much values of 'speed'");
1210   set = make_set();
1211   xbt_cfg_set_parse(set, "peername:toto:42 user:alegrand");
1212   TRY {
1213     xbt_cfg_set_parse(set, "speed:42 speed:24 speed:34");
1214   }
1215   CATCH(e) {
1216     if (e.category != mismatch_error ||
1217         strncmp(e.msg, "Cannot add value 34 to the config elem speed",
1218                 strlen("Config elem speed needs")))
1219       xbt_test_fail1("Got an exception. msg=%s", e.msg);
1220     xbt_ex_free(e);
1221   }
1222   xbt_cfg_check(set);
1223   xbt_cfg_free(&set);
1224   xbt_cfg_free(&set);
1225
1226 }
1227
1228 XBT_TEST_UNIT("use", test_config_use, "Data retrieving tests")
1229 {
1230
1231   xbt_test_add0("Get a single value");
1232   {
1233     /* get_single_value */
1234     int ival;
1235     xbt_cfg_t myset = make_set();
1236
1237     xbt_cfg_set_parse(myset, "peername:toto:42 speed:42");
1238     ival = xbt_cfg_get_int(myset, "speed");
1239     if (ival != 42)
1240       xbt_test_fail1("Speed value = %d, I expected 42", ival);
1241     xbt_cfg_free(&myset);
1242   }
1243
1244   xbt_test_add0("Get multiple values");
1245   {
1246     /* get_multiple_value */
1247     xbt_dynar_t dyn;
1248     xbt_cfg_t myset = make_set();
1249
1250     xbt_cfg_set_parse(myset, "peername:veloce user:foo\nuser:bar\tuser:toto");
1251     xbt_cfg_set_parse(myset, "speed:42");
1252     xbt_cfg_check(myset);
1253     dyn = xbt_cfg_get_dynar(myset, "user");
1254
1255     if (xbt_dynar_length(dyn) != 3)
1256       xbt_test_fail1("Dynar length = %lu, I expected 3",
1257                      xbt_dynar_length(dyn));
1258
1259     if (strcmp(xbt_dynar_get_as(dyn, 0, char *), "foo"))
1260         xbt_test_fail1("Dynar[0] = %s, I expected foo",
1261                        xbt_dynar_get_as(dyn, 0, char *));
1262
1263     if (strcmp(xbt_dynar_get_as(dyn, 1, char *), "bar"))
1264         xbt_test_fail1("Dynar[1] = %s, I expected bar",
1265                        xbt_dynar_get_as(dyn, 1, char *));
1266
1267     if (strcmp(xbt_dynar_get_as(dyn, 2, char *), "toto"))
1268         xbt_test_fail1("Dynar[2] = %s, I expected toto",
1269                        xbt_dynar_get_as(dyn, 2, char *));
1270     xbt_cfg_free(&myset);
1271   }
1272
1273   xbt_test_add0("Access to a non-existant entry");
1274   {
1275     /* non-existant_entry */
1276     xbt_cfg_t myset = make_set();
1277     xbt_ex_t e;
1278
1279     TRY {
1280       xbt_cfg_set_parse(myset, "color:blue");
1281     } CATCH(e) {
1282       if (e.category != not_found_error)
1283         xbt_test_exception(e);
1284       xbt_ex_free(e);
1285     }
1286     xbt_cfg_free(&myset);
1287   }
1288 }
1289 #endif /* SIMGRID_TEST */