Logo AND Algorithmique Numérique Distribuée

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