Logo AND Algorithmique Numérique Distribuée

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