/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2000, 2010 Oracle and/or its affiliates. All rights reserved. * */ package com.sleepycat.util; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; /** * A replacement for ByteArrayOutputStream that does not synchronize every * byte read. * *
This class extends {@link OutputStream} and its write()
* methods allow it to be used as a standard output stream. In addition, it
* provides writeFast()
methods that are not declared to throw
* IOException
. IOException
is never thrown by this
* class.
write(int) but does not throw
* IOException
.
* @see #write(int)
*/
public final void writeFast(int b) {
if (len + 1 > buf.length)
bump(1);
buf[len++] = (byte) b;
}
/**
* Equivalent to write(byte[]) but does not throw
* IOException
.
* @see #write(byte[])
*/
public final void writeFast(byte[] fromBuf) {
int needed = len + fromBuf.length - buf.length;
if (needed > 0)
bump(needed);
System.arraycopy(fromBuf, 0, buf, len, fromBuf.length);
len += fromBuf.length;
}
/**
* Equivalent to write(byte[],int,int) but does not throw
* IOException
.
* @see #write(byte[],int,int)
*/
public final void writeFast(byte[] fromBuf, int offset, int length) {
int needed = len + length - buf.length;
if (needed > 0)
bump(needed);
System.arraycopy(fromBuf, offset, buf, len, length);
len += length;
}
/**
* Returns the buffer owned by this object.
*
* @return the buffer.
*/
public byte[] getBufferBytes() {
return buf;
}
/**
* Returns the offset of the internal buffer.
*
* @return always zero currently.
*/
public int getBufferOffset() {
return 0;
}
/**
* Returns the length used in the internal buffer, i.e., the offset at
* which data will be written next.
*
* @return the buffer length.
*/
public int getBufferLength() {
return len;
}
/**
* Ensure that at least the given number of bytes are available in the
* internal buffer.
*
* @param sizeNeeded the number of bytes desired.
*/
public void makeSpace(int sizeNeeded) {
int needed = len + sizeNeeded - buf.length;
if (needed > 0)
bump(needed);
}
/**
* Skip the given number of bytes in the buffer.
*
* @param sizeAdded number of bytes to skip.
*/
public void addSize(int sizeAdded) {
len += sizeAdded;
}
private void bump(int needed) {
/* Double the buffer if the bumpLen is zero. */
int bump = (bumpLen > 0) ? bumpLen : buf.length;
byte[] toBuf = new byte[buf.length + needed + bump];
System.arraycopy(buf, 0, toBuf, 0, len);
buf = toBuf;
}
}