* This function can be used instead of RedisModule_RetainString(). * The main difference between the two is that this function will always * succeed, whereas RedisModule_RetainString() may fail because of an * assertion. * * The function returns a pointer to RedisModuleString, which is owned * by the caller. It requires a call to RedisModule_FreeString() to free * the string when automatic memory
| 1326 | * It is possible to call this function with a NULL context. |
| 1327 | */ |
| 1328 | RedisModuleString* RM_HoldString(RedisModuleCtx *ctx, RedisModuleString *str) { |
| 1329 | if (str->getrefcount(std::memory_order_relaxed) == OBJ_STATIC_REFCOUNT) { |
| 1330 | return RM_CreateStringFromString(ctx, str); |
| 1331 | } |
| 1332 | |
| 1333 | incrRefCount(str); |
| 1334 | if (ctx != NULL) { |
| 1335 | /* |
| 1336 | * Put the str in the auto memory management of the ctx. |
| 1337 | * It might already be there, in this case, the ref count will |
| 1338 | * be 2 and we will decrease the ref count twice and free the |
| 1339 | * object in the auto memory free function. |
| 1340 | * |
| 1341 | * Why we can not do the same trick of just remove the object |
| 1342 | * from the auto memory (like in RM_RetainString)? |
| 1343 | * This code shows the issue: |
| 1344 | * |
| 1345 | * RM_AutoMemory(ctx); |
| 1346 | * str1 = RM_CreateString(ctx, "test", 4); |
| 1347 | * str2 = RM_HoldString(ctx, str1); |
| 1348 | * RM_FreeString(str1); |
| 1349 | * RM_FreeString(str2); |
| 1350 | * |
| 1351 | * If after the RM_HoldString we would just remove the string from |
| 1352 | * the auto memory, this example will cause access to a freed memory |
| 1353 | * on 'RM_FreeString(str2);' because the String will be free |
| 1354 | * on 'RM_FreeString(str1);'. |
| 1355 | * |
| 1356 | * So it's safer to just increase the ref count |
| 1357 | * and add the String to auto memory again. |
| 1358 | * |
| 1359 | * The limitation is that it is not possible to use RedisModule_StringAppendBuffer |
| 1360 | * on the String. |
| 1361 | */ |
| 1362 | autoMemoryAdd(ctx,REDISMODULE_AM_STRING,str); |
| 1363 | } |
| 1364 | return str; |
| 1365 | } |
| 1366 | |
| 1367 | /* Given a string module object, this function returns the string pointer |
| 1368 | * and length of the string. The returned pointer and length should only |
nothing calls this directly
no test coverage detected