Trait vtubestudio::codec::MessageCodec

source ·
pub trait MessageCodec {
    type Input;
    type Output;
    type Error;

    // Required methods
    fn decode(msg: Self::Input) -> Result<Option<String>, Self::Error>;
    fn encode(text: String) -> Self::Output;
}
Expand description

A trait describing how to encode/decode a websocket message. This is provided to allow users to use their own websocket library instead of the default one.

Typically the Input and Output message types will be the same, but they’re defined separately to allow for flexibility (e.g., if the underlying websocket client uses distinct types for sending vs receiving, like validating UTF-8 only for outgoing messages).

§Example

use vtubestudio::codec::MessageCodec;

// Custom websocket message type
pub enum Message {
    Text(String),
    Binary(Vec<u8>),
    Ping(Vec<u8>),
    Pong(Vec<u8>),
    Close,
}

#[derive(Debug, Clone)]
pub struct MyCustomMessageCodec;

impl MessageCodec for MyCustomMessageCodec {
    type Input = Message;
    type Output = Message;
    type Error = std::convert::Infallible;

    fn decode(msg: Self::Input) -> Result<Option<String>, Self::Error> {
        Ok(match msg {
            Message::Text(s) => Some(s),
            _ => None,
        })
    }

    fn encode(text: String) -> Self::Output {
        Message::Text(text)
    }
}

Required Associated Types§

source

type Input

The underlying incoming message type.

source

type Output

The underlying outgoing message type.

source

type Error

Error type returned on decode failure.

Required Methods§

source

fn decode(msg: Self::Input) -> Result<Option<String>, Self::Error>

Decodes a websocket text message. None values are ignored (E.g., for disregarding ping messages).

source

fn encode(text: String) -> Self::Output

Converts a string into a websocket text message.

Object Safety§

This trait is not object safe.

Implementors§