Class ByteStringOutputStream

java.lang.Object
java.io.OutputStream
org.apache.pekko.http.impl.util.ByteStringOutputStream
All Implemented Interfaces:
Closeable, Flushable, AutoCloseable

public final class ByteStringOutputStream extends OutputStream
INTERNAL API

An OutputStream that buffers into a byte array like ByteArrayOutputStream but that hands the buffered data over as a pekko.util.ByteString without copying it, unlike ByteArrayOutputStream.toByteArray which always creates a copy, and whose writes are not synchronized: every user is a single stage that owns the stream, and the per-call monitor was a measurable share of the cost of encoding an HPACK header block.

After a hand-over the stream is empty again and can be reused for the next block of data.

Not thread-safe.

Derived from the ByteStringOutputStream in Apache Pekko gRPC (https://github.com/apache/pekko-grpc/pull/862).

  • Constructor Details

    • ByteStringOutputStream

      public ByteStringOutputStream(int initialCapacity)
  • Method Details

    • array

      public byte[] array()
      The array backing the buffered data. Only valid until the next write, reserve or hand-over, any of which may replace it.
      Returns:
      (undocumented)
    • reserve

      public int reserve(int length)
      Reserves length bytes at the end of the buffered data for the caller to fill in directly.

      Parameters:
      length - (undocumented)
      Returns:
      the position in array() at which the reserved bytes start
    • size

      public int size()
      The number of bytes written since the last hand-over.
    • takeByteString

      public org.apache.pekko.util.ByteString takeByteString()
      Hands the buffered data over as a ByteString and leaves the stream empty for the next block.

      When most of the buffer is used the ByteString wraps the array without copying and the stream starts a fresh array for the next block; when only a small part is used the data is copied so the ByteString does not retain a large, mostly unused array, and the stream keeps its array.

      Returns:
      (undocumented)
    • write

      public void write(int b)
      Specified by:
      write in class OutputStream
    • write

      public void write(byte[] bytes, int offset, int length)
      Overrides:
      write in class OutputStream