View Javadoc

1   /*
2    *  Licensed to the Apache Software Foundation (ASF) under one
3    *  or more contributor license agreements.  See the NOTICE file
4    *  distributed with this work for additional information
5    *  regarding copyright ownership.  The ASF licenses this file
6    *  to you under the Apache License, Version 2.0 (the
7    *  "License"); you may not use this file except in compliance
8    *  with the License.  You may obtain a copy of the License at
9    *
10   *    http://www.apache.org/licenses/LICENSE-2.0
11   *
12   *  Unless required by applicable law or agreed to in writing,
13   *  software distributed under the License is distributed on an
14   *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   *  KIND, either express or implied.  See the License for the
16   *  specific language governing permissions and limitations
17   *  under the License.
18   *
19   */
20  package org.apache.mina.util;
21  
22  import java.io.OutputStream;
23  import java.nio.ByteBuffer;
24  
25  /**
26   * {@link OutputStream} wrapper for {@link ByteBuffer}
27   * 
28   * <p>
29   * <i>Currently this class is only used and available in MINA's codec module</i>
30   * </p>
31   * 
32   * @author <a href="http://mina.apache.org">Apache MINA Project</a>
33   * 
34   */
35  public class ByteBufferOutputStream extends OutputStream {
36      private ByteBuffer buffer;
37  
38      private boolean elastic = false;
39  
40      public ByteBufferOutputStream() {
41          this(1024);
42      }
43  
44      private ByteBufferOutputStream(ByteBuffer buffer) {
45          this.buffer = buffer;
46      }
47  
48      public ByteBufferOutputStream(int initialSize) {
49          this(ByteBuffer.allocate(initialSize));
50      }
51  
52      public ByteBuffer getByteBuffer() {
53          ByteBuffer out = buffer.asReadOnlyBuffer();
54          out.limit(out.position());
55          out.position(0);
56  
57          return out;
58      }
59  
60      public boolean isElastic() {
61          return elastic;
62      }
63  
64      private void needSpace(int len) {
65          if (elastic && buffer.capacity() - buffer.position() < len) {
66              ByteBuffer newBuffer = ByteBuffer.allocate(Math.max(buffer.capacity() * 2, buffer.position() + len));
67              buffer.limit(buffer.position());
68              newBuffer.put(buffer);
69              buffer = newBuffer;
70          }
71      }
72  
73      public void setElastic(boolean elastic) {
74          this.elastic = elastic;
75      }
76  
77      @Override
78      public void write(byte[] b, int off, int len) {
79          needSpace(len);
80          buffer.put(b, off, len);
81      }
82  
83      @Override
84      public void write(int b) {
85          needSpace(1);
86          buffer.put((byte) b);
87      }
88  }