Class ChoiceCodec<T,V>

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

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

The wire format is [tag][value]. Each alternative is registered once, as a tag, a class and a codec, so the two directions cannot disagree:

Codec<Shape> codec = Codecs.<Integer, Shape>choice(Codecs.uint8())
    .on(1, Circle.class, circleCodec)
    .on(2, Rectangle.class, rectangleCodec)
    .build();

Decoding dispatches on the decoded tag; encoding dispatches on the value's exact runtime class. The choice codec reads and writes the tag in every case, registered or not, so it never rewinds and places no requirement on the stream. An unrecognised tag or class throws a CodecException unless a fallback is registered with ChoiceCodec.Builder.otherwise(Class, Function, Function).

Tags must not be arrays: array equality is by identity, so a decoded tag would never match a registered one. Use a String tag — Codecs.ascii(int) — for character codes.

  • 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<T>
      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<T>
      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<T>
      Parameters:
      value - the decoded value to inspect
      Returns:
      a structured representation (Map, List, or scalar)