Skip to content

Commit

Permalink
modules: Add newlen == 0 handling to RM_StringTruncate (#3717)
Browse files Browse the repository at this point in the history
Previously, passing 0 for newlen would not truncate the string at all.

This adds handling of this case, freeing the old string and creating a new empty string.
  • Loading branch information
neomantra committed Dec 29, 2016
1 parent 6712bce commit 087936a
Showing 1 changed file with 13 additions and 8 deletions.
21 changes: 13 additions & 8 deletions src/module.c
Expand Up @@ -1446,14 +1446,19 @@ int RM_StringTruncate(RedisModuleKey *key, size_t newlen) {
} else {
/* Unshare and resize. */
key->value = dbUnshareStringValue(key->db, key->key, key->value);
size_t curlen = sdslen(key->value->ptr);
if (newlen > curlen) {
key->value->ptr = sdsgrowzero(key->value->ptr,newlen);
} else if (newlen < curlen) {
sdsrange(key->value->ptr,0,newlen-1);
/* If the string is too wasteful, reallocate it. */
if (sdslen(key->value->ptr) < sdsavail(key->value->ptr))
key->value->ptr = sdsRemoveFreeSpace(key->value->ptr);
if (newlen == 0) {
sdsfree(key->value->ptr);
key->value->ptr = sdsempty();
} else {
size_t curlen = sdslen(key->value->ptr);
if (newlen > curlen) {
key->value->ptr = sdsgrowzero(key->value->ptr,newlen);
} else if (newlen < curlen) {
sdsrange(key->value->ptr,0,newlen-1);
/* If the string is too wasteful, reallocate it. */
if (sdslen(key->value->ptr) < sdsavail(key->value->ptr))
key->value->ptr = sdsRemoveFreeSpace(key->value->ptr);
}
}
}
return REDISMODULE_OK;
Expand Down

0 comments on commit 087936a

Please sign in to comment.