Logo AND Algorithmique Numérique Distribuée

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