[PATCH wayland 2/3] Add a wl_array_printf function for easy string formatting

Jason Ekstrand jason at jlekstrand.net
Wed Dec 18 18:56:19 PST 2013


Signed-off-by: Jason Ekstrand <jason at jlekstrand.net>
---
 src/wayland-util.c | 41 +++++++++++++++++++++++++++++++++++++++++
 src/wayland-util.h |  1 +
 2 files changed, 42 insertions(+)

diff --git a/src/wayland-util.c b/src/wayland-util.c
index 4fe9c81..c9d6d0e 100644
--- a/src/wayland-util.c
+++ b/src/wayland-util.c
@@ -25,6 +25,7 @@
 #include <stdint.h>
 #include <string.h>
 #include <stdarg.h>
+#include <errno.h>
 
 #include "wayland-util.h"
 #include "wayland-private.h"
@@ -148,6 +149,46 @@ wl_array_copy(struct wl_array *array, struct wl_array *source)
 	return 0;
 }
 
+int
+wl_array_printf(struct wl_array *array, const char *fmt, ...)
+{
+	va_list ap;
+	int nchars;
+	size_t old_size;
+
+	while (1) {
+		errno = 0;
+
+		va_start(ap, fmt);
+		nchars = vsnprintf((char *)array->data + array->size,
+				   array->alloc - array->size, fmt, ap);
+		va_end(ap);
+
+		/* Depending on whether the library implements the C99
+		 * printf specification or the ISO printf specification,
+		 * the return value may be different.  C99 printf returns
+		 * the value of the string that *would* be printed in the
+		 * case of overflow, ISO printf simply returns -1.
+		 *
+		 * In order to differentiate between overflow and an error,
+		 * we set errno to 0 explicitly.
+		 */
+		if (errno != 0)
+			return -1;
+
+		if (nchars < 0) {
+			wl_array_add(array, array->alloc);
+		} else if (nchars >= (ssize_t)(array->alloc - array->size)) {
+			old_size = array->size;
+			wl_array_add(array, nchars + 1);
+			array->size = old_size;
+		} else {
+			array->size += nchars;
+			return nchars;
+		}
+	}
+}
+
 union map_entry {
 	uintptr_t next;
 	void *data;
diff --git a/src/wayland-util.h b/src/wayland-util.h
index 68d91e2..b8919b9 100644
--- a/src/wayland-util.h
+++ b/src/wayland-util.h
@@ -202,6 +202,7 @@ void wl_array_init(struct wl_array *array);
 void wl_array_release(struct wl_array *array);
 void *wl_array_add(struct wl_array *array, size_t size);
 int wl_array_copy(struct wl_array *array, struct wl_array *source);
+int wl_array_printf(struct wl_array *array, const char *fmt, ...);
 
 typedef int32_t wl_fixed_t;
 
-- 
1.8.4.2



More information about the wayland-devel mailing list