1 /*
2 * Copyright 2007-2008 The Kuali Foundation
3 *
4 * Licensed under the Educational Community License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.opensource.org/licenses/ecl2.php
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.kuali.rice.kns.util.cache;
17
18 import java.io.InputStream;
19 import java.io.OutputStream;
20
21 /**
22 * ByteArrayOutputStream implementation that doesn't synchronize methods
23 * and doesn't copy the data on toByteArray().
24 */
25 public class FastByteArrayOutputStream extends OutputStream {
26 /**
27 * Buffer and size
28 */
29 protected byte[] buf = null;
30 protected int size = 0;
31
32 /**
33 * Constructs a stream with buffer capacity size 5K
34 */
35 public FastByteArrayOutputStream() {
36 this(5 * 1024);
37 }
38
39 /**
40 * Constructs a stream with the given initial size
41 */
42 public FastByteArrayOutputStream(int initSize) {
43 this.size = 0;
44 this.buf = new byte[initSize];
45 }
46
47 /**
48 * Ensures that we have a large enough buffer for the given size.
49 */
50 private void verifyBufferSize(int sz) {
51 if (sz > buf.length) {
52 byte[] old = buf;
53 buf = new byte[Math.max(sz, 2 * buf.length )];
54 System.arraycopy(old, 0, buf, 0, old.length);
55 old = null;
56 }
57 }
58
59 public int getSize() {
60 return size;
61 }
62
63 /**
64 * Returns the byte array containing the written data. Note that this
65 * array will almost always be larger than the amount of data actually
66 * written.
67 */
68 public byte[] getByteArray() {
69 return buf;
70 }
71
72 public final void write(byte b[]) {
73 verifyBufferSize(size + b.length);
74 System.arraycopy(b, 0, buf, size, b.length);
75 size += b.length;
76 }
77
78 public final void write(byte b[], int off, int len) {
79 verifyBufferSize(size + len);
80 System.arraycopy(b, off, buf, size, len);
81 size += len;
82 }
83
84 public final void write(int b) {
85 verifyBufferSize(size + 1);
86 buf[size++] = (byte) b;
87 }
88
89 public void reset() {
90 size = 0;
91 }
92
93 /**
94 * Returns a ByteArrayInputStream for reading back the written data
95 */
96 public InputStream getInputStream() {
97 return new FastByteArrayInputStream(buf, size);
98 }
99
100 }