membuffer: add helper functions to return regular C strings

The whole "create a string using a printf-like interface" thing is
pretty common, and most users then don't necessarily want to deal with
the membuffer interfaces around it.

So this just creates trivial wrappers to do this, so that you can do

    s = format_string("%d: %s\n", i, str);

or similar things.

Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Dirk Hohndel <dirk@hohndel.org>
This commit is contained in:
Linus Torvalds 2015-01-24 12:47:26 +12:00 committed by Dirk Hohndel
parent 6397d56af4
commit 3521cdcbd6
2 changed files with 34 additions and 2 deletions

View file

@ -6,12 +6,18 @@
#include "dive.h"
#include "membuffer.h"
void free_buffer(struct membuffer *b)
char *detach_buffer(struct membuffer *b)
{
free(b->buffer);
char *result = b->buffer;
b->buffer = NULL;
b->len = 0;
b->alloc = 0;
return result;
}
void free_buffer(struct membuffer *b)
{
free(detach_buffer(b));
}
void flush_buffer(struct membuffer *b, FILE *f)
@ -100,6 +106,26 @@ void put_vformat(struct membuffer *b, const char *fmt, va_list args)
}
}
/* Silly helper using membuffer */
char *vformat_string(const char *fmt, va_list args)
{
struct membuffer mb = { 0 };
put_vformat(&mb, fmt, args);
mb_cstring(&mb);
return detach_buffer(&mb);
}
char *format_string(const char *fmt, ...)
{
va_list args;
char *result;
va_start(args, fmt);
result = vformat_string(fmt, args);
va_end(args);
return result;
}
void put_format(struct membuffer *b, const char *fmt, ...)
{
va_list args;

View file

@ -18,6 +18,7 @@ struct membuffer {
#define __printf(x, y)
#endif
extern char *detach_buffer(struct membuffer *b);
extern void free_buffer(struct membuffer *);
extern void flush_buffer(struct membuffer *, FILE *);
extern void put_bytes(struct membuffer *, const char *, int);
@ -30,6 +31,11 @@ extern __printf(2, 3) void put_format(struct membuffer *, const char *fmt, ...);
extern __printf(2, 0) char *add_to_string_va(const char *old, const char *fmt, va_list args);
extern __printf(2, 3) char *add_to_string(const char *old, const char *fmt, ...);
/* Helpers that use membuffers internally */
extern __printf(1, 0) char *vformat_string(const char *, va_list);
extern __printf(1, 2) char *format_string(const char *, ...);
/* Output one of our "milli" values with type and pre/post data */
extern void put_milli(struct membuffer *, const char *, int, const char *);