[Bf-blender-cvs] [1884f6e7296] master: BLI_array: add BLI_array_trim utility to re-allocate the current size

Campbell Barton noreply at git.blender.org
Mon Feb 21 02:24:02 CET 2022


Commit: 1884f6e7296a3847f14331aadd6c520cc25e4d12
Author: Campbell Barton
Date:   Sun Feb 20 21:29:00 2022 +1100
Branches: master
https://developer.blender.org/rB1884f6e7296a3847f14331aadd6c520cc25e4d12

BLI_array: add BLI_array_trim utility to re-allocate the current size

Use this in BKE_view_layer_array_* functions.

===================================================================

M	source/blender/blenkernel/intern/layer_utils.c
M	source/blender/blenlib/BLI_array.h

===================================================================

diff --git a/source/blender/blenkernel/intern/layer_utils.c b/source/blender/blenkernel/intern/layer_utils.c
index 057309d0896..0903c2a2cac 100644
--- a/source/blender/blenkernel/intern/layer_utils.c
+++ b/source/blender/blenkernel/intern/layer_utils.c
@@ -67,9 +67,11 @@ Object **BKE_view_layer_array_selected_objects_params(
   }
   FOREACH_SELECTED_OBJECT_END;
 
-  object_array = MEM_reallocN(object_array, sizeof(*object_array) * BLI_array_len(object_array));
-  /* We always need a valid allocation (prevent crash on free). */
-  if (object_array == NULL) {
+  if (object_array != NULL) {
+    BLI_array_trim(object_array);
+  }
+  else {
+    /* We always need a valid allocation (prevent crash on free). */
     object_array = MEM_mallocN(0, __func__);
   }
   *r_len = BLI_array_len(object_array);
@@ -121,9 +123,11 @@ Base **BKE_view_layer_array_from_bases_in_mode_params(ViewLayer *view_layer,
   }
   FOREACH_BASE_IN_MODE_END;
 
-  base_array = MEM_reallocN(base_array, sizeof(*base_array) * BLI_array_len(base_array));
   /* We always need a valid allocation (prevent crash on free). */
-  if (base_array == NULL) {
+  if (base_array != NULL) {
+    BLI_array_trim(base_array);
+  }
+  else {
     base_array = MEM_mallocN(0, __func__);
   }
   *r_len = BLI_array_len(base_array);
diff --git a/source/blender/blenlib/BLI_array.h b/source/blender/blenlib/BLI_array.h
index d3bb3401d7e..80e865ded62 100644
--- a/source/blender/blenlib/BLI_array.h
+++ b/source/blender/blenlib/BLI_array.h
@@ -146,6 +146,17 @@ void _bli_array_grow_func(void **arr_p,
  */
 #define BLI_array_fake_user(arr) ((void)_##arr##_len, (void)_##arr##_static)
 
+/**
+ * Trim excess items from the array (when they exist).
+ */
+#define BLI_array_trim(arr) \
+  { \
+    if (_bli_array_totalsize_dynamic(arr) != _##arr##_len) { \
+      arr = MEM_reallocN(arr, sizeof(*arr) * _##arr##_len); \
+    } \
+  } \
+  ((void)0)
+
 /** \} */
 
 /* -------------------------------------------------------------------- */



More information about the Bf-blender-cvs mailing list