-
Notifications
You must be signed in to change notification settings - Fork 0
/
channel.c
84 lines (77 loc) · 2.54 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
#include <stdio.h>
#include <stdlib.h>
#include "channel.h"
struct channel *create_channel(int delay, double pe)
{
struct channel *ch = malloc(sizeof(struct channel));
ch->delay = delay;
ch->pe = pe;
ch->queue = calloc(delay+1, sizeof(void*));
return ch;
}
void free_channel(struct channel *chnl)
{
free(chnl->queue);
free(chnl);
chnl = NULL;
}
// Return whether the packet will be erased. If erased, it's the
// caller's responsibility to free the packet, as we have no idea
// about the packet's implementation (we always treat it as void)
int send_to_channel(struct channel *chnl, void *packet, int t)
{
int queue_len = chnl->delay + 1;
int lost = 0;
int pos = (t+chnl->delay) % queue_len; // where to put the packet in the queue
if (chnl->queue[pos] != NULL) {
free(chnl->queue[pos]); // Warning: there might be memory leak here, but don't care it
}
if (rand() % 10000 <= chnl->pe * 10000) {
lost = 1;
chnl->queue[pos] = NULL;
// printf("Element sent at time %d is lost\n", t);
} else {
chnl->queue[pos] = packet;
}
return lost;
}
void *recv_from_channel(struct channel *chnl, int t)
{
if (t < chnl->delay) {
return NULL;
}
int queue_len = chnl->delay + 1;
int pos = t % queue_len; // where to pick the packet in the queue
void *out = chnl->queue[pos];
chnl->queue[pos] = NULL;
return out;
}
// Modify channel characteristics
// Important to realloc memory for queue, and arrange stored elements according to time
void modify_channel(struct channel *chnl, int t, int newdelay, double newpe)
{
if (newdelay != chnl->delay) {
void **newqueue = calloc(newdelay+1, sizeof(void *));
int newqueue_len = newdelay + 1;
int olddelay = chnl->delay;
int oldqueue_len = chnl->delay + 1;
if (newdelay < olddelay) {
for (int i=0; i<=newdelay; i++) {
int newpos = (t - i + newdelay) % newqueue_len;
int oldpos = (t - i + olddelay) % oldqueue_len;
newqueue[newpos] = chnl->queue[oldpos];
}
} else {
for (int i=0; i<=olddelay; i++) {
int newpos = (t - i + newdelay) % newqueue_len;
int oldpos = (t - i + olddelay) % oldqueue_len;
newqueue[newpos] = chnl->queue[oldpos];
}
}
void **tmp = chnl->queue;
chnl->queue = newqueue;
chnl->delay = newdelay;
free(tmp);
}
chnl->pe = newpe;
}