Class VariableItemLengthCodec<V>

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

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

The lengthCodec encodes and decodes the item count. The codecFactory creates a codec for the given item count, handling both encoding and decoding. Unlike VariableByteLengthCodec, this codec does not buffer the encoded value; it writes directly to the output stream.

Example usage:


 // String with code point count prefix
 Codec<String> string = Codecs.utf8(Codecs.uint8());

 // List with item count prefix
 Codec<List<Foo>> list = Codecs.prefixed(Codecs.uint16(),
     List::size,
     length -> Codecs.listOf(length, fooCodec));
 
  • Method Details

    • encode

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

      Computes the item count using lengthOf, writes the count prefix, then encodes the value directly using a codec created by codecFactory.

      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.

      Decodes the item count prefix, then decodes the value using a codec created by codecFactory.

      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)