From 7c14139e06ca318936241c1e22d0a469237bf4bf Mon Sep 17 00:00:00 2001 From: Niki Date: Tue, 8 Apr 2025 17:12:13 +0200 Subject: [PATCH] array: new append and steal --- array.c | 24 ++++++++++++++++++++++++ array.h | 22 ++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/array.c b/array.c index 4b2faf6..12fd125 100644 --- 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 a4b8498..3f83371 100644 --- 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()`, -- 2.27.0