View Javadoc
1   /*
2    * Licensed under the Apache License, Version 2.0 (the "License");
3    * you may not use this file except in compliance with the License.
4    * You may obtain a copy of the License at
5    *
6    * http://www.apache.org/licenses/LICENSE-2.0
7    *
8    * Unless required by applicable law or agreed to in writing, software
9    * distributed under the License is distributed on an "AS IS" BASIS,
10   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11   * See the License for the specific language governing permissions and
12   * limitations under the License.
13   */
14  package com.addthis.codec.binary;
15  
16  import java.io.ByteArrayOutputStream;
17  import java.io.IOException;
18  import java.io.OutputStream;
19  
20  import java.util.Stack;
21  
22  import com.addthis.basis.util.Bytes;
23  
24  final class BufferOut {
25  
26      ByteArrayOutputStream        out;
27      Stack<ByteArrayOutputStream> stack;
28  
29      BufferOut() {
30          stack = new Stack<>();
31          push();
32      }
33  
34      public OutputStream out() {
35          return out;
36      }
37  
38      public void push() {
39          stack.push(new ByteArrayOutputStream());
40          out = stack.peek();
41      }
42  
43      public void pop() throws IOException {
44          ByteArrayOutputStream last = stack.pop();
45          out = stack.peek();
46          Bytes.writeLength(last.size(), out());
47          last.writeTo(out());
48      }
49  
50      @Override
51      public String toString() {
52          return "BufferOut:" + (out != null ? out.size() : -1);
53      }
54  }