util: buffer: Add API to set indentation level to a given value

It will be useful to set indentation level to 0 after formatting a
nested structure rather than having to track the depth.
This commit is contained in:
Peter Krempa 2017-03-09 17:02:19 +01:00
parent ff9ed72bf1
commit 91e7862c15
4 changed files with 51 additions and 0 deletions

View File

@ -1315,6 +1315,7 @@ virBufferEscapeShell;
virBufferEscapeString; virBufferEscapeString;
virBufferFreeAndReset; virBufferFreeAndReset;
virBufferGetIndent; virBufferGetIndent;
virBufferSetIndent;
virBufferStrcat; virBufferStrcat;
virBufferTrim; virBufferTrim;
virBufferURIEncodeString; virBufferURIEncodeString;

View File

@ -88,6 +88,25 @@ virBufferAdjustIndent(virBufferPtr buf, int indent)
buf->indent += indent; buf->indent += indent;
} }
/**
* virBufferSetIndent:
* @buf: the buffer
* @indent: new indentation size.
*
* Set the auto-indent value to @indent. See virBufferAdjustIndent on how auto
* indentation is applied.
*/
void
virBufferSetIndent(virBufferPtr buf, int indent)
{
if (!buf || buf->error)
return;
buf->indent = indent;
}
/** /**
* virBufferGetIndent: * virBufferGetIndent:
* @buf: the buffer * @buf: the buffer

View File

@ -95,6 +95,8 @@ void virBufferURIEncodeString(virBufferPtr buf, const char *str);
virBufferAdd(buf_, "" literal_string_ "", sizeof(literal_string_) - 1) virBufferAdd(buf_, "" literal_string_ "", sizeof(literal_string_) - 1)
void virBufferAdjustIndent(virBufferPtr buf, int indent); void virBufferAdjustIndent(virBufferPtr buf, int indent);
void virBufferSetIndent(virBufferPtr, int indent);
int virBufferGetIndent(const virBuffer *buf, bool dynamic); int virBufferGetIndent(const virBuffer *buf, bool dynamic);
void virBufferTrim(virBufferPtr buf, const char *trim, int len); void virBufferTrim(virBufferPtr buf, const char *trim, int len);

View File

@ -404,6 +404,34 @@ testBufEscapeN(const void *opaque)
} }
static int
testBufSetIndent(const void *opaque ATTRIBUTE_UNUSED)
{
virBuffer buf = VIR_BUFFER_INITIALIZER;
char *actual;
int ret = -1;
virBufferSetIndent(&buf, 11);
virBufferAddLit(&buf, "test\n");
virBufferSetIndent(&buf, 2);
virBufferAddLit(&buf, "test2\n");
if (!(actual = virBufferContentAndReset(&buf)))
goto cleanup;
if (STRNEQ(actual, " test\n test2\n")) {
VIR_TEST_DEBUG("testBufSetIndent: expected indent not set\n");
goto cleanup;
}
ret = 0;
cleanup:
VIR_FREE(actual);
return ret;
}
static int static int
mymain(void) mymain(void)
{ {
@ -422,6 +450,7 @@ mymain(void)
DO_TEST("Auto-indentation", testBufAutoIndent, 0); DO_TEST("Auto-indentation", testBufAutoIndent, 0);
DO_TEST("Trim", testBufTrim, 0); DO_TEST("Trim", testBufTrim, 0);
DO_TEST("AddBuffer", testBufAddBuffer, 0); DO_TEST("AddBuffer", testBufAddBuffer, 0);
DO_TEST("set indent", testBufSetIndent, 0);
#define DO_TEST_ADD_STR(DATA, EXPECT) \ #define DO_TEST_ADD_STR(DATA, EXPECT) \
do { \ do { \