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
38
39
40
41
42 public class ChannelBufferOutputStream extends OutputStream implements DataOutput {
43
44 private final ChannelBuffer buffer;
45 private final int startIndex;
46 private final DataOutputStream utf8out = new DataOutputStream(this);
47
48
49
50
51 public ChannelBufferOutputStream(ChannelBuffer buffer) {
52 if (buffer == null) {
53 throw new NullPointerException("buffer");
54 }
55 this.buffer = buffer;
56 startIndex = buffer.writerIndex();
57 }
58
59
60
61
62 public int writtenBytes() {
63 return buffer.writerIndex() - startIndex;
64 }
65
66 @Override
67 public void write(byte[] b, int off, int len) throws IOException {
68 if (len == 0) {
69 return;
70 }
71
72 buffer.writeBytes(b, off, len);
73 }
74
75 @Override
76 public void write(byte[] b) throws IOException {
77 buffer.writeBytes(b);
78 }
79
80 @Override
81 public void write(int b) throws IOException {
82 buffer.writeByte((byte) b);
83 }
84
85 public void writeBoolean(boolean v) throws IOException {
86 write(v? (byte) 1 : (byte) 0);
87 }
88
89 public void writeByte(int v) throws IOException {
90 write(v);
91 }
92
93 public void writeBytes(String s) throws IOException {
94 int len = s.length();
95 for (int i = 0; i < len; i ++) {
96 write((byte) s.charAt(i));
97 }
98 }
99
100 public void writeChar(int v) throws IOException {
101 writeShort((short) v);
102 }
103
104 public void writeChars(String s) throws IOException {
105 int len = s.length();
106 for (int i = 0 ; i < len ; i ++) {
107 writeChar(s.charAt(i));
108 }
109 }
110
111 public void writeDouble(double v) throws IOException {
112 writeLong(Double.doubleToLongBits(v));
113 }
114
115 public void writeFloat(float v) throws IOException {
116 writeInt(Float.floatToIntBits(v));
117 }
118
119 public void writeInt(int v) throws IOException {
120 buffer.writeInt(v);
121 }
122
123 public void writeLong(long v) throws IOException {
124 buffer.writeLong(v);
125 }
126
127 public void writeShort(int v) throws IOException {
128 buffer.writeShort((short) v);
129 }
130
131 public void writeUTF(String s) throws IOException {
132 utf8out.writeUTF(s);
133 }
134
135
136
137
138 public ChannelBuffer buffer() {
139 return buffer;
140 }
141 }