From 2d0b8560cee8a43297915883eda39749274654d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A1n=20Tomko?= Date: Fri, 18 Oct 2019 23:15:38 +0200 Subject: [PATCH] docs: hacking: document string concatenations MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Recommend GString for generic strings and virBuffer for strings that need helpers for other uses, like XML or command line formatting. Signed-off-by: Ján Tomko Reviewed-by: Daniel P. Berrangé Reviewed-by: Andrea Bolognani --- docs/hacking.html.in | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/docs/hacking.html.in b/docs/hacking.html.in index 60dc2f18e3..01c735120a 100644 --- a/docs/hacking.html.in +++ b/docs/hacking.html.in @@ -1290,7 +1290,11 @@ BAD:

If there is a need for complex string concatenations, avoid using the usual sequence of malloc/strcpy/strcat/snprintf functions and - make use of the virBuffer API described in virbuffer.h + make use of either the + GString + type from GLib or the virBuffer API. + If formatting XML or QEMU command line is needed, use the virBuffer + API described in virbuffer.h, since it has helper functions for those.

Typical usage is as follows:

@@ -1299,12 +1303,14 @@ BAD: char * somefunction(...) { - virBuffer buf = VIR_BUFFER_INITIALIZER; + g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER; ... virBufferAddLit(&buf, "<domain>\n"); virBufferAsprintf(&buf, " <memory>%d</memory>\n", memory); + if (some_error) + return NULL; /* g_auto will free the memory used so far */ ... virBufferAddLit(&buf, "</domain>\n"); @@ -1388,12 +1394,10 @@ BAD:

- When printing to a string, consider using virBuffer for - incremental allocations, virAsprintf for a one-shot allocation, - and snprintf for fixed-width buffers. Do not use sprintf, even - if you can prove the buffer won't overflow, since gnulib does - not provide the same portability guarantees for sprintf as it - does for snprintf. + When printing to a string, consider using GString or virBuffer for + incremental allocations, g_strdup_printf for a one-shot allocation, + and g_snprintf for fixed-width buffers. Only use g_sprintf, + if you can prove the buffer won't overflow.

Error message format