Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' of scm.gforge.inria.fr:/gitroot/simgrid/simgrid
[simgrid.git] / src / xbt / config.cpp
1 /* Copyright (c) 2004-2014,2016. The SimGrid Team.
2  * All rights reserved.                                                     */
3
4 #include <stdio.h>
5
6 #include <cerrno>
7 #include <cstring>
8 #include <climits>
9
10 #include <functional>
11 #include <stdexcept>
12 #include <string>
13 #include <typeinfo>
14 #include <type_traits>
15
16 #include <xbt/config.h>
17 #include <xbt/config.hpp>
18 #include "xbt/misc.h"
19 #include "xbt/sysdep.h"
20 #include "xbt/log.h"
21 #include "xbt/ex.h"
22 #include "xbt/dynar.h"
23 #include "xbt/dict.h"
24
25 // *****
26
27 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_cfg, xbt, "configuration support");
28
29 XBT_EXPORT_NO_IMPORT(xbt_cfg_t) simgrid_config = NULL;
30
31 namespace simgrid {
32 namespace config {
33
34 class Config;
35
36 namespace {
37
38 const char* true_values[] = {
39   "yes", "on", "true", "1"
40 };
41 const char* false_values[] = {
42   "no", "off", "false", "0"
43 };
44
45 static bool parseBool(const char* value)
46 {
47   for (const char* true_value : true_values)
48     if (std::strcmp(true_value, value) == 0)
49       return true;
50   for (const char* false_value : false_values)
51     if (std::strcmp(false_value, value) == 0)
52       return false;
53   throw std::domain_error("not a boolean");
54 }
55
56 static double parseDouble(const char* value)
57 {
58   char* end;
59   errno = 0;
60   double res = std::strtod(value, &end);
61   if (errno == ERANGE)
62     throw std::range_error("out of range");
63   else if (errno)
64     xbt_die("Unexpected errno");
65   if (end == value || *end != '\0')
66     throw std::range_error("invalid double");
67   else
68     return res;
69 }
70
71 static long int parseLong(const char* value)
72 {
73   char* end;
74   errno = 0;
75   long int res = std::strtol(value, &end, 0);
76   if (errno) {
77     if (res == LONG_MIN && errno == ERANGE)
78       throw std::range_error("underflow");
79     else if (res == LONG_MAX && errno == ERANGE)
80       throw std::range_error("overflow");
81     xbt_die("Unexpected errno");
82   }
83   if (end == value || *end != '\0')
84     throw std::range_error("invalid integer");
85   else
86     return res;
87 }
88
89 // ***** ConfigType *****
90
91 /// A trait which define possible options types:
92 template<class T> struct ConfigType;
93
94 template<> struct ConfigType<int> {
95   static constexpr const char* type_name = "int";
96   static inline double parse(const char* value)
97   {
98     return parseLong(value);
99   }
100 };
101 template<> struct ConfigType<double> {
102   static constexpr const char* type_name = "double";
103   static inline double parse(const char* value)
104   {
105     return parseDouble(value);
106   }
107 };
108 template<> struct ConfigType<std::string> {
109   static constexpr const char* type_name = "string";
110   static inline std::string parse(const char* value)
111   {
112     return std::string(value);
113   }
114 };
115 template<> struct ConfigType<bool> {
116   static constexpr const char* type_name = "boolean";
117   static inline bool parse(const char* value)
118   {
119     return parseBool(value);
120   }
121 };
122
123 // **** Forward declarations ****
124
125 class ConfigurationElement ;
126 template<class T> class TypedConfigurationElement;
127
128 // **** ConfigurationElement ****
129
130 class ConfigurationElement {
131 protected:
132   std::string key;
133   std::string desc;
134   bool isdefault = true;
135
136 public:
137
138   /* Callback */
139   xbt_cfg_cb_t old_callback = nullptr;
140
141   ConfigurationElement(const char* key, const char* desc)
142     : key(key ? key : ""), desc(desc ? desc : "") {}
143   ConfigurationElement(const char* key, const char* desc, xbt_cfg_cb_t cb)
144     : key(key ? key : ""), desc(desc ? desc : ""), old_callback(cb) {}
145
146   virtual ~ConfigurationElement();
147
148   virtual std::string getStringValue() = 0;
149   virtual void setStringValue(const char* value) = 0;
150   virtual const char* getTypeName() = 0;
151
152   template<class T>
153   T const& getValue() const
154   {
155     return dynamic_cast<const TypedConfigurationElement<T>&>(*this).getValue();
156   }
157   template<class T>
158   void setValue(T value)
159   {
160     dynamic_cast<TypedConfigurationElement<T>&>(*this).setValue(std::move(value));
161   }
162   template<class T>
163   void setDefaultValue(T value)
164   {
165     dynamic_cast<TypedConfigurationElement<T>&>(*this).setDefaultValue(std::move(value));
166   }
167   bool isDefault() const { return isdefault; }
168
169   std::string const& getDescription() const { return desc; }
170 };
171
172 ConfigurationElement::~ConfigurationElement() {}
173
174 // **** TypedConfigurationElement<T> ****
175
176 // TODO, could we use boost::any with some Type* reference?
177 template<class T>
178 class TypedConfigurationElement : public ConfigurationElement {
179 private:
180   T content;
181   std::function<void(T&)> callback;
182
183 public:
184   TypedConfigurationElement(const char* key, const char* desc, T value = T())
185     : ConfigurationElement(key, desc), content(std::move(value))
186   {}
187   TypedConfigurationElement(const char* key, const char* desc, T value,
188       xbt_cfg_cb_t cb)
189     : ConfigurationElement(key, desc, cb), content(std::move(value))
190   {}
191   TypedConfigurationElement(const char* key, const char* desc, T value,
192       std::function<void(T&)> callback)
193     : ConfigurationElement(key, desc), content(std::move(value)),
194       callback(std::move(callback))
195   {}
196   ~TypedConfigurationElement() override;
197
198   std::string getStringValue() override;
199   const char* getTypeName() override;
200   void setStringValue(const char* value) override;
201
202   void update()
203   {
204     if (old_callback)
205       this->old_callback(key.c_str());
206     if (this->callback)
207       this->callback(this->content);
208   }
209
210   T const& getValue() const { return content; }
211
212   void setValue(T value)
213   {
214     this->content = std::move(value);
215     this->update();
216   }
217
218   void setDefaultValue(T value)
219   {
220     if (this->isdefault) {
221       this->content = std::move(value);
222       this->update();
223     } else {
224       XBT_DEBUG("Do not override configuration variable '%s' with value '%s'"
225         " because it was already set.", key.c_str(), to_string(value).c_str());
226     }
227   }
228 };
229
230 template<class T>
231 std::string TypedConfigurationElement<T>::getStringValue() // override
232 {
233   return to_string(content);
234 }
235
236 template<class T>
237 void TypedConfigurationElement<T>::setStringValue(const char* value) // override
238 {
239   this->content = ConfigType<T>::parse(value);
240   this->isdefault = false;
241   this->update();
242 }
243
244 template<class T>
245 const char* TypedConfigurationElement<T>::getTypeName() // override
246 {
247   return ConfigType<T>::type_name;
248 }
249
250 template<class T>
251 TypedConfigurationElement<T>::~TypedConfigurationElement()
252 {}
253
254 } // end of anonymous namespace
255
256 // **** Config ****
257
258 class Config {
259 private:
260   // name -> ConfigElement:
261   xbt_dict_t options;
262   // alias -> xbt_dict_elm_t from options:
263   xbt_dict_t aliases;
264
265 public:
266   Config();
267   ~Config();
268
269   // No copy:
270   Config(Config const&) = delete;
271   Config& operator=(Config const&) = delete;
272
273   ConfigurationElement& operator[](const char* name);
274   template<class T>
275   TypedConfigurationElement<T>& getTyped(const char* name);
276   void alias(const char* realname, const char* aliasname);
277
278   template<class T, class... A>
279   simgrid::config::TypedConfigurationElement<T>*
280     registerOption(const char* name, A&&... a)
281   {
282     xbt_assert(xbt_dict_get_or_null(this->options, name) == nullptr,
283       "Refusing to register the config element '%s' twice.", name);
284     TypedConfigurationElement<T>* variable =
285       new TypedConfigurationElement<T>(name, std::forward<A>(a)...);
286     XBT_DEBUG("Register cfg elm %s (%s) of type %s @%p in set %p)",
287               name,
288               variable->getDescription().c_str(),
289               variable->getTypeName(), variable, this);
290     xbt_dict_set(this->options, name, variable, NULL);
291     variable->update();
292     return variable;
293   }
294
295   // Debug:
296   void dump(const char *name, const char *indent);
297   void showAliases();
298   void help();
299
300 protected:
301   xbt_dictelm_t getDictElement(const char* name);
302 };
303
304 /* Internal stuff used in cache to free a variable */
305 static void xbt_cfgelm_free(void *data)
306 {
307   if (data)
308     delete (simgrid::config::ConfigurationElement*) data;
309 }
310
311 Config::Config() :
312   options(xbt_dict_new_homogeneous(xbt_cfgelm_free)),
313   aliases(xbt_dict_new_homogeneous(NULL))
314 {}
315
316 Config::~Config()
317 {
318   XBT_DEBUG("Frees cfg set %p", this);
319   xbt_dict_free(&this->options);
320   xbt_dict_free(&this->aliases);
321 }
322
323 inline
324 xbt_dictelm_t Config::getDictElement(const char* name)
325 {
326   // We are interested in the options dictelm:
327   xbt_dictelm_t res = xbt_dict_get_elm_or_null(options, name);
328   if (res)
329     return res;
330   // The aliases dict stores pointers to the options dictelm:
331   res = (xbt_dictelm_t) xbt_dict_get_or_null(aliases, name);
332   if (res)
333     XBT_INFO("Option %s has been renamed to %s. Consider switching.", name, res->key);
334   return res;
335 }
336
337 inline
338 ConfigurationElement& Config::operator[](const char* name)
339 {
340   xbt_dictelm_t elm = getDictElement(name);
341   if (elm == nullptr)
342     throw std::invalid_argument(std::string("Bad config key, ") + name);
343   return *(ConfigurationElement*)elm->content;
344 }
345
346 void Config::alias(const char* realname, const char* aliasname)
347 {
348   xbt_assert(this->getDictElement(aliasname) == nullptr, "Alias '%s' already.", aliasname);
349   xbt_dictelm_t element = this->getDictElement(realname);
350   xbt_assert(element, "Cannot define an alias to the non-existing option '%s'.", realname);
351   xbt_dict_set(this->aliases, aliasname, element, NULL);
352 }
353
354 /** @brief Dump a config set for debuging purpose
355  *
356  * @param name The name to give to this config set
357  * @param indent what to write at the beginning of each line (right number of spaces)
358  */
359 void Config::dump(const char *name, const char *indent)
360 {
361   xbt_dict_t dict = this->options;
362   xbt_dict_cursor_t cursor = NULL;
363   simgrid::config::ConfigurationElement* variable = NULL;
364   char *key = NULL;
365
366   if (name)
367     printf("%s>> Dumping of the config set '%s':\n", indent, name);
368
369   xbt_dict_foreach(dict, cursor, key, variable)
370     printf("%s  %s: ()%s) %s", indent, key,
371       variable->getTypeName(),
372       variable->getStringValue().c_str());
373
374   if (name)
375     printf("%s<< End of the config set '%s'\n", indent, name);
376   fflush(stdout);
377
378   xbt_dict_cursor_free(&cursor);
379 }
380
381 /** @brief Displays the declared aliases and their description */
382 void Config::showAliases()
383 {
384   xbt_dict_cursor_t dict_cursor;
385   unsigned int dynar_cursor;
386   xbt_dictelm_t dictel;
387   char *name;
388   xbt_dynar_t names = xbt_dynar_new(sizeof(char *), NULL);
389
390   xbt_dict_foreach(this->aliases, dict_cursor, name, dictel)
391     xbt_dynar_push(names, &name);
392   xbt_dynar_sort_strings(names);
393
394   xbt_dynar_foreach(names, dynar_cursor, name)
395     printf("   %s: %s\n", name, (*this)[name].getDescription().c_str());
396 }
397
398 /** @brief Displays the declared options and their description */
399 void Config::help()
400 {
401   xbt_dict_cursor_t dict_cursor;
402   unsigned int dynar_cursor;
403   simgrid::config::ConfigurationElement* variable;
404   char *name;
405   xbt_dynar_t names = xbt_dynar_new(sizeof(char *), NULL);
406
407   xbt_dict_foreach(this->options, dict_cursor, name, variable)
408     xbt_dynar_push(names, &name);
409   xbt_dynar_sort_strings(names);
410
411   xbt_dynar_foreach(names, dynar_cursor, name) {
412     variable = (simgrid::config::ConfigurationElement*) xbt_dict_get(this->options, name);
413     printf("   %s: %s\n", name, variable->getDescription().c_str());
414     printf("       Type: %s; ", variable->getTypeName());
415     printf("Current value: %s\n", variable->getStringValue().c_str());
416   }
417   xbt_dynar_free(&names);
418 }
419
420 // ***** getConfig *****
421
422 template<class T>
423 XBT_PUBLIC(T const&) getConfig(const char* name)
424 {
425   return (*simgrid_config)[name].getValue<T>();
426 }
427
428 template XBT_PUBLIC(int const&) getConfig<int>(const char* name);
429 template XBT_PUBLIC(double const&) getConfig<double>(const char* name);
430 template XBT_PUBLIC(bool const&) getConfig<bool>(const char* name);
431 template XBT_PUBLIC(std::string const&) getConfig<std::string>(const char* name);
432
433 // ***** declareFlag *****
434
435 template<class T>
436 XBT_PUBLIC(void) declareFlag(const char* name, const char* description,
437   T value, std::function<void(const T&)> callback)
438 {
439   if (simgrid_config == NULL)
440     simgrid_config = xbt_cfg_new();
441   simgrid_config->registerOption<T>(
442     name, description, std::move(value), std::move(callback));
443 }
444
445 template XBT_PUBLIC(void) declareFlag(const char* name,
446   const char* description, int value, std::function<void(int const &)> callback);
447 template XBT_PUBLIC(void) declareFlag(const char* name,
448   const char* description, double value, std::function<void(double const &)> callback);
449 template XBT_PUBLIC(void) declareFlag(const char* name,
450   const char* description, bool value, std::function<void(bool const &)> callback);
451 template XBT_PUBLIC(void) declareFlag(const char* name,
452   const char* description, std::string value, std::function<void(std::string const &)> callback);
453
454
455 }
456 }
457
458 // ***** C bindings *****
459
460 xbt_cfg_t xbt_cfg_new(void)        { return new simgrid::config::Config(); }
461 void xbt_cfg_free(xbt_cfg_t * cfg) { delete *cfg; }
462
463 void xbt_cfg_dump(const char *name, const char *indent, xbt_cfg_t cfg)
464 {
465   cfg->dump(name, indent);
466 }
467
468 /*----[ Registering stuff ]-----------------------------------------------*/
469
470 void xbt_cfg_register_double(const char *name, double default_value,
471   xbt_cfg_cb_t cb_set, const char *desc)
472 {
473   if (simgrid_config == NULL)
474     simgrid_config = xbt_cfg_new();
475   simgrid_config->registerOption<double>(name, desc, default_value, cb_set);
476 }
477
478 void xbt_cfg_register_int(const char *name, int default_value,xbt_cfg_cb_t cb_set, const char *desc)
479 {
480   if (simgrid_config == NULL)
481     simgrid_config = xbt_cfg_new();
482   simgrid_config->registerOption<int>(name, desc, default_value, cb_set);
483 }
484
485 void xbt_cfg_register_string(const char *name, const char *default_value, xbt_cfg_cb_t cb_set, const char *desc)
486 {
487   if (simgrid_config == NULL)
488     simgrid_config = xbt_cfg_new();
489   simgrid_config->registerOption<std::string>(name, desc,
490     default_value ? default_value : "", cb_set);
491 }
492
493 void xbt_cfg_register_boolean(const char *name, const char*default_value,xbt_cfg_cb_t cb_set, const char *desc)
494 {
495   if (simgrid_config == NULL)
496     simgrid_config = xbt_cfg_new();
497   simgrid_config->registerOption<bool>(name, desc, simgrid::config::parseBool(default_value), cb_set);
498 }
499
500 void xbt_cfg_register_alias(const char *realname, const char *aliasname)
501 {
502   if (simgrid_config == NULL)
503     simgrid_config = xbt_cfg_new();
504   simgrid_config->alias(realname, aliasname);
505 }
506
507 void xbt_cfg_aliases(void) { simgrid_config->showAliases(); }
508 void xbt_cfg_help(void)    { simgrid_config->help(); }
509
510 /*----[ Setting ]---------------------------------------------------------*/
511
512 /** @brief Add values parsed from a string into a config set
513  *
514  * @param options a string containing the content to add to the config set. This is a '\\t',' ' or '\\n' or ','
515  * separated list of variables. Each individual variable is like "[name]:[value]" where [name] is the name of an
516  * already registered variable, and [value] conforms to the data type under which this variable was registered.
517  *
518  * @todo This is a crude manual parser, it should be a proper lexer.
519  */
520 void xbt_cfg_set_parse(const char *options)
521 {
522   if (!options || !strlen(options)) {   /* nothing to do */
523     return;
524   }
525   char *optionlist_cpy = xbt_strdup(options);
526
527   XBT_DEBUG("List to parse and set:'%s'", options);
528   char *option = optionlist_cpy;
529   while (1) {                   /* breaks in the code */
530     if (!option)
531       break;
532     char *name = option;
533     int len = strlen(name);
534     XBT_DEBUG("Still to parse and set: '%s'. len=%d; option-name=%ld", name, len, (long) (option - name));
535
536     /* Pass the value */
537     while (option - name <= (len - 1) && *option != ' ' && *option != '\n' && *option != '\t' && *option != ',') {
538       XBT_DEBUG("Take %c.", *option);
539       option++;
540     }
541     if (option - name == len) {
542       XBT_DEBUG("Boundary=EOL");
543       option = NULL;            /* don't do next iteration */
544     } else {
545       XBT_DEBUG("Boundary on '%c'. len=%d;option-name=%ld", *option, len, (long) (option - name));
546       /* Pass the following blank chars */
547       *(option++) = '\0';
548       while (option - name < (len - 1) && (*option == ' ' || *option == '\n' || *option == '\t')) {
549         /*      fprintf(stderr,"Ignore a blank char.\n"); */
550         option++;
551       }
552       if (option - name == len - 1)
553         option = NULL;          /* don't do next iteration */
554     }
555     XBT_DEBUG("parse now:'%s'; parse later:'%s'", name, option);
556
557     if (name[0] == ' ' || name[0] == '\n' || name[0] == '\t')
558       continue;
559     if (!strlen(name))
560       break;
561
562     char *val = strchr(name, ':');
563     xbt_assert(val, "Option '%s' badly formatted. Should be of the form 'name:value'", name);
564     /* don't free(optionlist_cpy) if the assert fails, 'name' points inside it */
565     *(val++) = '\0';
566
567     if (strncmp(name, "contexts/", strlen("contexts/")) && strncmp(name, "path", strlen("path")))
568       XBT_INFO("Configuration change: Set '%s' to '%s'", name, val);
569
570     try {
571       (*simgrid_config)[name].setStringValue(val);
572     }
573     catch (...) {
574       THROWF(not_found_error, 0, "Could not set the value %s for %s", val, name);
575     }
576   }
577
578   free(optionlist_cpy);
579 }
580
581 /** @brief Set the value of a variable, using the string representation of that value
582  *
583  * @param key name of the variable to modify
584  * @param value string representation of the value to set
585  */
586
587 void xbt_cfg_set_as_string(const char *key, const char *value)
588 {
589   try {
590     (*simgrid_config)[key].setStringValue(value);
591   }
592   catch (std::exception const& e) {
593     THROWF(unknown_error, 0, "%s", e.what());
594   }
595 }
596
597 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
598  *
599  * This is useful to change the default value of a variable while allowing
600  * users to override it with command line arguments
601  */
602 void xbt_cfg_setdefault_int(const char *name, int val)
603 {
604   try {
605     (*simgrid_config)[name].setDefaultValue<int>(val);
606   }
607   catch (std::exception const& e) {
608     THROWF(unknown_error, 0, "%s", e.what());
609   }
610 }
611
612 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
613  *
614  * This is useful to change the default value of a variable while allowing
615  * users to override it with command line arguments
616  */
617 void xbt_cfg_setdefault_double(const char *name, double val)
618 {
619   try {
620     (*simgrid_config)[name].setDefaultValue<double>(val);
621   }
622   catch (std::exception const& e) {
623     THROWF(unknown_error, 0, "%s", e.what());
624   }
625 }
626
627 /** @brief Set a string value to \a name within \a cfg if it wasn't changed yet
628  *
629  * This is useful to change the default value of a variable while allowing
630  * users to override it with command line arguments
631  */
632 void xbt_cfg_setdefault_string(const char *name, const char *val)
633 {
634   try {
635     (*simgrid_config)[name].setDefaultValue<std::string>(val ? val : "");
636   }
637   catch (std::exception const& e) {
638     THROWF(unknown_error, 0, "%s", e.what());
639   }
640 }
641
642 /** @brief Set an boolean value to \a name within \a cfg if it wasn't changed yet
643  *
644  * This is useful to change the default value of a variable while allowing
645  * users to override it with command line arguments
646  */
647 void xbt_cfg_setdefault_boolean(const char *name, const char *val)
648 {
649   try {
650     (*simgrid_config)[name].setDefaultValue<bool>(simgrid::config::parseBool(val));
651   }
652   catch (std::exception const& e) {
653     THROWF(unknown_error, 0, "%s", e.what());
654   }
655 }
656
657 /** @brief Set an integer value to \a name within \a cfg
658  *
659  * @param name the name of the variable
660  * @param val the value of the variable
661  */
662 void xbt_cfg_set_int(const char *name, int val)
663 {
664   try {
665     (*simgrid_config)[name].setValue<int>(val);
666   }
667   catch (std::exception const& e) {
668     THROWF(unknown_error, 0, "%s", e.what());
669   }
670 }
671
672 /** @brief Set or add a double value to \a name within \a cfg
673  *
674  * @param name the name of the variable
675  * @param val the double to set
676  */
677 void xbt_cfg_set_double(const char *name, double val)
678 {
679   try {
680     (*simgrid_config)[name].setValue<double>(val);
681   }
682   catch (std::exception const& e) {
683     THROWF(unknown_error, 0, "%s", e.what());
684   }
685 }
686
687 /** @brief Set or add a string value to \a name within \a cfg
688  *
689  * @param cfg the config set
690  * @param name the name of the variable
691  * @param val the value to be added
692  *
693  */
694 void xbt_cfg_set_string(const char *name, const char *val)
695 {
696   try {
697     (*simgrid_config)[name].setValue<std::string>(val ? val : "");
698   }
699   catch (std::exception const& e) {
700     THROWF(unknown_error, 0, "%s", e.what());
701   }
702 }
703
704 /** @brief Set or add a boolean value to \a name within \a cfg
705  *
706  * @param name the name of the variable
707  * @param val the value of the variable
708  */
709 void xbt_cfg_set_boolean(const char *name, const char *val)
710 {
711   try {
712     (*simgrid_config)[name].setValue<bool>(simgrid::config::parseBool(val));
713   }
714   catch (std::exception const& e) {
715     THROWF(unknown_error, 0, "%s", e.what());
716   }
717 }
718
719
720 /* Say if the value is the default value */
721 int xbt_cfg_is_default_value(const char *name)
722 {
723   try {
724     return (*simgrid_config)[name].isDefault() ? 1 : 0;
725   }
726   catch (std::exception const& e) {
727     THROWF(unknown_error, 0, "%s", e.what());
728   }
729 }
730
731 /*----[ Getting ]---------------------------------------------------------*/
732 /** @brief Retrieve an integer value of a variable (get a warning if not uniq)
733  *
734  * @param name the name of the variable
735  *
736  * Returns the first value from the config set under the given name.
737  */
738 int xbt_cfg_get_int(const char *name)
739 {
740   try {
741     return (*simgrid_config)[name].getValue<int>();
742   }
743   catch (std::exception const& e) {
744     THROWF(unknown_error, 0, "%s", e.what());
745   }
746 }
747
748 /** @brief Retrieve a double value of a variable (get a warning if not uniq)
749  *
750  * @param cfg the config set
751  * @param name the name of the variable
752  *
753  * Returns the first value from the config set under the given name.
754  */
755 double xbt_cfg_get_double(const char *name)
756 {
757   try {
758     return (*simgrid_config)[name].getValue<double>();
759   }
760   catch (std::exception const& e) {
761     THROWF(unknown_error, 0, "%s", e.what());
762   }
763 }
764
765 /** @brief Retrieve a string value of a variable (get a warning if not uniq)
766  *
767  * @param cfg the config set
768  * @param name the name of the variable
769  *
770  * Returns the first value from the config set under the given name.
771  * If there is more than one value, it will issue a warning.
772  * Returns NULL if there is no value.
773  *
774  * \warning the returned value is the actual content of the config set
775  */
776 char *xbt_cfg_get_string(const char *name)
777 {
778   try {
779     return (char*) (*simgrid_config)[name].getValue<std::string>().c_str();
780   }
781   catch (std::exception const& e) {
782     THROWF(unknown_error, 0, "%s", e.what());
783   }
784 }
785
786 /** @brief Retrieve a boolean value of a variable (get a warning if not uniq)
787  *
788  * @param cfg the config set
789  * @param name the name of the variable
790  *
791  * Returns the first value from the config set under the given name.
792  * If there is more than one value, it will issue a warning.
793  */
794 int xbt_cfg_get_boolean(const char *name)
795 {
796   try {
797     return (*simgrid_config)[name].getValue<bool>() ? 1 : 0;
798   }
799   catch (std::exception const& e) {
800     THROWF(unknown_error, 0, "%s", e.what());
801   }
802 }
803
804 #ifdef SIMGRID_TEST
805
806 #include <string>
807
808 #include "xbt.h"
809 #include "xbt/ex.h"
810
811 #include <xbt/config.hpp>
812
813 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(xbt_cfg);
814
815 XBT_TEST_SUITE("config", "Configuration support");
816
817 XBT_PUBLIC_DATA(xbt_cfg_t) simgrid_config;
818
819 static void make_set()
820 {
821   simgrid_config = NULL;
822   xbt_log_threshold_set(&_XBT_LOGV(xbt_cfg), xbt_log_priority_critical);
823   xbt_cfg_register_int("speed", 0, NULL, "");
824   xbt_cfg_register_string("peername", "", NULL, "");
825   xbt_cfg_register_string("user", "", NULL, "");
826 }                               /* end_of_make_set */
827
828 XBT_TEST_UNIT("memuse", test_config_memuse, "Alloc and free a config set")
829 {
830   auto temp = simgrid_config;
831   make_set();
832   xbt_test_add("Alloc and free a config set");
833   xbt_cfg_set_parse("peername:veloce user:bidule");
834   xbt_cfg_free(&simgrid_config);
835   simgrid_config = temp;
836 }
837
838 XBT_TEST_UNIT("use", test_config_use, "Data retrieving tests")
839 {
840   auto temp = simgrid_config;
841   make_set();
842   xbt_test_add("Get a single value");
843   {
844     /* get_single_value */
845     int ival;
846
847     xbt_cfg_set_parse("peername:toto:42 speed:42");
848     ival = xbt_cfg_get_int("speed");
849     if (ival != 42)
850       xbt_test_fail("Speed value = %d, I expected 42", ival);
851   }
852
853   xbt_test_add("Access to a non-existant entry");
854   {
855     xbt_ex_t e;
856
857     TRY {
858       xbt_cfg_set_parse("color:blue");
859     } CATCH(e) {
860       if (e.category != not_found_error)
861         xbt_test_exception(e);
862       xbt_ex_free(e);
863     }
864   }
865   xbt_cfg_free(&simgrid_config);
866   simgrid_config = temp;
867 }
868
869 XBT_TEST_UNIT("c++flags", test_config_cxx_flags, "C++ flags")
870 {
871   auto temp = simgrid_config;
872   make_set();
873   xbt_test_add("C++ declaration of flags");
874
875   simgrid::config::Flag<int> int_flag("int", "", 0);
876   simgrid::config::Flag<std::string> string_flag("string", "", "foo");
877   simgrid::config::Flag<double> double_flag("double", "", 0.32);
878   simgrid::config::Flag<bool> bool_flag1("bool1", "", false);
879   simgrid::config::Flag<bool> bool_flag2("bool2", "", true);
880
881   xbt_test_add("Parse values");
882   xbt_cfg_set_parse("int:42 string:bar double:8.0 bool1:true bool2:false");
883   xbt_test_assert(int_flag == 42, "Check int flag");
884   xbt_test_assert(string_flag == "bar", "Check string flag");
885   xbt_test_assert(double_flag == 8.0, "Check double flag");
886   xbt_test_assert(bool_flag1, "Check bool1 flag");
887   xbt_test_assert(!bool_flag2, "Check bool2 flag");
888
889   xbt_cfg_free(&simgrid_config);
890   simgrid_config = temp;
891 }
892
893 #endif                          /* SIMGRID_TEST */