Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Update copyright lines for 2022.
[simgrid.git] / src / xbt / string.cpp
1 /* Copyright (c) 2015-2022. 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 <simgrid/config.h>
7 #include <xbt/string.hpp>
8 #include <xbt/sysdep.h>
9
10 #include <cstdarg>
11 #include <cstdio>
12
13 namespace simgrid {
14 namespace xbt {
15
16 #if SIMGRID_HAVE_MC
17
18 char string::NUL = '\0';
19
20 #endif
21
22 std::string string_vprintf(const char *fmt, va_list ap)
23 {
24   // Get the size:
25   va_list ap2;
26   va_copy(ap2, ap);
27   int size = std::vsnprintf(nullptr, 0, fmt, ap2);
28   va_end(ap2);
29   xbt_assert(size >= 0, "string_vprintf error");
30
31   // Allocate the string and format:
32   std::string res;
33   res.resize(size);
34   if (size != 0)
35     xbt_assert(std::vsnprintf(&res[0], size + 1, fmt, ap) == size, "string_vprintf error");
36   return res;
37 }
38
39 std::string string_printf(const char *fmt, ...)
40 {
41   va_list ap;
42   va_start(ap, fmt);
43   std::string res;
44   try {
45     res = string_vprintf(fmt, ap);
46   }
47   catch(...) {
48     va_end(ap);
49     throw;
50   }
51   va_end(ap);
52   return res;
53 }
54
55 }
56 }