Logo AND Algorithmique Numérique Distribuée

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