MAP_RESULT Map_AddOrUpdate()

in src/map.c [390:457]


MAP_RESULT Map_AddOrUpdate(MAP_HANDLE handle, const char* key, const char* value)
{
    MAP_RESULT result;
    /*Codes_SRS_MAP_02_013: [If parameter handle is NULL then Map_AddOrUpdate shall return MAP_INVALID_ARG.]*/
    /*Codes_SRS_MAP_02_014: [If parameter key is NULL then Map_AddOrUpdate shall return MAP_INVALID_ARG.]*/
    /*Codes_SRS_MAP_02_015: [If parameter value is NULL then Map_AddOrUpdate shall return MAP_INVALID_ARG.] */
    if (
        (handle == NULL) ||
        (key == NULL) ||
        (value == NULL)
        )
    {
        result = MAP_INVALIDARG;
        LOG_MAP_ERROR;
    }
    else
    {
        MAP_HANDLE_DATA* handleData = handle;

        /* Codes_SRS_MAP_07_008: [If the mapFilterCallback function is not NULL, then the return value will be check and if it is not zero then Map_AddOrUpdate shall return MAP_FILTER_REJECT.] */
        if (handleData->mapFilterCallback != NULL && handleData->mapFilterCallback(key, value) != 0)
        {
            result = MAP_FILTER_REJECT;
        }
        else
        {
            char** whereIsIt = findKey(handleData, key);
            if (whereIsIt == NULL)
            {
                /*Codes_SRS_MAP_02_017: [Otherwise, Map_AddOrUpdate shall add the pair <key,value> to the map.]*/
                if (insertNewKeyValue(handleData, key, value) != 0)
                {
                    /*Codes_SRS_MAP_02_018: [If there are any failures then Map_AddOrUpdate shall return MAP_ERROR.] */
                    result = MAP_ERROR;
                    LOG_MAP_ERROR;
                }
                else
                {
                    result = MAP_OK;
                }
            }
            else
            {
                /*Codes_SRS_MAP_02_016: [If the key already exists, then Map_AddOrUpdate shall overwrite the value of the existing key with parameter value.]*/
                size_t index = whereIsIt - handleData->keys;
                size_t valueLength = strlen(value);
                /*try to realloc value of this key*/
                char* newValue = realloc_flex(handleData->values[index], 1, valueLength, 1);
                if (newValue == NULL)
                {
                    /*Codes_SRS_MAP_02_018: [If there are any failures then Map_AddOrUpdate shall return MAP_ERROR.] */
                    LogError("failure in realloc_flex(handleData->values[index], 1, valueLength=%zu, 1);",
                        valueLength);
                    result = MAP_ERROR;
                    LOG_MAP_ERROR;
                }
                else
                {
                    (void)memcpy(newValue, value, valueLength + 1);
                    handleData->values[index] = newValue;
                    /*Codes_SRS_MAP_02_019: [Otherwise, Map_AddOrUpdate shall return MAP_OK.] */
                    result = MAP_OK;
                }
            }
        }
    }
    return result;
}