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 (requiressimdfeature)MsgPackCodec- MessagePack binary format (requiresmsgpackfeature)
Required Methods§
Sourcefn decode<T: DeserializeOwned>(&self, bytes: &[u8]) -> CodecResult<T>
fn decode<T: DeserializeOwned>(&self, bytes: &[u8]) -> CodecResult<T>
Decode bytes to a value
Sourcefn content_type(&self) -> &'static str
fn content_type(&self) -> &'static str
Get the content type for this codec (e.g., “application/json”)
Provided Methods§
Sourcefn supports_streaming(&self) -> bool
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.