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§
Sourcefn encode(&self) -> Stringwhere
Self: Serialize,
fn encode(&self) -> Stringwhere
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.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".
Implementors§
impl<T> Codec for Twhere
T: Serialize + DeserializeOwned,
Blanket implementation for all serde types.