1 /*
   2  * reserved comment block
   3  * DO NOT REMOVE OR ALTER!
   4  */
   5 /*
   6  * Copyright 1999-2010 The Apache Software Foundation.
   7  *
   8  *  Licensed under the Apache License, Version 2.0 (the "License");
   9  *  you may not use this file except in compliance with the License.
  10  *  You may obtain a copy of the License at
  11  *
  12  *      http://www.apache.org/licenses/LICENSE-2.0
  13  *
  14  *  Unless required by applicable law or agreed to in writing, software
  15  *  distributed under the License is distributed on an "AS IS" BASIS,
  16  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17  *  See the License for the specific language governing permissions and
  18  *  limitations under the License.
  19  *
  20  */
  21 package com.sun.org.apache.xml.internal.security.utils;
  22 
  23 import java.io.OutputStream;
  24 
  25 /**
  26  * A simple Unsynced ByteArrayOutputStream
  27  * @author raul
  28  *
  29  */
  30 public class UnsyncByteArrayOutputStream extends OutputStream  {
  31     private static final int INITIAL_SIZE = 8192;
  32     private static ThreadLocal<byte[]> bufCache = new ThreadLocal<byte[]>() {
  33         protected synchronized byte[] initialValue() {
  34             return new byte[INITIAL_SIZE];
  35         }
  36     };
  37 
  38     private byte[] buf;
  39     private int size = INITIAL_SIZE;
  40     private int pos = 0;
  41 
  42     public UnsyncByteArrayOutputStream() {
  43         buf = bufCache.get();
  44     }
  45 
  46     public void write(byte[] arg0) {
  47         int newPos = pos + arg0.length;
  48         if (newPos > size) {
  49             expandSize(newPos);
  50         }
  51         System.arraycopy(arg0, 0, buf, pos, arg0.length);
  52         pos = newPos;
  53     }
  54 
  55     public void write(byte[] arg0, int arg1, int arg2) {
  56         int newPos = pos + arg2;
  57         if (newPos > size) {
  58             expandSize(newPos);
  59         }
  60         System.arraycopy(arg0, arg1, buf, pos, arg2);
  61         pos = newPos;
  62     }
  63 
  64     public void write(int arg0) {
  65         int newPos = pos + 1;
  66         if (newPos > size) {
  67             expandSize(newPos);
  68         }
  69         buf[pos++] = (byte)arg0;
  70     }
  71 
  72     public byte[] toByteArray() {
  73         byte result[] = new byte[pos];
  74         System.arraycopy(buf, 0, result, 0, pos);
  75         return result;
  76     }
  77 
  78     public void reset() {
  79         pos = 0;
  80     }
  81 
  82     private void expandSize(int newPos) {
  83         int newSize = size;
  84         while (newPos > newSize) {
  85             newSize = newSize<<2;
  86         }
  87         byte newBuf[] = new byte[newSize];
  88         System.arraycopy(buf, 0, newBuf, 0, pos);
  89         buf = newBuf;
  90         size = newSize;
  91     }
  92 }