-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDataBuffer.java
More file actions
111 lines (64 loc) · 2.09 KB
/
Copy pathDataBuffer.java
File metadata and controls
111 lines (64 loc) · 2.09 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
package tinyTCPServer.net;
public class DataBuffer {
private byte[] bf_ = null;
private int readBeginIdx_ = 0;
private int writeBeginIdx_ = 0;
public DataBuffer(int size) {
this.bf_ = new byte[size];
}
public int dataSize() {
return this.writeBeginIdx_ - this.readBeginIdx_;
}
public byte[] retrieveAllData() {
byte[] data = new byte[this.dataSize()];
System.arraycopy(this.bf_, this.readBeginIdx_, data, 0, this.dataSize());
this.reset();
return data;
}
public void setWriteIdx(int idx) {
this.writeBeginIdx_ = idx;
}
public void setReadIdx(int idx) {
this.readBeginIdx_ = idx;
}
public void reset() {
this.writeBeginIdx_ = 0;
this.readBeginIdx_ = 0;
}
public void append(byte[] bytes) {
int capcity = this.bf_.length - this.writeBeginIdx_;
if (capcity >= bytes.length) {
System.arraycopy(bytes, 0, this.bf_, this.writeBeginIdx_,
bytes.length);
this.writeBeginIdx_ = this.writeBeginIdx_ + bytes.length;
return;
} else {
int oldContentLen = this.writeBeginIdx_ - this.readBeginIdx_;
int totalEmptySize = this.bf_.length - oldContentLen;
int deltaSize = totalEmptySize - bytes.length;
if (deltaSize >= 0) {
// have enough place to handle the new content ,
// but need to adjust/move the buffer data then append the new
// data to the end
byte[] newBuff = new byte[this.bf_.length];
System.arraycopy(this.bf_, this.readBeginIdx_, newBuff, 0,
oldContentLen);
System.arraycopy(bytes, 0, newBuff, oldContentLen, bytes.length);
this.readBeginIdx_ = 0;
this.writeBeginIdx_ = this.readBeginIdx_ + oldContentLen
+ bytes.length;
this.bf_ = newBuff;
} else {
// Policy: enlarge the buffer size to double
int requireSize = (this.bf_.length + Math.abs(deltaSize)) * 2;
byte[] newBuff = new byte[requireSize];
System.arraycopy(this.bf_, 0, newBuff, 0, oldContentLen);
System.arraycopy(bytes, 0, newBuff, 0, bytes.length);
this.readBeginIdx_ = 0;
this.writeBeginIdx_ = this.readBeginIdx_ + oldContentLen
+ bytes.length;
this.bf_ = newBuff;
}
}
}
}