Class ChoiceCodec<V>

java.lang.Object
io.bytestreams.codec.core.ChoiceCodec<V>
Type Parameters:
V - the base type of the discriminated union
All Implemented Interfaces:
Codec<V>, Inspectable<V>

public class ChoiceCodec<V> extends Object implements Codec<V>, Inspectable<V>
A codec for discriminated unions where a class tag determines which codec to use for the value.

The wire format is [tag][value], where the tag selects among registered alternatives. This codec only sees Codec<Class<? extends V>> — callers typically create it by using xmap(Converter) to map a tag codec to class values:


 BiMap<Integer, Class<? extends Shape>> tags = BiMap.of(
     Map.entry(1, Circle.class),
     Map.entry(2, Rectangle.class));

 Codec<Shape> codec = Codecs.<Shape>choice(Codecs.uint8().xmap(tags))
     .on(Circle.class, circleCodec)
     .on(Rectangle.class, rectangleCodec)
     .build();
 
  • Method Details

    • encode

      public EncodeResult encode(V value, OutputStream output) throws IOException
      Description copied from interface: Codec
      Encodes the given value and writes it to the output stream.
      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
      Description copied from interface: Codec
      Decodes a value from the input stream.
      Specified by:
      decode in interface Codec<V>
      Parameters:
      input - the input stream to read the encoded bytes from
      Returns:
      the decoded value
      Throws:
      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)