-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstream.c
121 lines (107 loc) · 2.29 KB
/
stream.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
#include "stream.h"
struct _Stream_Data
{
uint8_t *data;
size_t data_size;
struct list_head link;
};
Stream *stream_new(int64_t stream_id)
{
Stream *s = (Stream *)malloc(sizeof(Stream));
s->id = stream_id;
init_list_head(&s->buffer);
init_list_head(&s->link);
s->sent_offset = 0;
s->acked_offset = 0;
return s;
}
void stream_free(Stream *s)
{
if (!s)
return;
struct list_head *el, *el1;
list_for_each_safe(el, el1, &s->buffer)
{
Stream_Data *sd = list_entry(el, Stream_Data, link);
list_del(el);
free(sd->data);
free(sd);
}
free(s);
}
void stream_free_list(struct list_head *streams)
{
if (!streams)
return;
struct list_head *el, *el1;
list_for_each_safe(el, el1, streams)
{
list_del(el);
Stream *stream = list_entry(el, Stream, link);
if (stream)
stream_free(stream);
}
}
struct list_head *stream_get_link(Stream *s)
{
return &s->link;
}
int64_t stream_get_id(Stream *s)
{
return s->id;
}
int stream_push_data(Stream *s, uint8_t *data, size_t data_size)
{
Stream_Data *sd = (Stream_Data *)malloc(sizeof(Stream_Data));
sd->data = data;
sd->data_size = data_size;
init_list_head(&sd->link);
list_add_tail(&sd->link, &s->buffer);
return 0;
}
Stream *stream_get_by_id(struct list_head *streams, int64_t stream_id)
{
struct list_head *el, *el1;
list_for_each_safe(el, el1, streams)
{
Stream *stream = list_entry(el, Stream, link);
if (stream_get_id(stream) == stream_id)
return stream;
}
return NULL;
}
uint8_t *stream_peek_data(Stream *s, size_t *data_size)
{
size_t start_offset = s->sent_offset - s->acked_offset;
size_t offset = 0;
struct list_head *el, *el1;
list_for_each_safe(el, el1, &s->buffer)
{
Stream_Data *sd = list_entry(el, Stream_Data, link);
if (start_offset - offset < sd->data_size)
{
*data_size = sd->data_size - (start_offset - offset);
return sd->data + (start_offset - offset);
}
offset += sd->data_size;
}
*data_size = 0;
return NULL;
}
void stream_mark_sent(Stream *s, size_t offset)
{
s->sent_offset += offset;
}
void stream_mark_acked(Stream *s, size_t offset)
{
struct list_head *el, *el1;
list_for_each_safe(el, el1, &s->buffer)
{
Stream_Data *sd = list_entry(el, Stream_Data, link);
if (s->acked_offset + sd->data_size > offset)
break;
s->acked_offset += sd->data_size;
list_del(el);
free(sd);
}
}