From 0658659f74ad134bddbc982f7e1de0ff9b8bda66 Mon Sep 17 00:00:00 2001 From: Campbell Barton Date: Wed, 2 Mar 2016 11:12:48 +1100 Subject: GHash: BLI_ghash_ensure_p_ex now takes a pointer-to-key arg This is an alternative to passing a copy callback which is some times inconvenient. Instead the caller can write to the key - needed when the key is duplicated memory. Allows for minor optimization in ghash/gset use. Also add BLI_gset_ensure_p_ex --- source/blender/blenlib/intern/BLI_ghash.c | 34 ++++++++++++++++++++++++++----- 1 file changed, 29 insertions(+), 5 deletions(-) (limited to 'source/blender/blenlib/intern/BLI_ghash.c') diff --git a/source/blender/blenlib/intern/BLI_ghash.c b/source/blender/blenlib/intern/BLI_ghash.c index 21b0a5860af..0cb30208642 100644 --- a/source/blender/blenlib/intern/BLI_ghash.c +++ b/source/blender/blenlib/intern/BLI_ghash.c @@ -836,11 +836,13 @@ bool BLI_ghash_ensure_p(GHash *gh, void *key, void ***r_val) } /** - * A version of #BLI_ghash_ensure_p copies the key on insertion. + * A version of #BLI_ghash_ensure_p that allows caller to re-assign the key. + * Typically used when the key is to be duplicated. + * + * \warning Caller _must_ write to \a r_key when returning false. */ bool BLI_ghash_ensure_p_ex( - GHash *gh, const void *key, void ***r_val, - GHashKeyCopyFP keycopyfp) + GHash *gh, const void *key, void ***r_key, void ***r_val) { const unsigned int hash = ghash_keyhash(gh, key); const unsigned int bucket_index = ghash_bucket_index(gh, hash); @@ -848,11 +850,11 @@ bool BLI_ghash_ensure_p_ex( const bool haskey = (e != NULL); if (!haskey) { - /* keycopyfp(key) is the only difference to BLI_ghash_ensure_p */ e = BLI_mempool_alloc(gh->entrypool); - ghash_insert_ex_keyonly_entry(gh, keycopyfp(key), bucket_index, (Entry *)e); + ghash_insert_ex_keyonly_entry(gh, NULL, bucket_index, (Entry *)e); } + *r_key = &e->e.key; *r_val = &e->val; return haskey; } @@ -1390,6 +1392,28 @@ bool BLI_gset_add(GSet *gs, void *key) return ghash_insert_safe_keyonly((GHash *)gs, key, false, NULL); } +/** + * Set counterpart to #BLI_ghash_ensure_p_ex. + * similar to BLI_gset_add, except it returns the key pointer. + * + * \warning Caller _must_ write to \a r_key when returning false. + */ +bool BLI_gset_ensure_p_ex(GSet *gs, const void *key, void ***r_key) +{ + const unsigned int hash = ghash_keyhash((GHash *)gs, key); + const unsigned int bucket_index = ghash_bucket_index((GHash *)gs, hash); + GSetEntry *e = (GSetEntry *)ghash_lookup_entry_ex((GHash *)gs, key, bucket_index); + const bool haskey = (e != NULL); + + if (!haskey) { + e = BLI_mempool_alloc(((GHash *)gs)->entrypool); + ghash_insert_ex_keyonly_entry((GHash *)gs, NULL, bucket_index, (Entry *)e); + } + + *r_key = &e->key; + return haskey; +} + /** * Adds the key to the set (duplicates are managed). * Matching #BLI_ghash_reinsert -- cgit v1.2.3