Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
[mc] Use std::string in simgrid::mc::request_to_string
[simgrid.git] / src / xbt / string.cpp
1 /* Copyright (c) 2015. The SimGrid Team.
2  * All rights reserved.                                                     */
3
4 /* This program is free software; you can redistribute it and/or modify it
5  * under the terms of the license (GNU LGPL) which comes with this package. */
6
7 #include <cstdarg>
8 #include <cstdio>
9
10 #include <simgrid_config.h>
11
12 #include <xbt/string.hpp>
13 #include <xbt/sysdep.h>
14
15 namespace simgrid {
16 namespace xbt {
17
18 #if HAVE_MC
19
20 const char string::NUL = '\0';
21
22 #endif
23
24 std::string string_vprintf(const char *fmt, va_list ap)
25 {
26   // Get the size:
27   va_list ap2;
28   va_copy(ap2, ap);
29   int size = std::vsnprintf(nullptr, 0, fmt, ap2);
30   va_end(ap2);
31   if (size < 0)
32     xbt_die("string_vprintf error");
33
34   // Allocate the string and format:
35   std::string res;
36   res.resize(size);
37   if (size != 0 && std::vsnprintf(&res[0], size + 1, fmt, ap) != size)
38     xbt_die("string_vprintf error");
39   return res;
40 }
41
42 std::string string_printf(const char *fmt, ...)
43 {
44   va_list ap;
45   va_start(ap, fmt);
46   std::string res;
47   try {
48     res = string_vprintf(fmt, ap);
49   }
50   catch(...) {
51     va_end(ap);
52     throw;
53   }
54   va_end(ap);
55   return res;
56 }
57
58 }
59 }