com.anaptecs.jeaf.workload.proxy.ByteBufferOutputStream Maven / Gradle / Ivy
/**
* Copyright 2004 - 2021 anaptecs GmbH, Burgstr. 96, 72764 Reutlingen, Germany
*
* All rights reserved.
*/
package com.anaptecs.jeaf.workload.proxy;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import com.anaptecs.jeaf.xfun.api.checks.Check;
/**
* Class implements an {@link OutputStream} using {@link ByteBuffer}. This class is part of a set of classes that try to
* implement a low garbage approach when working with streams. This class requires that the amount of data that should
* be written is known before we start writing to the stream.
*
* @author JEAF Development Team
*/
public class ByteBufferOutputStream extends OutputStream {
/**
* The buffer where data is stored.
*/
protected ByteBuffer byteBuffer;
/**
* Initialize object using the byte buffer that was passed as parameter. This method is intended to be used in cases
* where byte buffers are pooled in order to avoid garbage.
*
* @param pByteBuffer Byte buffer that should be used to store data that is send to to stream. The parameter must not
* be null.
*/
public ByteBufferOutputStream( ByteBuffer pByteBuffer ) {
// Check parameter
Check.checkInvalidParameterNull(pByteBuffer, "pByteBuffer");
byteBuffer = pByteBuffer;
}
/**
* Method writes the passed int as byte to the stream. According to specification from {@link OutputStream#write(int)}
* the upper 24 bit of the int are ignored ( means we will downcast int to byte).
*
* @param pByte int
that will be written as byte
to the stream.
*/
@Override
public void write( int pByte ) {
// According to specification we have to ignore the upper 24 bits of the int. So we just downcast it to an int.
byteBuffer.put((byte) pByte);
}
/**
* Method writes the passed amount of bytes from the passed array to the stream starting an the given position.
*
* @param pBytes Source array. The parameter must not be null.
* @param pOffset Offset from the source array where we should start with copying the data.
* @param pLength Amount of bytes that should be written.
*/
@Override
public void write( byte[] pBytes, int pOffset, int pLength ) {
byteBuffer.put(pBytes, pOffset, pLength);
}
/**
* Method returns the {@link ByteBuffer} that was used to store the data that was written to the stream.
*
* @return {@link ByteBuffer} Reference to byte buffer that was used to write the data that was send to this stream.
* This is the same object as the one that was passed when the stream was created. The method never returns null.
*/
public ByteBuffer getByteBuffer( ) {
return byteBuffer;
}
}