Logo AND Algorithmique Numérique Distribuée

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