-
Notifications
You must be signed in to change notification settings - Fork 2
/
WriteBuffer.java
102 lines (95 loc) · 2.41 KB
/
WriteBuffer.java
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
/**
* WriteBuffer Class
* Written By: Mitchell Pomery (21130887)
* Buffers either bit or byte data and writes it out in bulk amounts
* Also pads bit data nicely.
**/
import java.io.OutputStream;
import java.io.IOException;
class WriteBuffer {
int pos = 0; //the number of bits in the buffer
boolean[] buffer = new boolean[8];
byte[] outStream = new byte[12288];
int outLength = 0; //the number of bytes waiting to be written
OutputStream out;
boolean booleandata = true; //If we are expecting bits
/**
* Constructs WriteBuffer for writing to the output stream
* @param out the output stream to write to
* @param bitdata wether or not we are expecting bit data
**/
public WriteBuffer(OutputStream out, boolean bitdata) {
this.out = out;
booleandata = bitdata;
}
/**
* write bit data to the output stream
* @param b bit data to write
**/
public void write(boolean[] b) throws IOException{
if (booleandata) {
for (int i = 0; i < b.length; i++) {
buffer[pos] = b[i];
pos++;
if (pos > 7) {
//character |= 0x80;
byte character = BitByteConverter.booleanArrayToByte(buffer);
pos -= 8;
outStream[outLength] = character;
outLength++;
}
if (outLength > 12200) {
out.write(outStream, 0, outLength);
outLength = 0;
}
}
}
}
/**
* write an array of bytes to the output stream
* @param b byte array to write
**/
public void write(byte[] b) throws IOException{
if (!booleandata) {
for (int i = 0; i < b.length; i++) {
outStream[outLength] = b[i];
outLength++;
if (outLength > 12200) {
out.write(outStream, 0, outLength);
outLength = 0;
}
}
}
}
/**
* write a single byte to the output stream
* @param b byte to write
**/
public void write(byte b) throws IOException{
if (!booleandata) {
outStream[outLength] = b;
outLength++;
if (outLength > 12200) {
out.write(outStream, 0, outLength);
outLength = 0;
}
}
}
/**
* pads the final output with 0's and writes to the output stream
* then puts 1 however many times 0 was used to pad in the previous8 bits
**/
public void flush() throws IOException{
if (booleandata) {
boolean[] padding = new boolean[8 + (8 - pos)];
int poscopy = pos;
while (poscopy < 8) {
padding[padding.length - (poscopy + 1)] = true;
poscopy++;
}
write(padding);
}
out.write(outStream, 0, outLength);
outLength = 0;
}
}