-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.c
126 lines (97 loc) · 2.63 KB
/
common.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
#include "common.h"
int recv_all(int sockfd, void *buffer, size_t len) {
size_t bytes_received = 0;
char *buff = buffer;
while (bytes_received < len) {
int bytes = recv(sockfd, buff + bytes_received, len - bytes_received, 0);
if (bytes <= 0) {
if (bytes == 0) // connection closed
break;
else // error
return bytes;
}
bytes_received += bytes;
}
return bytes_received;
}
int send_all(int sockfd, void *buffer, size_t len) {
size_t bytes_sent = 0;
char *buff = buffer;
while (bytes_sent < len) {
int bytes = send(sockfd, buff + bytes_sent, len - bytes_sent, 0);
if (bytes <= 0) {
return bytes; // error
}
bytes_sent += bytes;
}
return bytes_sent;
}
// Returns the head of the topic_list with the topic inserted
struct double_list *addTopic(struct double_list *head, char *topic) {
if (head == NULL) {
head = malloc(sizeof(struct double_list));
head->next = NULL;
head->prev = NULL;
strcpy(head->topic, topic);
return head;
}
struct double_list *curr = head;
// topic at the start already
if (strcmp(curr->topic, topic) == 0) {
return head;
}
// topic somewhere in the middle already
while (curr->next != NULL) {
if (strcmp(curr->topic, topic) == 0) {
return head;
}
curr = curr->next;
}
// topic at the end already
if (strcmp(curr->topic, topic) == 0) {
return head;
}
struct double_list *newTopic = malloc(sizeof(struct double_list));
curr->next = newTopic;
newTopic->prev = curr;
newTopic->next = NULL;
strcpy(newTopic->topic, topic);
return head;
}
// Returns the head of the topic_list with the topic deleted
struct double_list *deleteTopic(struct double_list *head, char *topic) {
if (head == NULL) {
return NULL; // no list, no problem
}
struct double_list *curr;
// topic at the start
if (strcmp(head->topic, topic) == 0) {
if (head->next == NULL) { // no other topic
free(head);
return NULL;
} else { // replace head
curr = head->next; // curr is new head
curr->prev = NULL;
free(head);
return curr;
}
}
curr = head->next;
while (curr != NULL) {
if (strcmp(curr->topic, topic) == 0) { // curr needs to be removed
if (curr->next == NULL) { // curr is last
curr->prev->next = NULL;
free(curr);
return head;
} else { // curr is somewhere in the middle
curr->prev->next = curr->next;
curr->next->prev = curr->prev;
free(curr);
return head;
}
}
curr = curr->next;
}
// topic does not exist so we return the list unaffected
return head;
}