Skip to main content

Codec

Trait Codec 

Source
pub trait Codec: Sized {
    // Provided methods
    fn encode(&self) -> String
       where Self: Serialize { ... }
    fn encode_result(&self) -> Result<String, WsError>
       where Self: Serialize { ... }
    fn decode(s: &str) -> Result<Self, WsError>
       where Self: DeserializeOwned { ... }
}
Expand description

Trait for encoding/decoding WebSocket messages.

The default blanket implementation uses JSON via serde_json.

§Example

use ws_kit::codec::Codec;
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct Msg { text: String }

let msg = Msg { text: "hello".into() };
let s = msg.encode();
let decoded = Msg::decode(&s).unwrap();
assert_eq!(msg, decoded);

Provided Methods§

Source

fn encode(&self) -> String
where Self: Serialize,

Encode self into a JSON string.

This implementation serializes via serde_json::to_string. Panics are avoided — if serialization fails the error is surfaced through WsError::InvalidMessage in the Result variant. The infallible encode variant below unwraps for convenience; use Codec::encode_result when you need error handling.

Source

fn encode_result(&self) -> Result<String, WsError>
where Self: Serialize,

Encode with error handling.

Source

fn decode(s: &str) -> Result<Self, WsError>
where Self: DeserializeOwned,

Decode Self from a JSON string.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§

Source§

impl<T> Codec for T

Blanket implementation for all serde types.