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 public String toString() {
057 return new String(buffer, 0, index);
058 }
059
060 public String toString(String charsetName)
061 throws UnsupportedEncodingException {
062
063 return new String(buffer, 0, index, charsetName);
064 }
065
066 public byte[] unsafeGetByteArray() {
067 return buffer;
068 }
069
070 public ByteBuffer unsafeGetByteBuffer() {
071 return ByteBuffer.wrap(buffer, 0, index);
072 }
073
074 public void write(byte[] byteArray) {
075 write(byteArray, 0, byteArray.length);
076 }
077
078 public void write(byte[] byteArray, int offset, int length) {
079 if (length <= 0) {
080 return;
081 }
082
083 int newIndex = index + length;
084
085 if (newIndex > buffer.length) {
086 int newBufferSize = Math.max(buffer.length << 1, newIndex);
087
088 byte[] newBuffer = new byte[newBufferSize];
089
090 System.arraycopy(buffer, 0, newBuffer, 0, index);
091
092 buffer = newBuffer;
093 }
094
095 System.arraycopy(byteArray, offset, buffer, index, length);
096
097 index = newIndex;
098 }
099
100 public void write(int b) {
101 int newIndex = index + 1;
102
103 if (newIndex > buffer.length) {
104 int newBufferSize = Math.max(buffer.length << 1, newIndex);
105
106 byte[] newBuffer = new byte[newBufferSize];
107
108 System.arraycopy(buffer, 0, newBuffer, 0, buffer.length);
109
110 buffer = newBuffer;
111 }
112
113 buffer[index] = (byte)b;
114
115 index = newIndex;
116 }
117
118 public void writeTo(OutputStream outputStream) throws IOException {
119 outputStream.write(buffer, 0, index);
120 }
121
122 protected byte[] buffer;
123 protected int index;
124
125 }