-
Notifications
You must be signed in to change notification settings - Fork 3
/
channel.c
115 lines (91 loc) · 2.48 KB
/
channel.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
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include "global.h"
#include "channel.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
struct channel_t * channel_new(char * name)
{
struct channel_t * channel = malloc(sizeof (struct channel_t));
memset(channel, 0, sizeof (struct channel_t));
channel->name = strdup(name);
LIST_INIT(&channel->user_list_head);
return channel;
}
struct channel_t * channel_find(struct channel_list_t * head, char * name)
{
struct channel_t * iterator;
LIST_FOREACH(iterator, head, list) {
if (strcmp(iterator->name, name) == 0) {
return iterator;
}
}
return NULL;
}
void channel_add_user(struct channel_t * channel, char * user)
{
struct user_t * user_obj = malloc(sizeof *user_obj);
user_obj->name = strdup(user);
LIST_INSERT_HEAD(&channel->user_list_head, user_obj, list);
}
void channel_remove_user(struct channel_t * channel, char * user)
{
struct user_t * iterator, * temp;
temp = NULL;
LIST_FOREACH(iterator, &channel->user_list_head, list) {
if (strcmp(iterator->name, user) == 0) {
temp = iterator;
}
}
if (temp) {
LIST_REMOVE(temp, list);
free(temp->name);
free(temp);
}
}
void channel_free(struct channel_t * channel)
{
struct user_t * iterator, * temp;
if (!channel) {
return;
}
temp = NULL;
LIST_FOREACH(iterator, &channel->user_list_head, list) {
if (temp) {
channel_remove_user(channel, temp->name);
}
temp = iterator;
}
if (temp) {
channel_remove_user(channel, temp->name);
}
free(channel->name);
free(channel);
}
#ifdef TEST_CHANNEL
void channel_print(struct channel_t * channel)
{
char ** iterator;
printf("Channel name: %s\n", channel->name);
printf("Channel users:\n");
for (iterator = channel->users; *iterator != NULL; iterator++) {
printf("%s\n", *iterator);
}
return;
}
int main(int argc, char *argv[])
{
struct channel_t * channel = channel_new("#archlinux-tr");
channel_add_user(channel, "firat");
channel_add_user(channel, "ahmet");
channel_add_user(channel, "mehmet");
channel_add_user(channel, "murat");
channel_remove_user(channel, "mehmet");
channel_remove_user(channel, "murat");
channel_remove_user(channel, "firat");
channel_remove_user(channel, "firat2");
channel_remove_user(channel, "ahmet");
channel_print(channel);
channel_free(channel);
return 0;
}
#endif