-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathstream_buffer.cpp
More file actions
151 lines (117 loc) · 2.25 KB
/
Copy pathstream_buffer.cpp
File metadata and controls
151 lines (117 loc) · 2.25 KB
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
140
141
142
143
144
145
146
147
148
149
150
151
#include "stream_buffer.h"
#include <string.h>
#include <stdio.h>
using namespace ydx;
int StreamBuffer::alloc(uint64_t size)
{
data_ = ::malloc(size + 1);
size_ = size;
if(data_ == NULL)
return -1;
else
return 0;
}
void StreamBuffer::copy_in(const void *data, uint64_t len)
{
uint64_t l;
l = MIN(len, ((size_ + 1) - in_));
memcpy((char*)data_ + in_, data, l);
memcpy(data_, (char*)data + l, len - l);
}
void StreamBuffer::copy_out(void *buf, uint64_t len)
{
uint64_t l;
l = MIN(len, ((size_ + 1) - out_));
memcpy(buf, (char*)data_ + out_, l);
memcpy((char*)buf + l, data_, len - l);
}
uint64_t StreamBuffer::copy_in_must(const void *data, uint64_t len)
{
uint64_t l = unused();
if( len > l || data == NULL)
return 0;
copy_in(data, len);
in_ = (in_ + len) % (size_ + 1);
return len;
}
uint64_t StreamBuffer::copy_out_must(void* buf, uint64_t len)
{
uint64_t l = used();
if( len > l || buf == NULL )
return 0;
copy_out(buf, len);
out_ = (out_ + len) % (size_ + 1);
return len;
}
uint64_t StreamBuffer::peek_out_must(void* buf, uint64_t len)
{
uint64_t l;
l = used();
if(len > l)
{
return 0;
}
if(buf)
{
copy_out(buf, len);
}
return len;
}
bool StreamBuffer::has_writen(uint64_t len)
{
if(len > unused())
{
return false;
}
in_ = (in_ + len) % (size_ + 1);
return true;
}
bool StreamBuffer::has_read(uint64_t len)
{
if(len > used())
return false;
out_ = (out_ + len) % (size_ + 1);
return true;
}
bool StreamBuffer::write_buffer(const void* buf, int len)
{
uint64_t totb = len + sizeof(int);
if(unused() < totb)
{
return false;
}
uint64_t inb;
inb = copy_in_must((void *)&len, sizeof(int));
inb += copy_in_must(buf, len);
if(inb != totb)
{
printf("write_buffer error..\n");
return false;
}
return true;
}
bool StreamBuffer::read_buffer(void* buf, int &len)
{
//读取消息头部的4个字节长度,len会修正为一个消息的正确长度
if(!peek_out_must((void *)&len, sizeof(int)))
{
len = 0;
return false;
}
uint64_t totb = len + sizeof(int);
if(used() < totb)
{
len = 0;
return false;
}
uint64_t outb = 0;
if(has_read(sizeof(int)))
outb += sizeof(int);
outb += copy_out_must(buf, len);
if(outb != totb)
{
printf("read_buffer error..\n");
return false;
}
return true;
}