-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path3-hash_table_set.c
53 lines (47 loc) · 1.06 KB
/
3-hash_table_set.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include "hash_tables.h"
/**
* hash_table_set - Add or update an element in a hash table.
* @ht: A pointer to the hash table.
* @key: The key to add - cannot be an empty string.
* @value: The value associated with key.
*
* Return: Upon failure - 0.
* Otherwise - 1.
*/
int hash_table_set(hash_table_t *ht, const char *key, const char *value)
{
hash_node_t *new;
char *value_copy;
unsigned long int index, i;
if (ht == NULL || key == NULL || *key == '\0' || value == NULL)
return (0);
value_copy = strdup(value);
if (value_copy == NULL)
return (0);
index = key_index((const unsigned char *)key, ht->size);
for (i = index; ht->array[i]; i++)
{
if (strcmp(ht->array[i]->key, key) == 0)
{
free(ht->array[i]->value);
ht->array[i]->value = value_copy;
return (1);
}
}
new = malloc(sizeof(hash_node_t));
if (new == NULL)
{
free(value_copy);
return (0);
}
new->key = strdup(key);
if (new->key == NULL)
{
free(new);
return (0);
}
new->value = value_copy;
new->next = ht->array[index];
ht->array[index] = new;
return (1);
}