Class VariableByteLengthCodec<V>

java.lang.Object
io.bytestreams.codec.core.VariableByteLengthCodec<V>
Type Parameters:
V - the type of value this codec handles
All Implemented Interfaces:
Codec<V>, Inspectable<V>

public class VariableByteLengthCodec<V> extends Object implements Codec<V>, Inspectable<V>
A codec for variable-length values where the byte count is encoded as a prefix.

The lengthCodec encodes and decodes the byte count of the value. On encode, the value is first written to a buffer to determine its byte size, then the byte count prefix is written followed by the buffered value bytes. On decode, the byte count prefix is decoded, that many bytes are read into a bounded buffer, and the value is decoded from the buffer.

Example usage:


 Codec<String> varString = Codecs.prefixed(Codecs.uint16(), stringCodec);
 Codec<byte[]> varBinary = Codecs.prefixed(Codecs.uint16(), binaryCodec);
 
  • Method Details

    • encode

      public EncodeResult encode(V value, OutputStream output) throws IOException
      Encodes the given value and writes it to the output stream.

      Encodes the value to a buffer first, then writes the byte count prefix followed by the buffered value bytes.

      Specified by:
      encode in interface Codec<V>
      Parameters:
      value - the value to encode
      output - the output stream to write the encoded bytes to
      Returns:
      the encode result containing logical count and bytes written
      Throws:
      IOException - if an I/O error occurs during encoding
    • decode

      public V decode(InputStream input) throws IOException
      Decodes a value from the input stream.

      First decodes the byte count prefix, then reads that many bytes from the input and decodes the value from the bounded byte array.

      Specified by:
      decode in interface Codec<V>
      Parameters:
      input - the input stream to read the encoded bytes from
      Returns:
      the decoded value
      Throws:
      EOFException - if the stream ends before the length or value is fully read
      IOException - if an I/O error occurs during decoding
    • inspect

      public Object inspect(V value)
      Description copied from interface: Inspectable
      Returns a structured representation of the given value.
      Specified by:
      inspect in interface Inspectable<V>
      Parameters:
      value - the decoded value to inspect
      Returns:
      a structured representation (Map, List, or scalar)