Logo AND Algorithmique Numérique Distribuée

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