Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Add new entry in Release_Notes.
[simgrid.git] / src / xbt / string.cpp
1 /* Copyright (c) 2015-2023. 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 <xbt/string.hpp>
7 #include <xbt/sysdep.h>
8
9 namespace simgrid::xbt {
10
11 std::string string_vprintf(const char *fmt, va_list ap)
12 {
13   // Get the size:
14   va_list ap2;
15   va_copy(ap2, ap);
16   int size = std::vsnprintf(nullptr, 0, fmt, ap2);
17   va_end(ap2);
18   xbt_assert(size >= 0, "string_vprintf error");
19
20   // Allocate the string and format:
21   std::string res;
22   res.resize(size);
23   if (size != 0)
24     xbt_assert(std::vsnprintf(&res[0], size + 1, fmt, ap) == size, "string_vprintf error");
25   return res;
26 }
27
28 std::string string_printf(const char *fmt, ...)
29 {
30   va_list ap;
31   va_start(ap, fmt);
32   std::string res;
33   try {
34     res = string_vprintf(fmt, ap);
35   }
36   catch(...) {
37     va_end(ap);
38     throw;
39   }
40   va_end(ap);
41   return res;
42 }
43
44 } // namespace simgrid::xbt