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