-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.c
139 lines (121 loc) · 2.92 KB
/
util.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
#include "util.h"
//Linked list functions
int ll_get_length(LLnode * head)
{
LLnode * tmp;
int count = 1;
if (head == NULL)
return 0;
else
{
tmp = head->next;
while (tmp != head)
{
count++;
tmp = tmp->next;
}
return count;
}
}
void ll_append_node(LLnode ** head_ptr,
void * value)
{
LLnode * prev_last_node;
LLnode * new_node;
LLnode * head;
if (head_ptr == NULL)
{
return;
}
//Init the value pntr
head = (*head_ptr);
new_node = (LLnode *) malloc(sizeof(LLnode));
new_node->value = value;
//The list is empty, no node is currently present
if (head == NULL)
{
(*head_ptr) = new_node;
new_node->prev = new_node;
new_node->next = new_node;
}
else
{
//Node exists by itself
prev_last_node = head->prev;
head->prev = new_node;
prev_last_node->next = new_node;
new_node->next = head;
new_node->prev = prev_last_node;
}
}
LLnode * ll_pop_node(LLnode ** head_ptr)
{
LLnode * last_node;
LLnode * new_head;
LLnode * prev_head;
prev_head = (*head_ptr);
if (prev_head == NULL)
{
return NULL;
}
last_node = prev_head->prev;
new_head = prev_head->next;
//We are about to set the head ptr to nothing because there is only one thing in list
if (last_node == prev_head)
{
(*head_ptr) = NULL;
prev_head->next = NULL;
prev_head->prev = NULL;
return prev_head;
}
else
{
(*head_ptr) = new_head;
last_node->next = new_head;
new_head->prev = last_node;
prev_head->next = NULL;
prev_head->prev = NULL;
return prev_head;
}
}
void ll_destroy_node(LLnode * node)
{
if (node->type == llt_string)
{
free((char *) node->value);
}
free(node);
}
//Compute the difference in usec for two timeval objects
long timeval_usecdiff(struct timeval *start_time,
struct timeval *finish_time)
{
long usec;
usec=(finish_time->tv_sec - start_time->tv_sec)*1000000;
usec+=(finish_time->tv_usec- start_time->tv_usec);
return usec;
}
//Print out messages entered by the user
void print_cmd(Cmd * cmd)
{
fprintf(stderr, "src=%d, dst=%d, message=%s\n",
cmd->src_id,
cmd->dst_id,
cmd->message);
}
char * convert_frame_to_char(Frame * frame)
{
//TODO: You should implement this as necessary
char* char_buf = (char*)malloc(MAX_FRAME_SIZE);
memset(char_buf, 0, MAX_FRAME_SIZE);
memcpy(char_buf, frame, MAX_FRAME_SIZE);
return char_buf;
}
Frame * convert_char_to_frame(char * char_buf)
{
//TODO: You should implement this as necessary
Frame* frame = (Frame*)malloc(MAX_FRAME_SIZE);
memset(frame, 0, MAX_FRAME_SIZE);
memcpy(frame, char_buf, MAX_FRAME_SIZE);
return frame;
}