virStrndup: Accept negative values as string length

It may shorten the code a bit as the following pattern:

  VIR_STRNDUP(dst, src, cond ? n : strlen(src))

is used on several places among our code. However, we can
move the strlen into virStrndup and thus write just:

  VIR_STRNDUP(dst, src, cond ? n : -1)
This commit is contained in:
Michal Privoznik
2013-05-24 10:45:57 +02:00
parent 267915ee69
commit c93571968b
3 changed files with 51 additions and 4 deletions

View File

@@ -196,6 +196,40 @@ cleanup:
return ret;
}
static int
testStrndupNegative(const void *opaque ATTRIBUTE_UNUSED)
{
int ret = -1;
char *dst;
const char *src = "Hello world";
int value;
if ((value = VIR_STRNDUP(dst, src, 5)) != 1) {
fprintf(stderr, "unexpected virStrndup result %d, expected 1\n", value);
goto cleanup;
}
if (STRNEQ_NULLABLE(dst, "Hello")) {
fprintf(stderr, "unexpected content '%s'", dst);
goto cleanup;
}
VIR_FREE(dst);
if ((value = VIR_STRNDUP(dst, src, -1)) != 1) {
fprintf(stderr, "unexpected virStrndup result %d, expected 1\n", value);
goto cleanup;
}
if (STRNEQ_NULLABLE(dst, src)) {
fprintf(stderr, "unexpected content '%s'", dst);
goto cleanup;
}
ret = 0;
cleanup:
VIR_FREE(dst);
return ret;
}
static int
mymain(void)
@@ -245,6 +279,9 @@ mymain(void)
if (virtTestRun("strdup", 1, testStrdup, NULL) < 0)
ret = -1;
if (virtTestRun("strdup", 1, testStrndupNegative, NULL) < 0)
ret = -1;
return ret==0 ? EXIT_SUCCESS : EXIT_FAILURE;
}