Interface Codec<I,O>

Type Parameters:
I - input type (encoding source, decoding target) | 输入类型(编码源、解码目标)
O - output type (encoding target, decoding source) | 输出类型(编码目标、解码源)

public interface Codec<I,O>
Generic Codec Interface - Reversible encoding and decoding with composition support 通用编解码接口 - 支持可逆编解码和组合

A codec encodes values of type I to type O and decodes back. Codecs are composable via andThen(Codec) to build encoding pipelines.

编解码器将类型 I 的值编码为类型 O,并可解码还原。 编解码器可通过 andThen(Codec) 组合构建编码管道。

Usage Examples | 使用示例:

Codec<byte[], String> base64 = OpenCodec.base64();
String encoded = base64.encode(data);
byte[] decoded = base64.decode(encoded);

// Composition - 组合
Codec<byte[], String> combined = codecA.andThen(codecB);

Contract | 契约:

  • Roundtrip: decode(encode(x)).equals(x) must hold - 往返: 编码后解码必须还原
  • Null-safety: null input throws NullPointerException - 空值安全: null 输入抛出 NPE
  • Thread-safety: implementations must be thread-safe - 线程安全: 实现必须线程安全
Since:
JDK 25, opencode-base-core V1.0.3
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Method Summary

    Modifier and Type
    Method
    Description
    default <R> Codec<I,R>
    andThen(Codec<O,R> after)
    Composes this codec with another, creating a pipeline: this encodes first, then after 将此编解码器与另一个组合,创建管道:先由此编码,再由 after 编码
    decode(O output)
    Decodes the encoded value back to the original type 将编码值解码还原为原始类型
    encode(I input)
    Encodes the input value 编码输入值
  • Method Details

    • encode

      O encode(I input)
      Encodes the input value 编码输入值
      Parameters:
      input - the value to encode | 要编码的值
      Returns:
      the encoded value | 编码后的值
      Throws:
      NullPointerException - if input is null | 如果输入为 null
    • decode

      I decode(O output)
      Decodes the encoded value back to the original type 将编码值解码还原为原始类型
      Parameters:
      output - the value to decode | 要解码的值
      Returns:
      the decoded value | 解码后的值
      Throws:
      NullPointerException - if output is null | 如果输入为 null
      IllegalArgumentException - if the input is malformed | 如果输入格式错误
    • andThen

      default <R> Codec<I,R> andThen(Codec<O,R> after)
      Composes this codec with another, creating a pipeline: this encodes first, then after 将此编解码器与另一个组合,创建管道:先由此编码,再由 after 编码

      For codecs A (I→M) and B (M→O), A.andThen(B) produces codec C (I→O) where:

      • C.encode(x) == B.encode(A.encode(x))
      • C.decode(y) == A.decode(B.decode(y))
      Type Parameters:
      R - the final output type | 最终输出类型
      Parameters:
      after - the codec to apply after this one | 在此之后应用的编解码器
      Returns:
      a composed codec | 组合后的编解码器
      Throws:
      NullPointerException - if after is null | 如果 after 为 null