Skip to content

Commit

Permalink
fmt/pl: add pl_alloc_str
Browse files Browse the repository at this point in the history
  • Loading branch information
sreimers committed Oct 11, 2023
1 parent 1de6ddc commit 02d8085
Show file tree
Hide file tree
Showing 5 changed files with 64 additions and 0 deletions.
1 change: 1 addition & 0 deletions include/re_fmt.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
43 changes: 43 additions & 0 deletions src/fmt/pl.c
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,49 @@
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 pl Pointer-length object to be initialised
* @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
*
Expand Down
18 changes: 18 additions & 0 deletions test/fmt.c
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
1 change: 1 addition & 0 deletions test/test.c
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
1 change: 1 addition & 0 deletions test/test.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit 02d8085

Please sign in to comment.