Logo AND Algorithmique Numérique Distribuée

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