Logo AND Algorithmique Numérique Distribuée

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