]> granicus.if.org Git - libass/commitdiff
Add another helper-macro for array allocation
authorwm4 <wm4@nowhere>
Fri, 14 Nov 2014 19:19:14 +0000 (20:19 +0100)
committerwm4 <wm4@nowhere>
Fri, 14 Nov 2014 19:35:31 +0000 (20:35 +0100)
libass/ass_utils.c
libass/ass_utils.h

index 27fc025553a81b1a8a575f1f52187beb9a0064b7..593d787c57f86095c0b570820d55f15219b29b85 100644 (file)
@@ -102,6 +102,23 @@ void *ass_realloc_array(void *ptr, size_t nmemb, size_t size)
     return realloc(ptr, size);
 }
 
+/**
+ * Like ass_realloc_array(), but:
+ * 1. on failure, return the original ptr value, instead of NULL
+ * 2. set errno to indicate failure (errno!=0) or success (errno==0)
+ */
+void *ass_try_realloc_array(void *ptr, size_t nmemb, size_t size)
+{
+    void *new_ptr = ass_realloc_array(ptr, nmemb, size);
+    if (new_ptr) {
+        errno = 0;
+        return new_ptr;
+    } else {
+        errno = ENOMEM;
+        return ptr;
+    }
+}
+
 void skip_spaces(char **str)
 {
     char *p = *str;
index 5548a931e5abf787cf5f36b180325d0e293d2adb..5055e889197b8f5ce84cc95f05b966e545291a55 100644 (file)
@@ -25,6 +25,7 @@
 #include <stdlib.h>
 #include <string.h>
 #include <assert.h>
+#include <errno.h>
 
 #ifdef CONFIG_ENCA
 #include <enca.h>
@@ -57,6 +58,20 @@ void *ass_aligned_alloc(size_t alignment, size_t size);
 void ass_aligned_free(void *ptr);
 
 void *ass_realloc_array(void *ptr, size_t nmemb, size_t size);
+void *ass_try_realloc_array(void *ptr, size_t nmemb, size_t size);
+
+/**
+ * Reallocate the array in ptr to at least count elements. For example, if
+ * you do "int *ptr = NULL; ASS_REALLOC_ARRAY(ptr, 5)", you can access ptr[0]
+ * through ptr[4] (inclusive).
+ *
+ * If memory allocation fails, ptr is left unchanged, and the macro returns 0:
+ * "if (!ASS_REALLOC_ARRAY(ptr, 5)) goto error;"
+ *
+ * A count of 0 does not free the array (see ass_realloc_array for remarks).
+ */
+#define ASS_REALLOC_ARRAY(ptr, count) \
+    (errno = 0, (ptr) = ass_try_realloc_array(ptr, count, sizeof(*ptr)), !errno)
 
 void skip_spaces(char **str);
 void rskip_spaces(char **str, char *limit);