[RFA,01/12] Introduce string_vprintf

Message ID 20170928195011.27382-2-tom@tromey.com
State New, archived
Headers

Commit Message

Tom Tromey Sept. 28, 2017, 7:50 p.m. UTC
  This adds string_vprintf, a va_list variant of string_printf.  This
will be used in later patches.

gdb/ChangeLog
2017-09-28  Tom Tromey  <tom@tromey.com>

	* common/common-utils.c (string_vprintf): New function.
	* common/common-utils.h (string_vprintf): Declare.
---
 gdb/ChangeLog             |  5 +++++
 gdb/common/common-utils.c | 21 +++++++++++++++++++++
 gdb/common/common-utils.h |  4 ++++
 3 files changed, 30 insertions(+)
  

Comments

Pedro Alves Sept. 28, 2017, 9:53 p.m. UTC | #1
On 09/28/2017 08:50 PM, Tom Tromey wrote:
> This adds string_vprintf, a va_list variant of string_printf.  This
> will be used in later patches.

Thanks.

This is OK, but IWBN to add some unittest to
gdb/unittests/utils-selftests.c.

Thanks,
Pedro Alves
  

Patch

diff --git a/gdb/common/common-utils.c b/gdb/common/common-utils.c
index 6b10d11..d8c546a 100644
--- a/gdb/common/common-utils.c
+++ b/gdb/common/common-utils.c
@@ -174,6 +174,27 @@  string_printf (const char* fmt, ...)
   return str;
 }
 
+/* See documentation in common-utils.h.  */
+
+std::string
+string_vprintf (const char* fmt, va_list args)
+{
+  va_list vp;
+  size_t size;
+
+  va_copy (vp, args);
+  size = vsnprintf (NULL, 0, fmt, vp);
+  va_end (vp);
+
+  std::string str (size, '\0');
+
+  /* C++11 and later guarantee std::string uses contiguous memory and
+     always includes the terminating '\0'.  */
+  vsprintf (&str[0], fmt, args);
+
+  return str;
+}
+
 char *
 savestring (const char *ptr, size_t len)
 {
diff --git a/gdb/common/common-utils.h b/gdb/common/common-utils.h
index 6475c28..19724f9 100644
--- a/gdb/common/common-utils.h
+++ b/gdb/common/common-utils.h
@@ -63,6 +63,10 @@  int xsnprintf (char *str, size_t size, const char *format, ...)
 std::string string_printf (const char* fmt, ...)
   ATTRIBUTE_PRINTF (1, 2);
 
+/* Like string_printf, but takes a va_list.  */
+std::string string_vprintf (const char* fmt, va_list args)
+  ATTRIBUTE_PRINTF (1, 0);
+
 /* Make a copy of the string at PTR with LEN characters
    (and add a null character at the end in the copy).
    Uses malloc to get the space.  Returns the address of the copy.  */