Logo AND Algorithmique Numérique Distribuée

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