tlx
ssprintf_generic.hpp
Go to the documentation of this file.
1 /*******************************************************************************
2  * tlx/string/ssprintf_generic.hpp
3  *
4  * Part of tlx - http://panthema.net/tlx
5  *
6  * Copyright (C) 2007-2019 Timo Bingmann <tb@panthema.net>
7  *
8  * All rights reserved. Published under the Boost Software License, Version 1.0
9  ******************************************************************************/
10 
11 #ifndef TLX_STRING_SSPRINTF_GENERIC_HEADER
12 #define TLX_STRING_SSPRINTF_GENERIC_HEADER
13 
15 
16 #include <cstdarg>
17 #include <cstdio>
18 #include <string>
19 
20 namespace tlx {
21 
22 //! \addtogroup tlx_string
23 //! \{
24 
25 /*!
26  * Helper for return the result of a sprintf() call inside a string object.
27  *
28  * \param fmt printf format and additional parameters
29  */
30 template <typename String = std::string>
31 String ssprintf_generic(const char* fmt, ...)
33 
34 template <typename String>
35 String ssprintf_generic(const char* fmt, ...) {
36  String out;
37  out.resize(128);
38 
39  va_list args;
40  va_start(args, fmt);
41 
42  int size = std::vsnprintf(
43  const_cast<char*>(out.data()), out.size() + 1, fmt, args);
44 
45  if (size >= static_cast<int>(out.size())) {
46  // error, grow buffer and try again.
47  out.resize(size);
48  size = std::vsnprintf(
49  const_cast<char*>(out.data()), out.size() + 1, fmt, args);
50  }
51 
52  out.resize(size);
53 
54  va_end(args);
55 
56  return out;
57 }
58 
59 /*!
60  * Helper for return the result of a snprintf() call inside a string object.
61  *
62  * \param max_size maximum length of output string, longer ones are truncated.
63  * \param fmt printf format and additional parameters
64  */
65 template <typename String = std::string>
66 String ssnprintf_generic(size_t max_size, const char* fmt, ...)
68 
69 template <typename String>
70 String ssnprintf_generic(size_t max_size, const char* fmt, ...) {
71  String out;
72  out.resize(max_size);
73 
74  va_list args;
75  va_start(args, fmt);
76 
77  int size = std::vsnprintf(
78  const_cast<char*>(out.data()), out.size() + 1, fmt, args);
79 
80  if (static_cast<size_t>(size) < max_size)
81  out.resize(static_cast<size_t>(size));
82 
83  va_end(args);
84 
85  return out;
86 }
87 
88 //! \}
89 
90 } // namespace tlx
91 
92 #endif // !TLX_STRING_SSPRINTF_GENERIC_HEADER
93 
94 /******************************************************************************/
String ssprintf_generic(const char *fmt,...) TLX_ATTRIBUTE_FORMAT_PRINTF(1
Helper for return the result of a sprintf() call inside a string object.
#define TLX_ATTRIBUTE_FORMAT_PRINTF(X, Y)
String ssnprintf_generic(size_t max_size, const char *fmt,...) TLX_ATTRIBUTE_FORMAT_PRINTF(2
Helper for return the result of a snprintf() call inside a string object.