Improve RM_ModuleTypeReplaceValue() API.

With the previous API, a NULL return value was ambiguous and could
represent either an old value of NULL or an error condition. The new API
returns a status code and allows the old value to be returned
by-reference.

This commit also includes test coverage based on
tests/modules/datatype.c which did not exist at the time of the original
commit.
This commit is contained in:
Yossi Gottlieb
2019-12-12 18:50:11 +02:00
parent 118db9eeae
commit 0283db5883
4 changed files with 59 additions and 9 deletions

View File

@ -7308,22 +7308,30 @@ int RM_GetLFU(RedisModuleKey *key, long long *lfu_freq) {
* Unlike RM_ModuleTypeSetValue() which will free the old value, this function
* simply swaps the old value with the new value.
*
* The function returns the old value, or NULL if any of the above conditions is
* not met.
* The function returns REDISMODULE_OK on success, REDISMODULE_ERR on errors
* such as:
*
* 1. Key is not opened for writing.
* 2. Key is not a module data type key.
* 3. Key is a module datatype other than 'mt'.
*
* If old_value is non-NULL, the old value is returned by reference.
*/
void *RM_ModuleTypeReplaceValue(RedisModuleKey *key, moduleType *mt, void *new_value) {
int RM_ModuleTypeReplaceValue(RedisModuleKey *key, moduleType *mt, void *new_value, void **old_value) {
if (!(key->mode & REDISMODULE_WRITE) || key->iter)
return NULL;
return REDISMODULE_ERR;
if (!key->value || key->value->type != OBJ_MODULE)
return NULL;
return REDISMODULE_ERR;
moduleValue *mv = key->value->ptr;
if (mv->type != mt)
return NULL;
return REDISMODULE_ERR;
void *old_val = mv->value;
if (old_value)
*old_value = mv->value;
mv->value = new_value;
return old_val;
return REDISMODULE_OK;
}
/* Register all the APIs we export. Keep this function at the end of the