changeset 402:d3fa956cdaf0

core: add alloc_sdupf
author David Demelier <markand@malikania.fr>
date Wed, 30 Mar 2022 15:06:55 +0200
parents df5e1fea1d2e
children 7536be134718
files doc/docs/dev/api/core/alloc.md src/libmlk-core/core/alloc.c src/libmlk-core/core/alloc.h tests/test-alloc.c
diffstat 4 files changed, 45 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/doc/docs/dev/api/core/alloc.md	Wed Mar 16 13:37:56 2022 +0100
+++ b/doc/docs/dev/api/core/alloc.md	Wed Mar 30 15:06:55 2022 +0200
@@ -254,6 +254,15 @@
 alloc_sdup(const char *src)
 ```
 
+### alloc\_sdupf
+
+Create a dynamically allocated string using printf(3) format like.
+
+```c
+char *
+alloc_sdupf(const char *fmt, ...);
+```
+
 ### alloc\_pool\_init
 
 Initialize the `pool` as an array where elements have `elemsize` size. Optional
--- a/src/libmlk-core/core/alloc.c	Wed Mar 16 13:37:56 2022 +0100
+++ b/src/libmlk-core/core/alloc.c	Wed Mar 30 15:06:55 2022 +0200
@@ -24,6 +24,7 @@
 #include <SDL.h>
 
 #include "alloc.h"
+#include "buf.h"
 #include "error.h"
 #include "panic.h"
 
@@ -185,6 +186,30 @@
 	return ret;
 }
 
+char *
+alloc_sdupf(const char *fmt, ...)
+{
+	struct buf buf = {0};
+	char *ret;
+	va_list ap;
+
+	va_start(ap, fmt);
+	buf_vprintf(&buf, fmt, ap);
+	va_end(ap);
+
+	if (!buf.data)
+		panicf("%s", strerror(ENOMEM));
+
+	/*
+	 * We need to reallocate a copy because the API expects to use
+	 * alloc_free.
+	 */
+	ret = alloc_dup(buf.data, buf.length + 1);
+	buf_finish(&buf);
+
+	return ret;
+}
+
 int
 alloc_pool_init(struct alloc_pool *pool, size_t elemsize, void (*finalizer)(void *))
 {
--- a/src/libmlk-core/core/alloc.h	Wed Mar 16 13:37:56 2022 +0100
+++ b/src/libmlk-core/core/alloc.h	Wed Mar 30 15:06:55 2022 +0200
@@ -76,6 +76,9 @@
 char *
 alloc_sdup(const char *);
 
+char *
+alloc_sdupf(const char *, ...);
+
 /* alloc_pool functions. */
 int
 alloc_pool_init(struct alloc_pool *, size_t , void (*)(void *));
--- a/tests/test-alloc.c	Wed Mar 16 13:37:56 2022 +0100
+++ b/tests/test-alloc.c	Wed Mar 30 15:06:55 2022 +0200
@@ -93,6 +93,14 @@
 	RX_UINT_REQUIRE_EQUAL(pool.capacity, 0U);
 }
 
+RX_TEST_CASE(test, sdupf)
+{
+	char *str = alloc_sdupf("Hello %s", "David");
+
+	RX_STR_REQUIRE_EQUAL(str, "Hello David");
+	free(str);
+}
+
 int
 main(int argc, char **argv)
 {