diff options
author | Pedro Alves <palves@redhat.com> | 2016-11-08 15:26:42 +0000 |
---|---|---|
committer | Pedro Alves <palves@redhat.com> | 2016-11-08 15:26:42 +0000 |
commit | d4081a383e28db26c65298f7405554d4312b1342 (patch) | |
tree | 6a44bd0e08354fd50608dfe5240d28ec7e567e55 /gdb/common | |
parent | cb64e50d42a49bce61050c79c5ab0846905b6a82 (diff) | |
download | gdb-d4081a383e28db26c65298f7405554d4312b1342.zip gdb-d4081a383e28db26c65298f7405554d4312b1342.tar.gz gdb-d4081a383e28db26c65298f7405554d4312b1342.tar.bz2 |
Introduce string_printf
This introduces the string_printf function. Like asprintf, but
returns a std::string.
gdb/ChangeLog:
2016-11-08 Pedro Alves <palves@redhat.com>
* Makefile.in (COMMON_OBS): Add utils-selftests.o.
* common/common-utils.c (string_printf): New function.
* common/common-utils.h: Include <string>.
(string_printf): Declare.
* utils-selftests.c: New file.
Diffstat (limited to 'gdb/common')
-rw-r--r-- | gdb/common/common-utils.c | 23 | ||||
-rw-r--r-- | gdb/common/common-utils.h | 6 |
2 files changed, 29 insertions, 0 deletions
diff --git a/gdb/common/common-utils.c b/gdb/common/common-utils.c index 5a346ec..e112b62 100644 --- a/gdb/common/common-utils.c +++ b/gdb/common/common-utils.c @@ -150,6 +150,29 @@ xsnprintf (char *str, size_t size, const char *format, ...) return ret; } +/* See documentation in common-utils.h. */ + +std::string +string_printf (const char* fmt, ...) +{ + va_list vp; + int size; + + va_start (vp, fmt); + 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'. */ + va_start (vp, fmt); + vsprintf (&str[0], fmt, vp); + va_end (vp); + + 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 47def11..a9053ff 100644 --- a/gdb/common/common-utils.h +++ b/gdb/common/common-utils.h @@ -20,6 +20,8 @@ #ifndef COMMON_UTILS_H #define COMMON_UTILS_H +#include <string> + /* If possible, define FUNCTION_NAME, a macro containing the name of the function being defined. Since this macro may not always be defined, all uses must be protected by appropriate macro definition @@ -56,6 +58,10 @@ char *xstrvprintf (const char *format, va_list ap) int xsnprintf (char *str, size_t size, const char *format, ...) ATTRIBUTE_PRINTF (3, 4); +/* Returns a std::string built from a printf-style format string. */ +std::string string_printf (const char* fmt, ...) + ATTRIBUTE_PRINTF (1, 2); + /* 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. */ |