1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.buffer;
17
18 import java.io.DataOutput;
19 import java.io.DataOutputStream;
20 import java.io.IOException;
21 import java.io.OutputStream;
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37 public class ChannelBufferOutputStream extends OutputStream implements DataOutput {
38
39 private final ChannelBuffer buffer;
40 private final int startIndex;
41 private final DataOutputStream utf8out = new DataOutputStream(this);
42
43
44
45
46 public ChannelBufferOutputStream(ChannelBuffer buffer) {
47 if (buffer == null) {
48 throw new NullPointerException("buffer");
49 }
50 this.buffer = buffer;
51 startIndex = buffer.writerIndex();
52 }
53
54
55
56
57 public int writtenBytes() {
58 return buffer.writerIndex() - startIndex;
59 }
60
61 @Override
62 public void write(byte[] b, int off, int len) throws IOException {
63 if (len == 0) {
64 return;
65 }
66
67 buffer.writeBytes(b, off, len);
68 }
69
70 @Override
71 public void write(byte[] b) throws IOException {
72 buffer.writeBytes(b);
73 }
74
75 @Override
76 public void write(int b) throws IOException {
77 buffer.writeByte((byte) b);
78 }
79
80 public void writeBoolean(boolean v) throws IOException {
81 write(v? (byte) 1 : (byte) 0);
82 }
83
84 public void writeByte(int v) throws IOException {
85 write(v);
86 }
87
88 public void writeBytes(String s) throws IOException {
89 int len = s.length();
90 for (int i = 0; i < len; i ++) {
91 write((byte) s.charAt(i));
92 }
93 }
94
95 public void writeChar(int v) throws IOException {
96 writeShort((short) v);
97 }
98
99 public void writeChars(String s) throws IOException {
100 int len = s.length();
101 for (int i = 0 ; i < len ; i ++) {
102 writeChar(s.charAt(i));
103 }
104 }
105
106 public void writeDouble(double v) throws IOException {
107 writeLong(Double.doubleToLongBits(v));
108 }
109
110 public void writeFloat(float v) throws IOException {
111 writeInt(Float.floatToIntBits(v));
112 }
113
114 public void writeInt(int v) throws IOException {
115 buffer.writeInt(v);
116 }
117
118 public void writeLong(long v) throws IOException {
119 buffer.writeLong(v);
120 }
121
122 public void writeShort(int v) throws IOException {
123 buffer.writeShort((short) v);
124 }
125
126 public void writeUTF(String s) throws IOException {
127 utf8out.writeUTF(s);
128 }
129
130
131
132
133 public ChannelBuffer buffer() {
134 return buffer;
135 }
136 }