Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Use std::fill instead of memset.
[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::xbt {
14
15 #if SIMGRID_HAVE_MC
16
17 char string::NUL = '\0';
18
19 #endif
20
21 std::string string_vprintf(const char *fmt, va_list ap)
22 {
23   // Get the size:
24   va_list ap2;
25   va_copy(ap2, ap);
26   int size = std::vsnprintf(nullptr, 0, fmt, ap2);
27   va_end(ap2);
28   xbt_assert(size >= 0, "string_vprintf error");
29
30   // Allocate the string and format:
31   std::string res;
32   res.resize(size);
33   if (size != 0)
34     xbt_assert(std::vsnprintf(&res[0], size + 1, fmt, ap) == size, "string_vprintf error");
35   return res;
36 }
37
38 std::string string_printf(const char *fmt, ...)
39 {
40   va_list ap;
41   va_start(ap, fmt);
42   std::string res;
43   try {
44     res = string_vprintf(fmt, ap);
45   }
46   catch(...) {
47     va_end(ap);
48     throw;
49   }
50   va_end(ap);
51   return res;
52 }
53
54 } // namespace simgrid::xbt