Class ReusableByteBuffer

java.lang.Object
java.io.OutputStream
net.logstash.logback.util.ReusableByteBuffer
All Implemented Interfaces:
Closeable, Flushable, AutoCloseable

public class ReusableByteBuffer extends OutputStream
A speedy alternative to ByteArrayOutputStream.

Unlike ByteArrayOutputStream, this implementation is backed by an ArrayList of byte[] instead of 1 constantly resizing byte[] array. It does not copy buffers when it gets expanded.

The initial buffer is only created when the stream is first written. There is also no copying of the internal buffer if its contents is extracted with the writeTo(OutputStream) method.

The reset() method clears the content and resets the buffer to its initial state. Buffers are disposed except the initial buffer which is reused by subsequent usage.

This class is *not* thread-safe!

Note: This class is for internal use only and subject to backward incompatible change at any time.

Author:
brenuart
  • Constructor Details

    • ReusableByteBuffer

      public ReusableByteBuffer()
      Create a new ReusableByteBuffer with the default initial capacity of 1024 bytes.
    • ReusableByteBuffer

      public ReusableByteBuffer(int initialCapacity)
      Create a new ReusableByteBuffer with the specified initial capacity.
      Parameters:
      initialCapacity - the initial buffer size in bytes
  • Method Details

    • write

      public void write(int datum) throws IOException
      Specified by:
      write in class OutputStream
      Throws:
      IOException
    • write

      public void write(byte[] data, int offset, int length) throws IOException
      Overrides:
      write in class OutputStream
      Throws:
      IOException
    • close

      public void close()
      Specified by:
      close in interface AutoCloseable
      Specified by:
      close in interface Closeable
      Overrides:
      close in class OutputStream
    • size

      public int size()
      Return the current size of the buffer.
      Returns:
      the current size of the buffer.
    • reset

      public void reset()
      Reset the contents of this ReusableByteBuffer.

      All currently accumulated output in the output stream is discarded. The output stream can be used again.

    • writeTo

      public void writeTo(OutputStream out) throws IOException
      Write the buffers content to the given OutputStream.
      Parameters:
      out - the OutputStream to write to
      Throws:
      IOException - in case of problems writing into the output stream
    • toByteArray

      public byte[] toByteArray()
      Creates a newly allocated byte array.

      Its size is the current size of this output stream and the valid contents of the buffer have been copied into it.

      Returns:
      the current contents of this output stream, as a byte array.
      See Also: