array: new append and steal subtree
authorNiki <niki@nikiroo.be>
Tue, 8 Apr 2025 15:12:13 +0000 (17:12 +0200)
committerNiki <niki@nikiroo.be>
Tue, 8 Apr 2025 15:12:13 +0000 (17:12 +0200)
array.c
array.h

diff --git a/array.c b/array.c
index 4b2faf6a4c6cbfe524416c3edd32b162c0cc9f79..12fd125aebb4c70ee3b89a83feb2adff5a016115 100644 (file)
--- a/array.c
+++ b/array.c
@@ -112,6 +112,30 @@ void *array_convert(array_t *me) {
        return data;
 }
 
+int array_steal_data(array_t *me, array_t *victim) {
+       priv_t *priv  = (priv_t *)me    ->priv;
+       priv_t *vpriv = (priv_t *)victim->priv;
+       
+       if (priv->elem_size != vpriv->elem_size)
+               return 0;
+       
+       array_clear(me);
+       
+       void *tmp = me->priv;
+       me->priv = victim->priv;
+       victim->priv = tmp;
+               
+       me->count = victim->count;
+       victim->count = 0;
+               
+       return 1;
+}
+
+int array_append(array_t *me, array_t *extra) {
+       priv_t *epriv = (priv_t *)extra->priv;
+       return array_setn(me, me->count, epriv->data, extra->count);
+}
+
 void *array_data(array_t *me) {
        priv_t *priv = (priv_t *) me->priv;
 
diff --git a/array.h b/array.h
index a4b849837994ca8a34693f6e08af7d8debbbc572..3f83371ab7bebff1f6165998ec8b116588d9f34b 100644 (file)
--- a/array.h
+++ b/array.h
@@ -224,6 +224,28 @@ void array_clear(array_t *me);
  */
 void *array_convert(array_t *me);
 
+/**
+ * Will steal the data from this array and make it replace our own,
+ * clearing our own data first.
+ * The victim array will be empty on success.
+ *
+ * @param victim the array whose data will be taken and cleared
+ *
+ * @note useful if you want to filter an array via a new, temporary one
+ * @note do not forget that you are still responsible for the (cleared) array
+ * 
+ * @return FALSE if both arrays are incompatible
+ */
+int array_steal_data(array_t *me, array_t *victim);
+
+/**
+ * Will append the content of the given array to itself.
+ *
+ * @return FALSE if the array is too short and we cannot allocate enough 
+ *     contiguous memory for its needs
+ */
+int array_append(array_t *me, array_t *extra);
+
 /**
  * Return a pointer to the internal storage used by this array.
  * This is the same value as would return `array_convert()`,