Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Add new entry in Release_Notes.
[simgrid.git] / src / xbt / xbt_str.cpp
1 /* xbt_str.cpp - various helping functions to deal with strings             */
2
3 /* Copyright (c) 2007-2023. The SimGrid Team. All rights reserved.          */
4
5 /* This program is free software; you can redistribute it and/or modify it
6  * under the terms of the license (GNU LGPL) which comes with this package. */
7
8 #include "simgrid/Exception.hpp"
9 #include "xbt/misc.h"
10 #include "xbt/str.h" /* headers of these functions */
11 #include "xbt/string.hpp"
12
13 /** @brief Parse an integer out of a string, or raise an error
14  *
15  * The @a str is concatenated to your @a error_msg, as follows:
16  * @verbatim throw std::invalid_argument(simgrid::xbt::string_printf("%s: %s", error_msg, str)); @endverbatim
17  */
18 long int xbt_str_parse_int(const char* str, const char* error_msg)
19 {
20   char* endptr;
21   if (str == nullptr || str[0] == '\0')
22     throw std::invalid_argument(simgrid::xbt::string_printf("%s: %s", error_msg, str));
23
24   long int res = strtol(str, &endptr, 10);
25   if (endptr[0] != '\0')
26     throw std::invalid_argument(simgrid::xbt::string_printf("%s: %s", error_msg, str));
27
28   return res;
29 }
30
31 /** @brief Parse a double out of a string, or raise an error
32  *
33  * The @a str is concatenated to your @a error_msg, as follows:
34  * @verbatim throw std::invalid_argument(simgrid::xbt::string_printf("%s: %s", error_msg, str)); @endverbatim
35  */
36 double xbt_str_parse_double(const char* str, const char* error_msg)
37 {
38   char *endptr;
39   if (str == nullptr || str[0] == '\0')
40     throw std::invalid_argument(simgrid::xbt::string_printf("%s: %s", error_msg, str));
41
42   double res = strtod(str, &endptr);
43   if (endptr[0] != '\0')
44     throw std::invalid_argument(simgrid::xbt::string_printf("%s: %s (parse error at '%s')", error_msg, str, endptr));
45
46   return res;
47 }