Logo AND Algorithmique Numérique Distribuée

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