001
014
015 package com.liferay.portal.kernel.io.unsync;
016
017 import java.io.IOException;
018 import java.io.OutputStream;
019 import java.io.UnsupportedEncodingException;
020
021 import java.nio.ByteBuffer;
022
023
030 public class UnsyncByteArrayOutputStream extends OutputStream {
031
032 public UnsyncByteArrayOutputStream() {
033 this(32);
034 }
035
036 public UnsyncByteArrayOutputStream(int size) {
037 buffer = new byte[size];
038 }
039
040 public void reset() {
041 index = 0;
042 }
043
044 public int size() {
045 return index;
046 }
047
048 public byte[] toByteArray() {
049 byte[] newBuffer = new byte[index];
050
051 System.arraycopy(buffer, 0, newBuffer, 0, index);
052
053 return newBuffer;
054 }
055
056 @Override
057 public String toString() {
058 return new String(buffer, 0, index);
059 }
060
061 public String toString(String charsetName)
062 throws UnsupportedEncodingException {
063
064 return new String(buffer, 0, index, charsetName);
065 }
066
067 public byte[] unsafeGetByteArray() {
068 return buffer;
069 }
070
071 public ByteBuffer unsafeGetByteBuffer() {
072 return ByteBuffer.wrap(buffer, 0, index);
073 }
074
075 @Override
076 public void write(byte[] bytes) {
077 write(bytes, 0, bytes.length);
078 }
079
080 @Override
081 public void write(byte[] bytes, int offset, int length) {
082 if (length <= 0) {
083 return;
084 }
085
086 int newIndex = index + length;
087
088 if (newIndex > buffer.length) {
089 int newBufferSize = Math.max(buffer.length << 1, newIndex);
090
091 byte[] newBuffer = new byte[newBufferSize];
092
093 System.arraycopy(buffer, 0, newBuffer, 0, index);
094
095 buffer = newBuffer;
096 }
097
098 System.arraycopy(bytes, offset, buffer, index, length);
099
100 index = newIndex;
101 }
102
103 @Override
104 public void write(int b) {
105 int newIndex = index + 1;
106
107 if (newIndex > buffer.length) {
108 int newBufferSize = Math.max(buffer.length << 1, newIndex);
109
110 byte[] newBuffer = new byte[newBufferSize];
111
112 System.arraycopy(buffer, 0, newBuffer, 0, buffer.length);
113
114 buffer = newBuffer;
115 }
116
117 buffer[index] = (byte)b;
118
119 index = newIndex;
120 }
121
122 public void writeTo(OutputStream outputStream) throws IOException {
123 outputStream.write(buffer, 0, index);
124 }
125
126 protected byte[] buffer;
127 protected int index;
128
129 }