Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Objectify MSG task send
[simgrid.git] / src / xbt / string.cpp
1 /* Copyright (c) 2015-2019. 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   if (size < 0)
30     xbt_die("string_vprintf error");
31
32   // Allocate the string and format:
33   std::string res;
34   res.resize(size);
35   if (size != 0 && std::vsnprintf(&res[0], size + 1, fmt, ap) != size)
36     xbt_die("string_vprintf error");
37   return res;
38 }
39
40 std::string string_printf(const char *fmt, ...)
41 {
42   va_list ap;
43   va_start(ap, fmt);
44   std::string res;
45   try {
46     res = string_vprintf(fmt, ap);
47   }
48   catch(...) {
49     va_end(ap);
50     throw;
51   }
52   va_end(ap);
53   return res;
54 }
55
56 }
57 }