From a29229f862d5bea1fe09222f04bbda834c08d887 Mon Sep 17 00:00:00 2001 From: Sebastian Reimers Date: Wed, 11 Oct 2023 12:02:45 +0200 Subject: [PATCH] fmt/pl: add pl_alloc_str --- include/re_fmt.h | 1 + src/fmt/pl.c | 42 ++++++++++++++++++++++++++++++++++++++++++ test/fmt.c | 18 ++++++++++++++++++ test/test.c | 1 + test/test.h | 1 + 5 files changed, 63 insertions(+) diff --git a/include/re_fmt.h b/include/re_fmt.h index 13d0783ba..af4cd1841 100644 --- a/include/re_fmt.h +++ b/include/re_fmt.h @@ -29,6 +29,7 @@ struct pl { extern const struct pl pl_null; +struct pl *pl_alloc_str(const char *str); void pl_set_str(struct pl *pl, const char *str); void pl_set_mbuf(struct pl *pl, const struct mbuf *mb); int32_t pl_i32(const struct pl *pl); diff --git a/src/fmt/pl.c b/src/fmt/pl.c index 32edd193b..72ebfa4e8 100644 --- a/src/fmt/pl.c +++ b/src/fmt/pl.c @@ -21,6 +21,48 @@ const struct pl pl_null = {NULL, 0}; +static void pl_alloc_destruct(void *arg) +{ + struct pl *pl = arg; + + mem_deref((void *)pl->p); +} + + +/** + * Allocate a pointer-length object from a NULL-terminated string + * + * @param str NULL-terminated string + * + * @return Allocated Pointer-length object or NULL + */ +struct pl *pl_alloc_str(const char *str) +{ + struct pl *pl; + + if (!str) + return NULL; + + size_t sz = strlen(str); + + pl = mem_zalloc(sizeof(struct pl), pl_alloc_destruct); + if (!pl) + return NULL; + + pl->p = mem_alloc(sz, NULL); + if (!pl->p) { + mem_deref(pl); + return NULL; + } + + memcpy((void *)pl->p, str, sz); + + pl->l = sz; + + return pl; +} + + /** * Initialise a pointer-length object from a NULL-terminated string * diff --git a/test/fmt.c b/test/fmt.c index 79a93aecc..6eb9ef807 100644 --- a/test/fmt.c +++ b/test/fmt.c @@ -138,6 +138,24 @@ int test_fmt_pl(void) } +int test_fmt_pl_alloc_str(void) +{ + int err = 0; + char test_str[] = "Test String"; + + struct pl *pl = pl_alloc_str(test_str); + if (!pl) + return ENOMEM; + + TEST_MEMCMP(test_str, str_len(test_str), pl->p, pl->l); + +out: + mem_deref(pl); + + return err; +} + + int test_fmt_pl_i32(void) { const struct { diff --git a/test/test.c b/test/test.c index 86a3a278d..daec37bb1 100644 --- a/test/test.c +++ b/test/test.c @@ -79,6 +79,7 @@ static const struct test tests[] = { TEST(test_fmt_human_time), TEST(test_fmt_param), TEST(test_fmt_pl), + TEST(test_fmt_pl_alloc_str), TEST(test_fmt_pl_float), TEST(test_fmt_pl_i32), TEST(test_fmt_pl_i64), diff --git a/test/test.h b/test/test.h index a11cfdc5a..1eb31009e 100644 --- a/test/test.h +++ b/test/test.h @@ -181,6 +181,7 @@ int test_fmt_hexdump(void); int test_fmt_human_time(void); int test_fmt_param(void); int test_fmt_pl(void); +int test_fmt_pl_alloc_str(void); int test_fmt_pl_float(void); int test_fmt_pl_i32(void); int test_fmt_pl_i64(void);