-
Notifications
You must be signed in to change notification settings - Fork 7
/
vector_fd.c
94 lines (75 loc) · 1.62 KB
/
vector_fd.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
#include <stdio.h>
#include <malloc.h>
#include <assert.h>
#include <memory.h>
#include <stdlib.h>
#include "vector_fd.h"
#define ENLAGE_NR 5
#define DEFALT_FD_NR 5
#define DEFALT_VECTOR_NR 1
/* 动态创建一个保存客户端连接的容器 */
VectorFD* create_vector_fd(void)
{
VectorFD *vfd = (VectorFD *)calloc(DEFALT_VECTOR_NR, sizeof(VectorFD));
assert(vfd != NULL);
vfd->fd = (int *)calloc(DEFALT_FD_NR, sizeof(int));
assert(vfd->fd != NULL);
vfd->counter = 0;
vfd->max_counter = 0;
return vfd;
}
void destory_vector_fd(VectorFD *vfd)
{
assert(vfd != NULL);
free(vfd->fd);
free(vfd);
}
int get_fd(VectorFD *vfd, int index)
{
assert(vfd != NULL);
if (index < 0 || index > vfd->counter - 1)
return 0;
return vfd->fd[index];
}
static int indexof(VectorFD *vfd, int fd)
{
int i;
for (i = 0; i < vfd->counter; i++)
if (vfd->fd[i] == fd)
return i;
return -1;
}
void remove_fd(VectorFD *vfd, int fd)
{
int index;
int i;
assert(vfd != NULL);
index = indexof(vfd, fd);
if (index == -1)
return;
/* 后面的覆盖需要删除的fd即可 */
for (i = index; i < vfd->counter - 1; i++)
vfd->fd[i] = vfd->fd[i+1];
vfd->counter--;
}
/* 动态扩大容器的大小 */
static void encapacity(VectorFD *vfd)
{
int *fds;
if (vfd->counter >= vfd->max_counter)
{
fds = (int *)calloc(vfd->counter + ENLAGE_NR, sizeof(int));
assert(fds != NULL);
memcpy(fds, vfd->fd, sizeof(int) * vfd->counter);
free(vfd->fd);
vfd->fd = fds;
vfd->max_counter += ENLAGE_NR;
}
}
/* 添加fd到容器中 */
void add_fd(VectorFD *vfd, int fd)
{
assert(vfd != NULL);
encapacity(vfd);
vfd->fd[vfd->counter++] = fd;
}