001: package com.jofti.util;
002:
003: import java.io.OutputStream;
004:
005: import java.io.IOException;
006:
007: import java.io.InputStream;
008:
009: import java.io.ByteArrayInputStream;
010:
011: /**
012:
013: * ByteArrayOutputStream implementation that doesn't synchronize methods
014:
015: * and doesn't copy the data on toByteArray().
016:
017: */
018:
019: public class FastByteArrayOutputStream extends OutputStream {
020:
021: /**
022:
023: * Buffer and size
024:
025: */
026:
027: protected byte[] buf = null;
028:
029: protected int size = 0;
030:
031: public int realSize = 0;
032:
033: protected int initSize = 0;
034:
035: /**
036:
037: * Constructs a stream with the given initial size
038:
039: */
040:
041: public FastByteArrayOutputStream(int initSize) {
042:
043: this .size = 0;
044: this .initSize = initSize;
045: this .buf = new byte[initSize];
046:
047: }
048:
049: /**
050:
051: * Ensures that we have a large enough buffer for the given size.
052:
053: */
054:
055: private void verifyBufferSize(int sz) {
056:
057: if (sz > buf.length) {
058:
059: byte[] old = buf;
060:
061: buf = new byte[Math.max(sz, buf.length + (buf.length / 2))];
062:
063: System.arraycopy(old, 0, buf, 0, old.length);
064:
065: old = null;
066:
067: }
068:
069: }
070:
071: public int getSize() {
072:
073: return size;
074:
075: }
076:
077: /**
078:
079: * Returns the byte array containing the written data. Note that this
080:
081: * array will almost always be larger than the amount of data actually
082:
083: * written.
084:
085: */
086:
087: public byte[] getByteArray() {
088:
089: return buf;
090:
091: }
092:
093: public final void write(byte b[]) {
094:
095: verifyBufferSize(size + b.length);
096:
097: System.arraycopy(b, 0, buf, size, b.length);
098:
099: size += b.length;
100:
101: realSize += b.length;
102:
103: }
104:
105: public final void write(byte b[], int off, int len) {
106:
107: verifyBufferSize(size + len);
108:
109: System.arraycopy(b, off, buf, size, len);
110:
111: size += len;
112:
113: realSize += len;
114:
115: }
116:
117: public final void write(int b) {
118:
119: verifyBufferSize(size + 1);
120:
121: buf[size++] = (byte) b;
122:
123: realSize++;
124:
125: }
126:
127: public void reset() {
128:
129: // if (buf.length >initSize){
130: // buf = new byte[initSize];
131: // }
132: //
133: //keep the headers here
134: size = 4;
135: realSize = 4;
136:
137: }
138:
139: }
|