Skip to main content

Codec

Trait Codec 

Source
pub trait Codec: Send + Sync {
    // Required methods
    fn encode<T: Serialize>(&self, value: &T) -> CodecResult<Vec<u8>>;
    fn decode<T: DeserializeOwned>(&self, bytes: &[u8]) -> CodecResult<T>;
    fn content_type(&self) -> &'static str;
    fn name(&self) -> &'static str;

    // Provided method
    fn supports_streaming(&self) -> bool { ... }
}
Expand description

Wire format codec trait

This trait abstracts over different serialization formats, allowing pluggable encoding/decoding while maintaining type safety.

§Send + Sync Bounds

The Send + Sync bounds are required because codecs are typically shared across multiple threads/tasks in multi-threaded runtimes (tokio, async-std). This enables:

  • Concurrent encoding/decoding: Multiple tasks can use the codec simultaneously
  • Zero-copy sharing: Codec instances can be wrapped in Arc and shared cheaply
  • Thread-safe initialization: Codec configuration is immutable after creation

§WASM Implications

On WASM targets (single-threaded), these bounds are automatically satisfied since all types are Send + Sync by default in single-threaded environments. The trait bounds don’t add overhead on WASM - they’re purely compile-time constraints that prevent accidental use of non-thread-safe types on native platforms.

§Implementors

  • JsonCodec - Standard JSON encoding (default)
  • SimdJsonCodec - SIMD-accelerated JSON (requires simd feature)
  • MsgPackCodec - MessagePack binary format (requires msgpack feature)

Required Methods§

Source

fn encode<T: Serialize>(&self, value: &T) -> CodecResult<Vec<u8>>

Encode a value to bytes

Source

fn decode<T: DeserializeOwned>(&self, bytes: &[u8]) -> CodecResult<T>

Decode bytes to a value

Source

fn content_type(&self) -> &'static str

Get the content type for this codec (e.g., “application/json”)

Source

fn name(&self) -> &'static str

Get codec name for debugging

Provided Methods§

Source

fn supports_streaming(&self) -> bool

Check if this codec supports streaming

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§

Source§

impl Codec for JsonCodec

Source§

impl Codec for MsgPackCodec

Available on crate feature msgpack only.
Source§

impl Codec for SimdJsonCodec

Available on crate feature simd only.