Logo AND Algorithmique Numérique Distribuée

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