Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
cosmetics
[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   try {
309     return options.at(name);
310   } catch (std::out_of_range& unfound) {
311     try {
312       ConfigurationElement* res = aliases.at(name);
313       if (warn_for_aliases)
314         XBT_INFO("Option %s has been renamed to %s. Consider switching.", name, res->getKey().c_str());
315       return res;
316     } catch (std::out_of_range& missing_key) {
317       throw simgrid::config::missing_key_error(std::string("Bad config key: ") + name);
318     }
319   }
320 }
321
322 inline ConfigurationElement& Config::operator[](const char* name)
323 {
324   return *(getDictElement(name));
325 }
326
327 void Config::alias(const char* realname, const char* aliasname)
328 {
329   xbt_assert(aliases.find(aliasname) == aliases.end(), "Alias '%s' already.", aliasname);
330   ConfigurationElement* element = this->getDictElement(realname);
331   xbt_assert(element, "Cannot define an alias to the non-existing option '%s'.", realname);
332   this->aliases.insert({aliasname, element});
333 }
334
335 /** @brief Dump a config set for debuging purpose
336  *
337  * @param name The name to give to this config set
338  * @param indent what to write at the beginning of each line (right number of spaces)
339  */
340 void Config::dump(const char *name, const char *indent)
341 {
342   if (name)
343     printf("%s>> Dumping of the config set '%s':\n", indent, name);
344
345   for (auto elm : options)
346     printf("%s  %s: ()%s) %s", indent, elm.first.c_str(), elm.second->getTypeName(),
347            elm.second->getStringValue().c_str());
348
349   if (name)
350     printf("%s<< End of the config set '%s'\n", indent, name);
351   fflush(stdout);
352 }
353
354 /** @brief Displays the declared aliases and their description */
355 void Config::showAliases()
356 {
357   bool old_warn_for_aliases = false;
358   std::swap(warn_for_aliases, old_warn_for_aliases);
359   for (auto elm : aliases)
360     printf("   %s: %s\n", elm.first.c_str(), (*this)[elm.first.c_str()].getDescription().c_str());
361   std::swap(warn_for_aliases, old_warn_for_aliases);
362 }
363
364 /** @brief Displays the declared options and their description */
365 void Config::help()
366 {
367   for (auto elm : options) {
368     simgrid::config::ConfigurationElement* variable = this->options.at(elm.first);
369     printf("   %s: %s\n", elm.first.c_str(), variable->getDescription().c_str());
370     printf("       Type: %s; ", variable->getTypeName());
371     printf("Current value: %s\n", variable->getStringValue().c_str());
372   }
373 }
374
375 // ***** getConfig *****
376
377 template<class T>
378 XBT_PUBLIC(T const&) getConfig(const char* name)
379 {
380   return (*simgrid_config)[name].getValue<T>();
381 }
382
383 template XBT_PUBLIC(int const&) getConfig<int>(const char* name);
384 template XBT_PUBLIC(double const&) getConfig<double>(const char* name);
385 template XBT_PUBLIC(bool const&) getConfig<bool>(const char* name);
386 template XBT_PUBLIC(std::string const&) getConfig<std::string>(const char* name);
387
388 // ***** alias *****
389
390 void alias(const char* realname, const char* aliasname)
391 {
392   simgrid_config->alias(realname, aliasname);
393 }
394
395 // ***** declareFlag *****
396
397 template<class T>
398 XBT_PUBLIC(void) declareFlag(const char* name, const char* description,
399   T value, std::function<void(const T&)> callback)
400 {
401   if (simgrid_config == nullptr) {
402     simgrid_config = xbt_cfg_new();
403     atexit(sg_config_finalize);
404   }
405   simgrid_config->registerOption<T>(
406     name, description, std::move(value), std::move(callback));
407 }
408
409 template XBT_PUBLIC(void) declareFlag(const char* name,
410   const char* description, int value, std::function<void(int const &)> callback);
411 template XBT_PUBLIC(void) declareFlag(const char* name,
412   const char* description, double value, std::function<void(double const &)> callback);
413 template XBT_PUBLIC(void) declareFlag(const char* name,
414   const char* description, bool value, std::function<void(bool const &)> callback);
415 template XBT_PUBLIC(void) declareFlag(const char* name,
416   const char* description, std::string value, std::function<void(std::string const &)> callback);
417
418 }
419 }
420
421 // ***** C bindings *****
422
423 xbt_cfg_t xbt_cfg_new()        { return new simgrid::config::Config(); }
424 void xbt_cfg_free(xbt_cfg_t * cfg) { delete *cfg; }
425
426 void xbt_cfg_dump(const char *name, const char *indent, xbt_cfg_t cfg)
427 {
428   cfg->dump(name, indent);
429 }
430
431 /*----[ Registering stuff ]-----------------------------------------------*/
432
433 void xbt_cfg_register_double(const char *name, double default_value,
434   xbt_cfg_cb_t cb_set, const char *desc)
435 {
436   if (simgrid_config == nullptr)
437     simgrid_config = xbt_cfg_new();
438   simgrid_config->registerOption<double>(name, desc, default_value, cb_set);
439 }
440
441 void xbt_cfg_register_int(const char *name, int default_value,xbt_cfg_cb_t cb_set, const char *desc)
442 {
443   if (simgrid_config == nullptr) {
444     simgrid_config = xbt_cfg_new();
445     atexit(&sg_config_finalize);
446   }
447   simgrid_config->registerOption<int>(name, desc, default_value, cb_set);
448 }
449
450 void xbt_cfg_register_string(const char *name, const char *default_value, xbt_cfg_cb_t cb_set, const char *desc)
451 {
452   if (simgrid_config == nullptr) {
453     simgrid_config = xbt_cfg_new();
454     atexit(sg_config_finalize);
455   }
456   simgrid_config->registerOption<std::string>(name, desc,
457     default_value ? default_value : "", cb_set);
458 }
459
460 void xbt_cfg_register_boolean(const char *name, const char*default_value,xbt_cfg_cb_t cb_set, const char *desc)
461 {
462   if (simgrid_config == nullptr) {
463     simgrid_config = xbt_cfg_new();
464     atexit(sg_config_finalize);
465   }
466   simgrid_config->registerOption<bool>(name, desc, simgrid::config::parseBool(default_value), cb_set);
467 }
468
469 void xbt_cfg_register_alias(const char *realname, const char *aliasname)
470 {
471   if (simgrid_config == nullptr) {
472     simgrid_config = xbt_cfg_new();
473     atexit(sg_config_finalize);
474   }
475   simgrid_config->alias(realname, aliasname);
476 }
477
478 void xbt_cfg_aliases() { simgrid_config->showAliases(); }
479 void xbt_cfg_help()    { simgrid_config->help(); }
480
481 /*----[ Setting ]---------------------------------------------------------*/
482
483 /** @brief Add values parsed from a string into a config set
484  *
485  * @param options a string containing the content to add to the config set. This is a '\\t',' ' or '\\n' or ','
486  * separated list of variables. Each individual variable is like "[name]:[value]" where [name] is the name of an
487  * already registered variable, and [value] conforms to the data type under which this variable was registered.
488  *
489  * @todo This is a crude manual parser, it should be a proper lexer.
490  */
491 void xbt_cfg_set_parse(const char *options)
492 {
493   if (not options || not strlen(options)) { /* nothing to do */
494     return;
495   }
496   char *optionlist_cpy = xbt_strdup(options);
497
498   XBT_DEBUG("List to parse and set:'%s'", options);
499   char *option = optionlist_cpy;
500   while (1) {                   /* breaks in the code */
501     if (not option)
502       break;
503     char *name = option;
504     int len = strlen(name);
505     XBT_DEBUG("Still to parse and set: '%s'. len=%d; option-name=%ld", name, len, (long) (option - name));
506
507     /* Pass the value */
508     while (option - name <= (len - 1) && *option != ' ' && *option != '\n' && *option != '\t' && *option != ',') {
509       XBT_DEBUG("Take %c.", *option);
510       option++;
511     }
512     if (option - name == len) {
513       XBT_DEBUG("Boundary=EOL");
514       option = nullptr;            /* don't do next iteration */
515     } else {
516       XBT_DEBUG("Boundary on '%c'. len=%d;option-name=%ld", *option, len, (long) (option - name));
517       /* Pass the following blank chars */
518       *(option++) = '\0';
519       while (option - name < (len - 1) && (*option == ' ' || *option == '\n' || *option == '\t')) {
520         /*      fprintf(stderr,"Ignore a blank char.\n"); */
521         option++;
522       }
523       if (option - name == len - 1)
524         option = nullptr;          /* don't do next iteration */
525     }
526     XBT_DEBUG("parse now:'%s'; parse later:'%s'", name, option);
527
528     if (name[0] == ' ' || name[0] == '\n' || name[0] == '\t')
529       continue;
530     if (not strlen(name))
531       break;
532
533     char *val = strchr(name, ':');
534     xbt_assert(val, "Option '%s' badly formatted. Should be of the form 'name:value'", name);
535     /* don't free(optionlist_cpy) if the assert fails, 'name' points inside it */
536     *(val++) = '\0';
537
538     if (strncmp(name, "path", strlen("path")))
539       XBT_INFO("Configuration change: Set '%s' to '%s'", name, val);
540
541     try {
542       (*simgrid_config)[name].setStringValue(val);
543     }
544     catch (simgrid::config::missing_key_error& e) {
545       goto on_missing_key;
546     }
547     catch (...) {
548       goto on_exception;
549     }
550   }
551
552   free(optionlist_cpy);
553   return;
554
555   /* Do not THROWF from a C++ exception catching context, or some cleanups will be missing */
556 on_missing_key:
557   free(optionlist_cpy);
558   THROWF(not_found_error, 0, "Could not set variables %s", options);
559   return;
560 on_exception:
561   free(optionlist_cpy);
562   THROWF(unknown_error, 0, "Could not set variables %s", options);
563 }
564
565 // Horrible mess to translate C++ exceptions to C exceptions:
566 // Exit from the catch block (and do the correct exception cleaning) before attempting to THROWF.
567 #define TRANSLATE_EXCEPTIONS(...) \
568   catch(simgrid::config::missing_key_error& e) { THROWF(not_found_error, 0, __VA_ARGS__); abort(); } \
569   catch(...) { THROWF(not_found_error, 0, __VA_ARGS__); abort(); }
570
571 /** @brief Set the value of a variable, using the string representation of that value
572  *
573  * @param key name of the variable to modify
574  * @param value string representation of the value to set
575  */
576
577 void xbt_cfg_set_as_string(const char *key, const char *value)
578 {
579   try {
580     (*simgrid_config)[key].setStringValue(value);
581     return;
582   }
583   TRANSLATE_EXCEPTIONS("Could not set variable %s as string %s", key, value);
584 }
585
586 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
587  *
588  * This is useful to change the default value of a variable while allowing
589  * users to override it with command line arguments
590  */
591 void xbt_cfg_setdefault_int(const char *key, int value)
592 {
593   try {
594     (*simgrid_config)[key].setDefaultValue<int>(value);
595     return;
596   }
597   TRANSLATE_EXCEPTIONS("Could not set variable %s to default integer %i", key, value);
598 }
599
600 /** @brief Set an integer value to \a name within \a cfg if it wasn't changed yet
601  *
602  * This is useful to change the default value of a variable while allowing
603  * users to override it with command line arguments
604  */
605 void xbt_cfg_setdefault_double(const char *key, double value)
606 {
607   try {
608     (*simgrid_config)[key].setDefaultValue<double>(value);
609     return;
610   }
611   TRANSLATE_EXCEPTIONS("Could not set variable %s to default double %f", key, value);
612 }
613
614 /** @brief Set a string value to \a name within \a cfg if it wasn't changed yet
615  *
616  * This is useful to change the default value of a variable while allowing
617  * users to override it with command line arguments
618  */
619 void xbt_cfg_setdefault_string(const char *key, const char *value)
620 {
621   try {
622     (*simgrid_config)[key].setDefaultValue<std::string>(value ? value : "");
623     return;
624   }
625   TRANSLATE_EXCEPTIONS("Could not set variable %s to default string %s", key, value);
626 }
627
628 /** @brief Set an boolean value to \a name within \a cfg if it wasn't changed yet
629  *
630  * This is useful to change the default value of a variable while allowing
631  * users to override it with command line arguments
632  */
633 void xbt_cfg_setdefault_boolean(const char *key, const char *value)
634 {
635   try {
636     (*simgrid_config)[key].setDefaultValue<bool>(simgrid::config::parseBool(value));
637     return;
638   }
639   TRANSLATE_EXCEPTIONS("Could not set variable %s to default boolean %s", key, value);
640 }
641
642 /** @brief Set an integer value to \a name within \a cfg
643  *
644  * @param key the name of the variable
645  * @param value the value of the variable
646  */
647 void xbt_cfg_set_int(const char *key, int value)
648 {
649   try {
650     (*simgrid_config)[key].setValue<int>(value);
651     return;
652   }
653   TRANSLATE_EXCEPTIONS("Could not set variable %s to integer %i", key, value);
654 }
655
656 /** @brief Set or add a double value to \a name within \a cfg
657  *
658  * @param key the name of the variable
659  * @param value the double to set
660  */
661 void xbt_cfg_set_double(const char *key, double value)
662 {
663   try {
664     (*simgrid_config)[key].setValue<double>(value);
665     return;
666   }
667   TRANSLATE_EXCEPTIONS("Could not set variable %s to double %f", key, value);
668 }
669
670 /** @brief Set or add a string value to \a name within \a cfg
671  *
672  * @param key the name of the variable
673  * @param value the value to be added
674  *
675  */
676 void xbt_cfg_set_string(const char *key, const char *value)
677 {
678   try {
679     (*simgrid_config)[key].setValue<std::string>(value ? value : "");
680     return;
681   }
682   TRANSLATE_EXCEPTIONS("Could not set variable %s to string %s", key, value);
683 }
684
685 /** @brief Set or add a boolean value to \a name within \a cfg
686  *
687  * @param key the name of the variable
688  * @param value the value of the variable
689  */
690 void xbt_cfg_set_boolean(const char *key, const char *value)
691 {
692   try {
693     (*simgrid_config)[key].setValue<bool>(simgrid::config::parseBool(value));
694     return;
695   }
696   TRANSLATE_EXCEPTIONS("Could not set variable %s to boolean %s", key, value);
697 }
698
699
700 /* Say if the value is the default value */
701 int xbt_cfg_is_default_value(const char *key)
702 {
703   try {
704     return (*simgrid_config)[key].isDefault() ? 1 : 0;
705   }
706   TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
707 }
708
709 /*----[ Getting ]---------------------------------------------------------*/
710 /** @brief Retrieve an integer value of a variable (get a warning if not uniq)
711  *
712  * @param key the name of the variable
713  *
714  * Returns the first value from the config set under the given name.
715  */
716 int xbt_cfg_get_int(const char *key)
717 {
718   try {
719     return (*simgrid_config)[key].getValue<int>();
720   }
721   TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
722 }
723
724 /** @brief Retrieve a double value of a variable (get a warning if not uniq)
725  *
726  * @param key the name of the variable
727  *
728  * Returns the first value from the config set under the given name.
729  */
730 double xbt_cfg_get_double(const char *key)
731 {
732   try {
733     return (*simgrid_config)[key].getValue<double>();
734   }
735   TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
736 }
737
738 /** @brief Retrieve a string value of a variable (get a warning if not uniq)
739  *
740  * @param key the name of the variable
741  *
742  * Returns the first value from the config set under the given name.
743  * If there is more than one value, it will issue a warning.
744  * Returns nullptr if there is no value.
745  *
746  * \warning the returned value is the actual content of the config set
747  */
748 char *xbt_cfg_get_string(const char *key)
749 {
750   try {
751     return (char*) (*simgrid_config)[key].getValue<std::string>().c_str();
752   }
753   TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
754 }
755
756 /** @brief Retrieve a boolean value of a variable (get a warning if not uniq)
757  *
758  * @param key the name of the variable
759  *
760  * Returns the first value from the config set under the given name.
761  * If there is more than one value, it will issue a warning.
762  */
763 int xbt_cfg_get_boolean(const char *key)
764 {
765   try {
766     return (*simgrid_config)[key].getValue<bool>() ? 1 : 0;
767   }
768   TRANSLATE_EXCEPTIONS("Could not get variable %s", key);
769 }
770
771 #ifdef SIMGRID_TEST
772
773 #include <string>
774
775 #include "xbt.h"
776 #include "xbt/ex.h"
777 #include <xbt/ex.hpp>
778
779 #include <xbt/config.hpp>
780
781 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(xbt_cfg);
782
783 XBT_TEST_SUITE("config", "Configuration support");
784
785 XBT_PUBLIC_DATA(xbt_cfg_t) simgrid_config;
786
787 static void make_set()
788 {
789   simgrid_config = nullptr;
790   xbt_log_threshold_set(&_XBT_LOGV(xbt_cfg), xbt_log_priority_critical);
791   xbt_cfg_register_int("speed", 0, nullptr, "");
792   xbt_cfg_register_string("peername", "", nullptr, "");
793   xbt_cfg_register_string("user", "", nullptr, "");
794 }                               /* end_of_make_set */
795
796 XBT_TEST_UNIT("memuse", test_config_memuse, "Alloc and free a config set")
797 {
798   auto temp = simgrid_config;
799   make_set();
800   xbt_test_add("Alloc and free a config set");
801   xbt_cfg_set_parse("peername:veloce user:bidule");
802   xbt_cfg_free(&simgrid_config);
803   simgrid_config = temp;
804 }
805
806 XBT_TEST_UNIT("use", test_config_use, "Data retrieving tests")
807 {
808   auto temp = simgrid_config;
809   make_set();
810   xbt_test_add("Get a single value");
811   {
812     /* get_single_value */
813     xbt_cfg_set_parse("peername:toto:42 speed:42");
814     int ival = xbt_cfg_get_int("speed");
815     if (ival != 42)
816       xbt_test_fail("Speed value = %d, I expected 42", ival);
817   }
818
819   xbt_test_add("Access to a non-existant entry");
820   {
821     try {
822       xbt_cfg_set_parse("color:blue");
823     } catch(xbt_ex& e) {
824       if (e.category != not_found_error)
825         xbt_test_exception(e);
826     }
827   }
828   xbt_cfg_free(&simgrid_config);
829   simgrid_config = temp;
830 }
831
832 XBT_TEST_UNIT("c++flags", test_config_cxx_flags, "C++ flags")
833 {
834   auto temp = simgrid_config;
835   make_set();
836   xbt_test_add("C++ declaration of flags");
837
838   simgrid::config::Flag<int> int_flag("int", "", 0);
839   simgrid::config::Flag<std::string> string_flag("string", "", "foo");
840   simgrid::config::Flag<double> double_flag("double", "", 0.32);
841   simgrid::config::Flag<bool> bool_flag1("bool1", "", false);
842   simgrid::config::Flag<bool> bool_flag2("bool2", "", true);
843
844   xbt_test_add("Parse values");
845   xbt_cfg_set_parse("int:42 string:bar double:8.0 bool1:true bool2:false");
846   xbt_test_assert(int_flag == 42, "Check int flag");
847   xbt_test_assert(string_flag == "bar", "Check string flag");
848   xbt_test_assert(double_flag == 8.0, "Check double flag");
849   xbt_test_assert(bool_flag1, "Check bool1 flag");
850   xbt_test_assert(not bool_flag2, "Check bool2 flag");
851
852   xbt_cfg_free(&simgrid_config);
853   simgrid_config = temp;
854 }
855
856 #endif                          /* SIMGRID_TEST */