[gegl] buffer: add gegl_try_malloc()



commit 2c3f247577838a6c7292d884bb2618f915bc906e
Author: Ell <ell_se yahoo com>
Date:   Fri Jul 19 19:23:45 2019 +0300

    buffer: add gegl_try_malloc()
    
    ... which returns NULL if allocation fails, instead of aborting.

 gegl/buffer/gegl-memory.c | 36 +++++++++++++++++++++++++++++-------
 gegl/buffer/gegl-memory.h | 13 ++++++++++++-
 2 files changed, 41 insertions(+), 8 deletions(-)
---
diff --git a/gegl/buffer/gegl-memory.c b/gegl/buffer/gegl-memory.c
index e6e047c68..5b1e492b1 100644
--- a/gegl/buffer/gegl-memory.c
+++ b/gegl/buffer/gegl-memory.c
@@ -32,22 +32,44 @@ G_STATIC_ASSERT (GEGL_ALIGNMENT <= G_MAXUINT8);
 /* utility call that makes sure allocations are 16 byte aligned.
  * making RGBA float buffers have aligned access for pixels.
  */
-gpointer
-gegl_malloc (gsize size)
+static inline gpointer
+gegl_malloc_align (gchar *mem)
 {
-  gchar *mem;
   gchar *ret;
   gint   offset;
 
-  mem    = g_malloc (size + GEGL_ALIGNMENT);
-  offset = GEGL_ALIGNMENT - GPOINTER_TO_UINT(mem) % GEGL_ALIGNMENT;
-  ret    = (gpointer)(mem + offset);
+  offset = GEGL_ALIGNMENT - GPOINTER_TO_UINT (mem) % GEGL_ALIGNMENT;
+  ret    = (gpointer) (mem + offset);
 
   /* store the offset to the real malloc one byte in front of this malloc */
-  *(guint8*)(ret-1)=offset;
+  *(guint8 *) (ret - 1) = offset;
+
   return (gpointer) ret;
 }
 
+gpointer
+gegl_malloc (gsize size)
+{
+  gchar *mem;
+
+  mem = g_malloc (size + GEGL_ALIGNMENT);
+
+  return gegl_malloc_align (mem);
+}
+
+gpointer
+gegl_try_malloc (gsize size)
+{
+  gchar *mem;
+
+  mem = g_try_malloc (size + GEGL_ALIGNMENT);
+
+  if (! mem)
+    return NULL;
+
+  return gegl_malloc_align (mem);
+}
+
 gpointer
 gegl_calloc (gsize size,
              gint  n_memb)
diff --git a/gegl/buffer/gegl-memory.h b/gegl/buffer/gegl-memory.h
index 881ce2dbc..41155f0fa 100644
--- a/gegl/buffer/gegl-memory.h
+++ b/gegl/buffer/gegl-memory.h
@@ -29,12 +29,23 @@
  * gegl_malloc: (skip)
  * @n_bytes: the number of bytes to allocte.
  *
- * Allocates @n_bytes of memory. If n_bytes is 0 it returns NULL.
+ * Allocates @n_bytes of memory. If @n_bytes is 0, returns NULL.
  *
  * Returns a pointer to the allocated memory.
  */
 gpointer   gegl_malloc         (gsize         n_bytes) G_GNUC_MALLOC;
 
+/**
+ * gegl_try_malloc: (skip)
+ * @n_bytes: the number of bytes to allocte.
+ *
+ * Allocates @n_bytes of memory. If allocation fails, or if @n_bytes is 0,
+ * returns %NULL.
+ *
+ * Returns a pointer to the allocated memory, or NULL.
+ */
+gpointer   gegl_try_malloc     (gsize         n_bytes) G_GNUC_MALLOC;
+
 /**
  * gegl_free: (skip)
  * @mem: the memory to free.


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]