CLDS_ST_HASH_SET_HANDLE clds_st_hash_set_create()

in src/clds_st_hash_set.c [30:91]


CLDS_ST_HASH_SET_HANDLE clds_st_hash_set_create(CLDS_ST_HASH_SET_COMPUTE_HASH_FUNC compute_hash_func, CLDS_ST_HASH_SET_KEY_COMPARE_FUNC key_compare_func, size_t bucket_size)
{
    CLDS_ST_HASH_SET_HANDLE clds_st_hash_set;

    if (
        /* Codes_SRS_CLDS_ST_HASH_SET_01_003: [ If compute_hash_func is NULL, clds_st_hash_set_create shall fail and return NULL. ]*/
        (compute_hash_func == NULL) ||
        /* Codes_SRS_CLDS_ST_HASH_SET_01_004: [ If key_compare_func is NULL, clds_st_hash_set_create shall fail and return NULL. ]*/
        (key_compare_func == NULL) ||
        /* Codes_SRS_CLDS_ST_HASH_SET_01_005: [ If bucket_size is 0, clds_st_hash_set_create shall fail and return NULL. ]*/
        (bucket_size == 0)
        )
    {
        LogError("Invalid arguments: CLDS_ST_HASH_SET_COMPUTE_HASH_FUNC compute_hash=%p, CLDS_ST_HASH_SET_KEY_COMPARE_FUNC key_compare_func=%p, size_t bucket_size=%zu",
            compute_hash_func, key_compare_func, bucket_size);
    }
    else
    {
        /* Codes_SRS_CLDS_ST_HASH_SET_01_001: [ clds_st_hash_set_create shall create a new hash set object and on success it shall return a non-NULL handle to the newly created hash set. ]*/
        clds_st_hash_set = malloc(sizeof(CLDS_ST_HASH_SET));
        if (clds_st_hash_set == NULL)
        {
            /* Codes_SRS_CLDS_ST_HASH_SET_01_002: [ If any error happens, clds_st_hash_set_create shall fail and return NULL. ]*/
            LogError("Cannot allocate memory for hash table");
        }
        else
        {
            /* Codes_SRS_CLDS_ST_HASH_SET_01_022: [ clds_st_hash_set_create shall allocate memory for the array of buckets used to store the hash set data. ]*/
            clds_st_hash_set->hash_set = malloc_2(bucket_size, sizeof(void*));
            if (clds_st_hash_set->hash_set == NULL)
            {
                /* Codes_SRS_CLDS_ST_HASH_SET_01_002: [ If any error happens, clds_st_hash_set_create shall fail and return NULL. ]*/
                LogError("Cannot allocate memory for hash set array, malloc_2(bucket_size=%zu, sizeof(void*)=%zu);",
                    bucket_size, sizeof(void*));
            }
            else
            {
                size_t i;

                clds_st_hash_set->compute_hash_func = compute_hash_func;
                clds_st_hash_set->key_compare_func = key_compare_func;

                // set the initial bucket count
                clds_st_hash_set->bucket_count = bucket_size;

                for (i = 0; i < bucket_size; i++)
                {
                    clds_st_hash_set->hash_set[i] = NULL;
                }

                goto all_ok;
            }

            free(clds_st_hash_set);
        }
    }

    clds_st_hash_set = NULL;

all_ok:
    return clds_st_hash_set;
}