-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbuffer.h
102 lines (83 loc) · 1.97 KB
/
buffer.h
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
/*
* buffer.h
*
* Created on: 2011-11-3
* Author: gxl2007@hotmail.com
*/
#ifndef BUFFER_H_
#define BUFFER_H_
namespace xlnet
{
/*
* @brief data buffer which have independent read and write pointer ,
* caller must keep data and pointer correct
* linear buffer, not circular, when space is greater than 1/4 , it'll memory move.
*/
class buffer
{
public:
buffer();
~buffer();
/*
* @brief initialize and alloc memory
* @param [in] memory size
* @return 0 on success , -1 on failed
*/
int init(int size) ;
/*
* @brief free memroy
*/
void fini() ;
/*
* @brief resize memory
*/
int resize(int size) ;
/*
* @brief move data when read pointer > 1/4 total memory
*/
void adjust() ;
int capacity() const { return m_end - m_begin ; } ;
/*
* @brief data pointer for read
*/
char* data() { return m_data ; } ;
int data_size() const { return m_space - m_data ; } ;
/*
* @brief data ponter for write
*/
char* space() { return m_space ; } ;
int space_size() const { return m_end - m_space ; } ;
/*
* @brief move write pointer after shift in data
*/
int push_data(int count)
{
if(count < 1 || count > space_size() ) return -1 ;
m_space += count ;
return 0 ;
}
/*
* @brief move read pointer after shift out data
*/
int pop_data(int count)
{
if(count < 1 || count > data_size() ) return -1 ;
m_data += count ;
if(m_data == m_space ) m_data = m_space = m_begin ;
return 0 ;
}
/*
* @brief clean up
*/
void clear() { m_data = m_space = m_begin ; } ;
private:
buffer(const buffer&) ;
buffer& operator=(const buffer&) ;
private:
char* m_begin ;
char* m_end ;
char* m_data ;
char* m_space ;
};
}
#endif /* BUFFER_H_ */