-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustom_hash_table.h
More file actions
96 lines (82 loc) · 2.14 KB
/
custom_hash_table.h
File metadata and controls
96 lines (82 loc) · 2.14 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#ifndef CUSTOM_HASH_TABLE_H
#define CUSTOM_HASH_TABLE_H
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#define TABLE_SIZE 100
typedef struct node {
char *key;
struct node *next;
} hash_node_t;
//ref: https://stackoverflow.com/questions/7666509/hash-function-for-string
unsigned int hash(const char *key) {
unsigned long hash_val = 5381;
int c;
while ((c = *key++)) {
hash_val = ((hash_val << 5) + hash_val) + c;
}
return hash_val % TABLE_SIZE;
}
void insert(hash_node_t **table, const char *key) {
unsigned int idx = hash(key);
hash_node_t *n = table[idx];
while (n) {
if (strcmp(n->key, key) == 0) {
return;
}
n = n->next;
}
//add new node
hash_node_t *new_node = (hash_node_t *)malloc(sizeof(hash_node_t));
new_node->key = strdup(key);
new_node->next = table[idx];
table[idx] = new_node;
}
//check if key exists in set
bool contains(hash_node_t **table, const char *key) {
unsigned int idx = hash(key);
hash_node_t *n = table[idx];
while (n) {
if (strcmp(n->key, key) == 0) {
return true;
}
n = n->next;
}
return false;
}
//remove key from set
void remove_key(hash_node_t **table, const char *key) {
unsigned int idx = hash(key);
hash_node_t *n = table[idx];
hash_node_t *prev = NULL;
while (n) {
if (strcmp(n->key, key) == 0) {
if (prev) {
prev->next = n->next;
} else {
table[idx] = n->next;
}
free(n->key);
free(n);
return;
}
prev = n;
n = n->next;
}
}
//extract username from message format "username: message"
void extract_username(const char *message, char *username, int max_len) {
const char *colon = strchr(message, ':');
if (colon != NULL) {
int len = colon - message;
if (len > 0 && len < max_len) {
strncpy(username, message, len);
username[len] = '\0';
} else {
username[0] = '\0';
}
} else {
username[0] = '\0';
}
}
#endif