-
Notifications
You must be signed in to change notification settings - Fork 0
/
channel.c
141 lines (123 loc) · 2.63 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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "user.h"
#include "channel.h"
#include "utils.h"
/** Channel head */
static struct channel_t *head = 0;
/**
* @brief Print all channels
*
*/
void list_channels() {
struct channel_t* curr = head;
while(curr) {
printf("[Channel %p] name=%s, next=%p\n", curr, curr->name, curr->next);
curr = curr->next;
}
}
/**
* @brief Does channel exist in channel linked-list
*
* @param channel
* @return int
*/
int has_channel(struct channel_t* channel) {
struct channel_t* curr = head;
while(curr) {
if(strcmp(curr->name, channel->name) == 0) {
return 1;
}
curr = curr->next;
}
return 0;
}
/**
* @brief Create a channel object
*
* @param name
* @return struct channel_t*
*/
struct channel_t* create_channel(char* name) {
struct channel_t* channel = malloc(sizeof(struct channel_t));
sprintf(channel->name, "%s", name);
channel->next = 0;
return channel;
}
/**
* @brief Add channel to the top of channel linked-list
*
* @param name
* @return struct channel_t*
*/
struct channel_t* add_channel(char* name) {
struct channel_t* channel = create_channel(name);
channel->next = head;
head = channel;
return channel;
}
/**
* @brief Remove channel and relink channel linked-list
*
* @param channel
*/
void remove_channel(struct channel_t* channel) {
if(!strcmp(head->name, channel->name)) {
struct channel_t* tmp = head;
head = head->next;
return;
}
struct channel_t* curr = head;
struct channel_t* prev = head;
while(curr) {
if(!strcmp(curr->name, channel->name)) {
prev->next = curr->next;
break;
}
prev = curr;
curr = curr->next;
}
}
/**
* @brief Get the channel object
*
* @param name
* @return struct channel_t*
*/
struct channel_t* get_channel(char* name) {
struct channel_t* curr = head;
while(curr) {
if(strcmp(curr->name, name) == 0) {
return curr;
}
curr = curr->next;
}
return 0;
}
/**
* @brief Remove channel from channel linked-list and free channel object
*
* @param channel
* @return int
*/
int destroy_channel(struct channel_t* channel) {
remove_channel(channel);
free(channel);
return 1;
}
/**
* @brief Destroy all channels from memory
*
*/
void destroy_channels() {
struct channel_t* curr = head;
int size = 0;
while(curr) {
struct channel_t* tmp = curr;
curr = curr->next;
destroy_channel(tmp);
size++;
}
printf("Destroyed %d channels\n", size);
}