From 1598c2a362fec3de547616cb8020a315631a4c15 Mon Sep 17 00:00:00 2001 From: Ralph Ronnquist Date: Mon, 11 Jul 2022 00:38:51 +1000 Subject: [PATCH] revise hashvector_contents to optionally create the target vector --- vector/hashvector.c | 35 ++++++++++++++++++++--------------- vector/hashvector.h | 19 +++++++++++++------ 2 files changed, 33 insertions(+), 21 deletions(-) diff --git a/vector/hashvector.c b/vector/hashvector.c index b39ef5e..8b88135 100644 --- a/vector/hashvector.c +++ b/vector/hashvector.c @@ -158,23 +158,28 @@ int hashvector_delete(hashvector *hv,void *item) { return 1; } -// Copy items into a vector. Returns 0 on success and -1 on failure. -int hashvector_contents(hashvector *hv,vector *pv) { - if ( vector_resize( pv, hv->fill, 0, 0 ) ) { - return -1; - } - unsigned long from = 0; - unsigned long to = 0; - for ( ; to < hv->fill; from++ ) { - void **slot = vector_next_used( &hv->table, &from ); - if ( slot == 0 ) { - break; - } - if ( *slot != HV_HOLE ) { - vector_set( pv, to++, *slot ); +vector *hashvector_contents( + hashvector *hv,enum vector_variant variant,vector *v) +{ + if ( v == 0 ) { + if ( hv->fill == 0 ) { + return 0; } + v = (vector*) malloc( sizeof( vector ) ); + } else { + vector_resize( v, 0, vector_clear_any, 0 ); } - return 0; + (*v) = (vector) { .variant = variant, 0, 0 }; + if ( hv->fill == 0 ) { + return v; + } + vector_resize( v, hv->fill, 0, 0 ); + vector_index i; + vector_index j = 0; + for ( i = 0; i < v->size; i++, j++ ) { + vector_set( v, i, hashvector_next( hv, &j, 0 ) ); + } + return v; } // A simple binary hashcode, (before modulo table size) diff --git a/vector/hashvector.h b/vector/hashvector.h index 2754fb1..b57aede 100644 --- a/vector/hashvector.h +++ b/vector/hashvector.h @@ -134,16 +134,23 @@ extern int hashvector_delete(hashvector *hv,void *item); * * \param hv is the \ref hashvector concerned. * - * \param pv is the \ref vector to copy the content into. + * \param variant is the desired vector variant. * - * \returns \b -1 if the required resizing of the \ref vector to the - * \ref hashvector \b fill fails, otherwise \b 0 after having copied - * the hashvector items in their internal order of appearance into the - * \ref vector. + * \param pv is the optional \ref vector to copy the content into. + * + * \returns the \ref vector with the \ref hashvector content + * + * If \pv is null, then a new vector is allocated and handed out for + * the caller to reclaim unless the hashvector is empty in which case + * this function returns 0. + * + * If \b pv is not null, it is first cleared, and then populated with + * the content from the hashvector. The populated vector is returned. * * \related hashvector */ -extern int hashvector_contents(hashvector *hv,vector *pv); +extern vector *hashvector_contents( + hashvector *hv,enum vector_variant variant,vector *pv); /** * \brief This is a utility function to compute and return a hashcode -- 2.39.2